diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 000000000..82492e8f8 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "10.0.13", + "commands": [ + "dotnet-ef" + ], + "rollForward": false + } + } +} diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..6e3e94a6c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,24 @@ +# The image is built from Directory.Build.props, SignKey.snk and src/ only (see Dockerfile). +**/bin/ +**/obj/ +**/*.user +.git/ +.vs/ +.config/ +.devcontainer/ +.github/ +Packages/ +TestResults/ +tests/ +samples/ +docs/ + +# Local data and settings of a developer's run of src/BaGet: never in the image. +src/BaGet/appsettings.Overrides.json +src/BaGet/baget.db* +src/BaGet/catalog/ +src/BaGet/packages/ +src/BaGet/symbols/ +src/BaGet/staging/ +src/BaGet/logs/ +src/BaGet/Properties/launchSettings.json diff --git a/.editorconfig b/.editorconfig index df9dfe6ff..3879e6f27 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,6 +6,25 @@ indent_style = space charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion [*.{htm,html,js,ts,tsx,css,sass,scss,less,svg,vue}] indent_size = 2 @@ -53,7 +72,7 @@ dotnet_naming_style.pascal_case_style.capitalization = pascal_case # Use PascalCase for constant fields dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields -dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style dotnet_naming_symbols.constant_fields.applicable_kinds = field dotnet_naming_symbols.constant_fields.applicable_accessibilities = * dotnet_naming_symbols.constant_fields.required_modifiers = const @@ -94,3 +113,18 @@ csharp_space_between_method_call_empty_parameter_list_parentheses = false # Wrapping preferences csharp_preserve_single_line_statements = true csharp_preserve_single_line_blocks = true +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_namespace_declarations = block_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent diff --git a/.gitattributes b/.gitattributes index 87528b50b..3ce5cf440 100644 --- a/.gitattributes +++ b/.gitattributes @@ -50,4 +50,5 @@ *.dbproj text=auto *.sln text=auto eol=crlf -*.sh eol=lf \ No newline at end of file +*.sh eol=lf# UI contract snapshots are compared as text with LF line ends +tests/BaGet.Tests/Contracts/*.txt text eol=lf diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md index 6b30ddd26..bf87ed1dd 100644 --- a/.github/ISSUE_TEMPLATE/Bug_report.md +++ b/.github/ISSUE_TEMPLATE/Bug_report.md @@ -13,6 +13,9 @@ Steps to reproduce the behavior: 3. With these arguments '....' 4. See error +### Configuration +Database and storage provider, and `Accounts:Enabled`, `Feeds:EnableV2`, `Validation:Enabled` if not default. + ### Expected behavior A clear and concise description of what you expected to happen. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e439b8098..19974dcae 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -3,4 +3,9 @@ Summary of the changes (in less than 80 chars) * Detail 1 * Detail 2 -Addresses https://github.com/loic-sharma/BaGet/issues/123 +Addresses https://github.com/pieroviano/BaGet/issues/123 + +Checklist: + + * [ ] Tests pass: `dotnet test BaGet.sln -p:GeneratePackageOnBuild=false` + * [ ] A schema change has a migration in all four `BaGet.Database.*` projects diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 000000000..824d3eeb3 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,47 @@ +name: Docs + +# Builds the mkdocs site (mkdocs.yml, docs/) and deploys it to GitHub Pages on every push to main. +# Requires Settings > Pages > Source = "GitHub Actions". +on: + push: + branches: [ main ] + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +# One deployment at a time; a newer push replaces a queued one. +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - name: Install mkdocs + run: pip install mkdocs-material==9.8.0 + - name: Build + run: mkdocs build --strict -d site + env: + NO_MKDOCS_2_WARNING: 1 + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v4 + with: + path: site + + deploy: + needs: build + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 90c51c63c..0bda5df16 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,19 +10,27 @@ on: # Allows you to run this workflow manually from the Actions tab workflow_dispatch: +permissions: + contents: read + jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v7 - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v6 with: - dotnet-version: 3.1.x + dotnet-version: 10.0.x + # nuget.config lists ./Packages as a package source. Locally it is a symlink to a shared + # feed; in a clean checkout it does not exist, and restore fails with NU1301. + - name: Create the local package source + run: mkdir -p Packages - name: Restore dependencies - run: dotnet restore + run: dotnet restore BaGet.sln + # Directory.Build.props packs every project on build; CI only needs the binaries. - name: Build - run: dotnet build --no-restore + run: dotnet build BaGet.sln --no-restore -p:GeneratePackageOnBuild=false - name: Test - run: dotnet test --no-build --verbosity normal + run: dotnet test BaGet.sln --no-build --verbosity normal diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cfd2806cc..4731b12d3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,12 +6,15 @@ on: releaseVersion: description: 'Release version' required: true - default: '1.0.0-preview1' + default: '1.0.0' packageSource: description: 'Package source' required: true default: 'https://api.nuget.org/v3/index.json' +permissions: + contents: read + env: Version: ${{ github.event.inputs.releaseVersion }} PackageVersion: ${{ github.event.inputs.releaseVersion }} @@ -22,13 +25,16 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v7 - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v6 with: - dotnet-version: 3.1.x + dotnet-version: 10.0.x + # nuget.config lists ./Packages as a package source; it does not exist in a clean checkout. + - name: Create the local package source + run: mkdir -p Packages - name: Test - run: dotnet test --verbosity normal + run: dotnet test BaGet.sln --verbosity normal -p:GeneratePackageOnBuild=false release_zip: needs: verify @@ -36,15 +42,17 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v7 - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v6 with: - dotnet-version: 3.1.x + dotnet-version: 10.0.x + - name: Create the local package source + run: mkdir -p Packages - name: Publish - run: dotnet publish src/BaGet --configuration Release --output artifacts + run: dotnet publish src/BaGet --configuration Release --output artifacts -p:GeneratePackageOnBuild=false - name: Upload - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v7 with: name: BaGet path: artifacts @@ -55,36 +63,48 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v7 - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v6 with: - dotnet-version: 3.1.x + dotnet-version: 10.0.x + - name: Create the local package source + run: mkdir -p Packages + # Packing on build as well would pack every project twice. - name: Pack - run: dotnet pack --configuration Release --output artifacts + run: dotnet pack BaGet.sln --configuration Release --output artifacts -p:GeneratePackageOnBuild=false + # Inputs and secrets go through the environment, never into the script text. A .nupkg push + # also pushes its .snupkg, so the symbol packages are not listed separately. - name: Push - run: dotnet nuget push "*" -s ${{ github.event.inputs.packageSource }} -k ${{secrets.NUGET_API_KEY}} + run: dotnet nuget push "*.nupkg" --source "$PACKAGE_SOURCE" --api-key "$NUGET_API_KEY" --skip-duplicate working-directory: artifacts + env: + PACKAGE_SOURCE: ${{ github.event.inputs.packageSource }} + NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} release_docker_image: needs: verify name: Release Docker image to Docker Hub runs-on: ubuntu-latest + env: + # Repository variable DOCKER_IMAGE (e.g. "myorg/baget"); defaults to "/baget". + IMAGE: ${{ vars.DOCKER_IMAGE || format('{0}/baget', secrets.DOCKER_USERNAME) }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v7 - name: Log in to Docker Hub - uses: docker/login-action@v1 + uses: docker/login-action@v4 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Build and push Docker image - uses: docker/build-push-action@v2 + uses: docker/build-push-action@v7 with: context: . push: true + labels: org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} tags: | - loicsharma/baget:latest - loicsharma/baget:${{ github.event.inputs.releaseVersion }} + ${{ env.IMAGE }}:latest + ${{ env.IMAGE }}:${{ github.event.inputs.releaseVersion }} diff --git a/.gitignore b/.gitignore index 2cec84750..78a07fb56 100644 --- a/.gitignore +++ b/.gitignore @@ -162,6 +162,11 @@ PublishScripts/ **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ +# ... and except BaGet's own package-management Razor Pages, which live in a folder called +# Packages: the rule above matched them and left the Manage page untracked. +!src/BaGet.Identity/Pages/Packages/** +# ... and the Models/Packages folders of the Identity/Web projects (forms and view models). +!src/**/Models/Packages/** # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignoreable files @@ -272,3 +277,13 @@ __pycache__/ **/baget.db **/baget.db-shm **/baget.db-wal + +# BaGet host logs (Serilog file sink) +logs/ + +# BaGet host storage when Storage:Path is empty (the content root, e.g. src/BaGet under dotnet run / Visual Studio) +src/BaGet/catalog/ +src/BaGet/symbols/ +src/BaGet/staging/ +src/BaGet/validation/ +src/BaGet/repos/ diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index ccbe25d9e..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "version": "0.2.0", - "configurations": [ - { - "name": ".NET Core Launch (web)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/src/BaGet/bin/Debug/netcoreapp3.1/BaGet.dll", - "args": [], - "cwd": "${workspaceFolder}/src/BaGet", - "stopAtEntry": false, - "internalConsoleOptions": "openOnSessionStart", - "launchBrowser": { - "enabled": true, - "args": "${auto-detect-url}", - "windows": { - "command": "cmd.exe", - "args": "/C start ${auto-detect-url}" - }, - "osx": { - "command": "open" - }, - "linux": { - "command": "xdg-open" - } - }, - "env": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "sourceFileMap": { - "/Views": "${workspaceFolder}/Views" - } - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "processId": "${command:pickProcess}" - } - ] -} diff --git a/.vscode/tasks.json b/.vscode/tasks.json deleted file mode 100644 index d76e01779..000000000 --- a/.vscode/tasks.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "taskName": "build", - "command": "dotnet", - "type": "process", - "args": [ - "build", - "${workspaceFolder}/src/BaGet/BaGet.csproj" - ], - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file diff --git a/Acknowledgments.md b/Acknowledgments.md new file mode 100644 index 000000000..21e9fc702 --- /dev/null +++ b/Acknowledgments.md @@ -0,0 +1,7 @@ +## Acknowledgments + +This product is derived from [BaGet](https://github.com/loic-sharma/BaGet), originally developed by Loic Sharma. + +The original BaGet source code is licensed under the MIT License. The applicable copyright notices and license text are included in this distribution. + +This product is independently maintained and is not an official BaGet release. \ No newline at end of file diff --git a/BaGet.sln b/BaGet.sln index af6601d21..d9456164e 100644 --- a/BaGet.sln +++ b/BaGet.sln @@ -1,7 +1,6 @@ - Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29104.9 +# Visual Studio Version 18 +VisualStudioVersion = 18.7.11919.86 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet", "src\BaGet\BaGet.csproj", "{284366CB-C68F-473E-908A-50A382616AE0}" EndProject @@ -13,9 +12,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Core.Tests", "tests\B EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Tests", "tests\BaGet.Tests\BaGet.Tests.csproj", "{892A7A82-4283-4315-B7E5-6D5B70543000}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Src", "Src", "{26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{C237857D-AD8E-4C52-974F-6A8155BB0C18}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{C237857D-AD8E-4C52-974F-6A8155BB0C18}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Protocol", "src\BaGet.Protocol\BaGet.Protocol.csproj", "{A2D23427-9278-4D52-B31F-759212252832}" EndProject @@ -26,11 +25,16 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0B44364D-952B-497A-82E0-C9AAE94E0369}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig + .gitattributes = .gitattributes + .gitignore = .gitignore + build.ps1 = build.ps1 src\Directory.Build.props = src\Directory.Build.props + global.json = global.json + mkdocs.yml = mkdocs.yml nuget.config = nuget.config EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Web", "src\BaGet.Web\BaGet.Web.csproj", "{D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Web.V3", "src\BaGet.Web.V3\BaGet.Web.V3.csproj", "{D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Database.Sqlite", "src\BaGet.Database.Sqlite\BaGet.Database.Sqlite.csproj", "{EC5E6B2C-2494-40E8-8682-080BA580DDA7}" EndProject @@ -42,7 +46,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Database.PostgreSql", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Gcp", "src\BaGet.Gcp\BaGet.Gcp.csproj", "{D7D60BA0-FF7F-4B37-815C-74D487C5176E}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{DDEC0736-8169-4834-815E-B78E7CE612A4}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{DDEC0736-8169-4834-815E-B78E7CE612A4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Protocol.Samples.Tests", "samples\BaGet.Protocol.Samples.Tests\BaGet.Protocol.Samples.Tests.csproj", "{16B0D424-BB2F-4C0C-90B0-4F7955326ADF}" EndProject @@ -52,84 +56,679 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGetWebApplication", "samp EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Web.Tests", "tests\BaGet.Web.Tests\BaGet.Web.Tests.csproj", "{BEEAAA73-36CD-4178-9C9F-6D036586E7BF}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGet.Azure.Tests", "tests\BaGet.Azure.Tests\BaGet.Azure.Tests.csproj", "{493DE3CC-BE24-4206-88C6-7BDE7721EF10}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Catalog", "src\BaGet.Catalog\BaGet.Catalog.csproj", "{17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Web.V2", "src\BaGet.Web.V2\BaGet.Web.V2.csproj", "{6F4FBCFC-6887-4401-A0B7-A856C91011BA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Identity.Api", "src\BaGet.Identity.Api\BaGet.Identity.Api.csproj", "{C8689F3D-B2C3-4B67-B2D6-6727AD11103D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Validation", "src\BaGet.Validation\BaGet.Validation.csproj", "{E2D03D72-23F2-409E-B895-45BAEEC75768}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Database.Tests", "tests\BaGet.Database.Tests\BaGet.Database.Tests.csproj", "{C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{2AEF938A-36F0-49B4-868A-E062B2596A1B}" + ProjectSection(SolutionItems) = preProject + docs\access-control.md = docs\access-control.md + docs\admin-api.md = docs\admin-api.md + docs\configuration.md = docs\configuration.md + docs\custom-frontend.md = docs\custom-frontend.md + docs\devops-manual.md = docs\devops-manual.md + docs\docker-registry.md = docs\docker-registry.md + docs\formats.md = docs\formats.md + docs\high-availability.md = docs\high-availability.md + docs\howto.md = docs\howto.md + docs\index.md = docs\index.md + docs\installation-manual.md = docs\installation-manual.md + docs\maven-repositories.md = docs\maven-repositories.md + docs\npm-registry.md = docs\npm-registry.md + docs\remote-repositories.md = docs\remote-repositories.md + docs\replication.md = docs\replication.md + docs\repositories.md = docs\repositories.md + docs\retention.md = docs\retention.md + docs\scalar.md = docs\scalar.md + docs\ui-api.md = docs\ui-api.md + docs\ui-coverage.md = docs\ui-coverage.md + docs\user-manual.md = docs\user-manual.md + docs\virtual-repositories.md = docs\virtual-repositories.md + docs\vulnerability-scanning.md = docs\vulnerability-scanning.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "advanced", "advanced", "{4974D3C8-A572-426F-84A0-7EA7D087EADD}" + ProjectSection(SolutionItems) = preProject + docs\advanced\api.md = docs\advanced\api.md + docs\advanced\architecture.md = docs\advanced\architecture.md + docs\advanced\debugging.md = docs\advanced\debugging.md + docs\advanced\sdk.md = docs\advanced\sdk.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "import", "import", "{18E1CCF3-1808-4982-8D0B-D2BEE393F0C3}" + ProjectSection(SolutionItems) = preProject + docs\import\local-feeds.md = docs\import\local-feeds.md + docs\import\nugetorg.md = docs\import\nugetorg.md + docs\import\nugetserver.md = docs\import\nugetserver.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "installation", "installation", "{E3E95BD1-D4AC-4C30-B157-643C65F6CC0B}" + ProjectSection(SolutionItems) = preProject + docs\installation\aliyun.md = docs\installation\aliyun.md + docs\installation\aws.md = docs\installation\aws.md + docs\installation\azure.md = docs\installation\azure.md + docs\installation\docker.md = docs\installation\docker.md + docs\installation\gcp.md = docs\installation\gcp.md + docs\installation\iis-proxy.md = docs\installation\iis-proxy.md + docs\installation\local.md = docs\installation\local.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "vs", "vs", "{FBD25121-8133-4E7F-B2D0-1F82AF3E1082}" + ProjectSection(SolutionItems) = preProject + docs\vs\artifactory.md = docs\vs\artifactory.md + docs\vs\azure-artifacts.md = docs\vs\azure-artifacts.md + docs\vs\liget.md = docs\vs\liget.md + docs\vs\local-feeds.md = docs\vs\local-feeds.md + docs\vs\myget.md = docs\vs\myget.md + docs\vs\nexus.md = docs\vs\nexus.md + docs\vs\nugetorg.md = docs\vs\nugetorg.md + docs\vs\nugetserver.md = docs\vs\nugetserver.md + docs\vs\teamcity.md = docs\vs\teamcity.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docker", "Docker", "{E42EA236-EE31-4F3F-AF68-B91C8200B74D}" + ProjectSection(SolutionItems) = preProject + Dockerfile = Dockerfile + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Markdown", "Markdown", "{ED084C7A-713F-4B8E-9BA4-3C54F9AA836F}" + ProjectSection(SolutionItems) = preProject + Acknowledgments.md = Acknowledgments.md + CLAUDE.md = CLAUDE.md + CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md + CONTRIBUTING.md = CONTRIBUTING.md + readme.md = readme.md + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Telemetry.Tests", "tests\BaGet.Telemetry.Tests\BaGet.Telemetry.Tests.csproj", "{A0B476AB-E170-443F-B37D-66C8C0F7C69B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Clients.Tests", "tests\BaGet.Clients.Tests\BaGet.Clients.Tests.csproj", "{BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Storage.Tests", "tests\BaGet.Storage.Tests\BaGet.Storage.Tests.csproj", "{6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Ha.Tests", "tests\BaGet.Ha.Tests\BaGet.Ha.Tests.csproj", "{7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Cloud", "Cloud", "{2AF127EE-B198-4914-B3CD-5DA732F53648}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Data", "Data", "{3F4F1174-109E-4221-8B00-0E3DEC0774CD}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Identity.Application", "src\BaGet.Identity.Application\BaGet.Identity.Application.csproj", "{311939DB-1F11-4F60-8A32-AD6AA71F6D39}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Web.Application", "src\BaGet.Web.Application\BaGet.Web.Application.csproj", "{35F745F2-E3CF-40B9-A033-DD396650192A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Frontend.Base", "src\BaGet.Frontend.Base\BaGet.Frontend.Base.csproj", "{A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Api.Base", "src\BaGet.Api.Base\BaGet.Api.Base.csproj", "{80B1AF3E-38B2-409F-8616-E5781C5DD226}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Identity.FrontEnd", "src\BaGet.Identity.FrontEnd\BaGet.Identity.FrontEnd.csproj", "{72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Web.FrontEnd", "src\BaGet.Web.FrontEnd\BaGet.Web.FrontEnd.csproj", "{71CA649D-A029-45CC-9713-196D9A922403}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "BaGet.Frontend.Angular", "BaGet.Frontend.Angular", "{36F2C53C-EE04-44C7-BADB-6A7182EDC40E}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\.editorconfig = samples\BaGet.Frontend.Angular\.editorconfig + samples\BaGet.Frontend.Angular\.gitignore = samples\BaGet.Frontend.Angular\.gitignore + samples\BaGet.Frontend.Angular\.npmrc = samples\BaGet.Frontend.Angular\.npmrc + samples\BaGet.Frontend.Angular\.prettierrc = samples\BaGet.Frontend.Angular\.prettierrc + samples\BaGet.Frontend.Angular\angular.json = samples\BaGet.Frontend.Angular\angular.json + samples\BaGet.Frontend.Angular\package-lock.json = samples\BaGet.Frontend.Angular\package-lock.json + samples\BaGet.Frontend.Angular\package.json = samples\BaGet.Frontend.Angular\package.json + samples\BaGet.Frontend.Angular\README.md = samples\BaGet.Frontend.Angular\README.md + samples\BaGet.Frontend.Angular\tsconfig.app.json = samples\BaGet.Frontend.Angular\tsconfig.app.json + samples\BaGet.Frontend.Angular\tsconfig.json = samples\BaGet.Frontend.Angular\tsconfig.json + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "openapi", "openapi", "{CE692325-32D2-49D2-AF37-3FACDB8979BD}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\openapi\ui.json = samples\BaGet.Frontend.Angular\openapi\ui.json + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "public", "public", "{4611ECCF-6029-4917-A9B9-F35AA94555A7}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\public\favicon.ico = samples\BaGet.Frontend.Angular\public\favicon.ico + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scripts", "scripts", "{D1906418-E817-44EF-B10F-DB7E40424E23}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\scripts\smoke.mjs = samples\BaGet.Frontend.Angular\scripts\smoke.mjs + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{4898C856-3C78-4E13-BF8A-6FC322121B04}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\src\index.html = samples\BaGet.Frontend.Angular\src\index.html + samples\BaGet.Frontend.Angular\src\main.ts = samples\BaGet.Frontend.Angular\src\main.ts + samples\BaGet.Frontend.Angular\src\styles.css = samples\BaGet.Frontend.Angular\src\styles.css + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "app", "app", "{A85A2FDD-166D-4FD8-8D55-644C1CAD9665}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\src\app\app.config.ts = samples\BaGet.Frontend.Angular\src\app\app.config.ts + samples\BaGet.Frontend.Angular\src\app\app.html = samples\BaGet.Frontend.Angular\src\app\app.html + samples\BaGet.Frontend.Angular\src\app\app.routes.ts = samples\BaGet.Frontend.Angular\src\app\app.routes.ts + samples\BaGet.Frontend.Angular\src\app\app.ts = samples\BaGet.Frontend.Angular\src\app\app.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "api", "api", "{995FA248-E191-4AC7-8B13-6BF028B3F0BF}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\src\app\api\api-client.ts = samples\BaGet.Frontend.Angular\src\app\api\api-client.ts + samples\BaGet.Frontend.Angular\src\app\api\api-types.ts = samples\BaGet.Frontend.Angular\src\app\api\api-types.ts + samples\BaGet.Frontend.Angular\src\app\api\field-errors.ts = samples\BaGet.Frontend.Angular\src\app\api\field-errors.ts + samples\BaGet.Frontend.Angular\src\app\api\schema.d.ts = samples\BaGet.Frontend.Angular\src\app\api\schema.d.ts + samples\BaGet.Frontend.Angular\src\app\api\screens.ts = samples\BaGet.Frontend.Angular\src\app\api\screens.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "pages", "pages", "{AC1023B1-12D9-43D1-A266-B59A6D2C00D3}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\src\app\pages\admin-users.ts = samples\BaGet.Frontend.Angular\src\app\pages\admin-users.ts + samples\BaGet.Frontend.Angular\src\app\pages\confirm-email.ts = samples\BaGet.Frontend.Angular\src\app\pages\confirm-email.ts + samples\BaGet.Frontend.Angular\src\app\pages\external-sign-in.ts = samples\BaGet.Frontend.Angular\src\app\pages\external-sign-in.ts + samples\BaGet.Frontend.Angular\src\app\pages\forgot-password.ts = samples\BaGet.Frontend.Angular\src\app\pages\forgot-password.ts + samples\BaGet.Frontend.Angular\src\app\pages\package-detail.ts = samples\BaGet.Frontend.Angular\src\app\pages\package-detail.ts + samples\BaGet.Frontend.Angular\src\app\pages\packages.ts = samples\BaGet.Frontend.Angular\src\app\pages\packages.ts + samples\BaGet.Frontend.Angular\src\app\pages\register.ts = samples\BaGet.Frontend.Angular\src\app\pages\register.ts + samples\BaGet.Frontend.Angular\src\app\pages\reset-password.ts = samples\BaGet.Frontend.Angular\src\app\pages\reset-password.ts + samples\BaGet.Frontend.Angular\src\app\pages\sign-in.ts = samples\BaGet.Frontend.Angular\src\app\pages\sign-in.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "session", "session", "{3EE7AAF5-C4DD-4982-B0EF-2F26DA8ACD5D}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\src\app\session\auth.guard.ts = samples\BaGet.Frontend.Angular\src\app\session\auth.guard.ts + samples\BaGet.Frontend.Angular\src\app\session\oidc-state.ts = samples\BaGet.Frontend.Angular\src\app\session\oidc-state.ts + samples\BaGet.Frontend.Angular\src\app\session\session.interceptor.ts = samples\BaGet.Frontend.Angular\src\app\session\session.interceptor.ts + samples\BaGet.Frontend.Angular\src\app\session\session.service.ts = samples\BaGet.Frontend.Angular\src\app\session\session.service.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "environments", "environments", "{42AF979F-EEE9-43F1-8FD1-ABA989F1D87E}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.Angular\src\environments\environment.development.ts = samples\BaGet.Frontend.Angular\src\environments\environment.development.ts + samples\BaGet.Frontend.Angular\src\environments\environment.ts = samples\BaGet.Frontend.Angular\src\environments\environment.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "BaGet.Frontend.React", "BaGet.Frontend.React", "{A0FE8C68-8740-4373-B311-627E21518DDC}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.React\.env.example = samples\BaGet.Frontend.React\.env.example + samples\BaGet.Frontend.React\.gitignore = samples\BaGet.Frontend.React\.gitignore + samples\BaGet.Frontend.React\index.html = samples\BaGet.Frontend.React\index.html + samples\BaGet.Frontend.React\package-lock.json = samples\BaGet.Frontend.React\package-lock.json + samples\BaGet.Frontend.React\package.json = samples\BaGet.Frontend.React\package.json + samples\BaGet.Frontend.React\README.md = samples\BaGet.Frontend.React\README.md + samples\BaGet.Frontend.React\tsconfig.json = samples\BaGet.Frontend.React\tsconfig.json + samples\BaGet.Frontend.React\vite.config.ts = samples\BaGet.Frontend.React\vite.config.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "openapi", "openapi", "{1A82125A-EA10-4AD1-B8C5-27D3E446052E}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.React\openapi\ui.json = samples\BaGet.Frontend.React\openapi\ui.json + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scripts", "scripts", "{DB140D73-2B25-43ED-9E1A-118C6326FA06}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.React\scripts\smoke.mjs = samples\BaGet.Frontend.React\scripts\smoke.mjs + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1D6ED755-2D8E-4A3E-A6D0-8EAE3513C739}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.React\src\App.tsx = samples\BaGet.Frontend.React\src\App.tsx + samples\BaGet.Frontend.React\src\auth.tsx = samples\BaGet.Frontend.React\src\auth.tsx + samples\BaGet.Frontend.React\src\config.ts = samples\BaGet.Frontend.React\src\config.ts + samples\BaGet.Frontend.React\src\main.tsx = samples\BaGet.Frontend.React\src\main.tsx + samples\BaGet.Frontend.React\src\routes.ts = samples\BaGet.Frontend.React\src\routes.ts + samples\BaGet.Frontend.React\src\styles.css = samples\BaGet.Frontend.React\src\styles.css + samples\BaGet.Frontend.React\src\vite-env.d.ts = samples\BaGet.Frontend.React\src\vite-env.d.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "api", "api", "{15577495-2C8F-4F34-92F7-AD5352B1126C}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.React\src\api\client.ts = samples\BaGet.Frontend.React\src\api\client.ts + samples\BaGet.Frontend.React\src\api\schema.d.ts = samples\BaGet.Frontend.React\src\api\schema.d.ts + samples\BaGet.Frontend.React\src\api\screen.ts = samples\BaGet.Frontend.React\src\api\screen.ts + samples\BaGet.Frontend.React\src\api\session.ts = samples\BaGet.Frontend.React\src\api\session.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "components", "components", "{9FA00C89-09E9-4C1F-ADBF-A71CB6BFA513}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.React\src\components\Form.tsx = samples\BaGet.Frontend.React\src\components\Form.tsx + samples\BaGet.Frontend.React\src\components\useScreen.ts = samples\BaGet.Frontend.React\src\components\useScreen.ts + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "pages", "pages", "{45CC80FB-737C-417C-A103-D7CADD530591}" + ProjectSection(SolutionItems) = preProject + samples\BaGet.Frontend.React\src\pages\AdminUsers.tsx = samples\BaGet.Frontend.React\src\pages\AdminUsers.tsx + samples\BaGet.Frontend.React\src\pages\ConfirmEmail.tsx = samples\BaGet.Frontend.React\src\pages\ConfirmEmail.tsx + samples\BaGet.Frontend.React\src\pages\ForgotPassword.tsx = samples\BaGet.Frontend.React\src\pages\ForgotPassword.tsx + samples\BaGet.Frontend.React\src\pages\Home.tsx = samples\BaGet.Frontend.React\src\pages\Home.tsx + samples\BaGet.Frontend.React\src\pages\PackageDetail.tsx = samples\BaGet.Frontend.React\src\pages\PackageDetail.tsx + samples\BaGet.Frontend.React\src\pages\Register.tsx = samples\BaGet.Frontend.React\src\pages\Register.tsx + samples\BaGet.Frontend.React\src\pages\ResetPassword.tsx = samples\BaGet.Frontend.React\src\pages\ResetPassword.tsx + samples\BaGet.Frontend.React\src\pages\SignIn.tsx = samples\BaGet.Frontend.React\src\pages\SignIn.tsx + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {284366CB-C68F-473E-908A-50A382616AE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {284366CB-C68F-473E-908A-50A382616AE0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Debug|x64.ActiveCfg = Debug|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Debug|x64.Build.0 = Debug|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Debug|x86.ActiveCfg = Debug|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Debug|x86.Build.0 = Debug|Any CPU {284366CB-C68F-473E-908A-50A382616AE0}.Release|Any CPU.ActiveCfg = Release|Any CPU {284366CB-C68F-473E-908A-50A382616AE0}.Release|Any CPU.Build.0 = Release|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Release|x64.ActiveCfg = Release|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Release|x64.Build.0 = Release|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Release|x86.ActiveCfg = Release|Any CPU + {284366CB-C68F-473E-908A-50A382616AE0}.Release|x86.Build.0 = Release|Any CPU {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Debug|x64.ActiveCfg = Debug|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Debug|x64.Build.0 = Debug|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Debug|x86.ActiveCfg = Debug|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Debug|x86.Build.0 = Debug|Any CPU {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Release|Any CPU.ActiveCfg = Release|Any CPU {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Release|Any CPU.Build.0 = Release|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Release|x64.ActiveCfg = Release|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Release|x64.Build.0 = Release|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Release|x86.ActiveCfg = Release|Any CPU + {FFFACD28-C300-4046-BCFE-4A7899E88EA3}.Release|x86.Build.0 = Release|Any CPU {716C970D-9614-4265-AC92-57E8B227B98E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {716C970D-9614-4265-AC92-57E8B227B98E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Debug|x64.ActiveCfg = Debug|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Debug|x64.Build.0 = Debug|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Debug|x86.ActiveCfg = Debug|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Debug|x86.Build.0 = Debug|Any CPU {716C970D-9614-4265-AC92-57E8B227B98E}.Release|Any CPU.ActiveCfg = Release|Any CPU {716C970D-9614-4265-AC92-57E8B227B98E}.Release|Any CPU.Build.0 = Release|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Release|x64.ActiveCfg = Release|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Release|x64.Build.0 = Release|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Release|x86.ActiveCfg = Release|Any CPU + {716C970D-9614-4265-AC92-57E8B227B98E}.Release|x86.Build.0 = Release|Any CPU {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Debug|Any CPU.Build.0 = Debug|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Debug|x64.ActiveCfg = Debug|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Debug|x64.Build.0 = Debug|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Debug|x86.ActiveCfg = Debug|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Debug|x86.Build.0 = Debug|Any CPU {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Release|Any CPU.ActiveCfg = Release|Any CPU {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Release|Any CPU.Build.0 = Release|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Release|x64.ActiveCfg = Release|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Release|x64.Build.0 = Release|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Release|x86.ActiveCfg = Release|Any CPU + {89AB1AE2-6CAA-4809-8B74-D78CBE00B049}.Release|x86.Build.0 = Release|Any CPU {892A7A82-4283-4315-B7E5-6D5B70543000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {892A7A82-4283-4315-B7E5-6D5B70543000}.Debug|Any CPU.Build.0 = Debug|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Debug|x64.ActiveCfg = Debug|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Debug|x64.Build.0 = Debug|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Debug|x86.ActiveCfg = Debug|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Debug|x86.Build.0 = Debug|Any CPU {892A7A82-4283-4315-B7E5-6D5B70543000}.Release|Any CPU.ActiveCfg = Release|Any CPU {892A7A82-4283-4315-B7E5-6D5B70543000}.Release|Any CPU.Build.0 = Release|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Release|x64.ActiveCfg = Release|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Release|x64.Build.0 = Release|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Release|x86.ActiveCfg = Release|Any CPU + {892A7A82-4283-4315-B7E5-6D5B70543000}.Release|x86.Build.0 = Release|Any CPU {A2D23427-9278-4D52-B31F-759212252832}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A2D23427-9278-4D52-B31F-759212252832}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Debug|x64.ActiveCfg = Debug|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Debug|x64.Build.0 = Debug|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Debug|x86.ActiveCfg = Debug|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Debug|x86.Build.0 = Debug|Any CPU {A2D23427-9278-4D52-B31F-759212252832}.Release|Any CPU.ActiveCfg = Release|Any CPU {A2D23427-9278-4D52-B31F-759212252832}.Release|Any CPU.Build.0 = Release|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Release|x64.ActiveCfg = Release|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Release|x64.Build.0 = Release|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Release|x86.ActiveCfg = Release|Any CPU + {A2D23427-9278-4D52-B31F-759212252832}.Release|x86.Build.0 = Release|Any CPU {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Debug|x64.ActiveCfg = Debug|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Debug|x64.Build.0 = Debug|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Debug|x86.ActiveCfg = Debug|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Debug|x86.Build.0 = Debug|Any CPU {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Release|Any CPU.ActiveCfg = Release|Any CPU {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Release|Any CPU.Build.0 = Release|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Release|x64.ActiveCfg = Release|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Release|x64.Build.0 = Release|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Release|x86.ActiveCfg = Release|Any CPU + {AC764A9A-9EAF-422B-9223-D3290C3CFD79}.Release|x86.Build.0 = Release|Any CPU {D067D82E-D515-44D1-A832-C79F29418DFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D067D82E-D515-44D1-A832-C79F29418DFC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Debug|x64.ActiveCfg = Debug|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Debug|x64.Build.0 = Debug|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Debug|x86.ActiveCfg = Debug|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Debug|x86.Build.0 = Debug|Any CPU {D067D82E-D515-44D1-A832-C79F29418DFC}.Release|Any CPU.ActiveCfg = Release|Any CPU {D067D82E-D515-44D1-A832-C79F29418DFC}.Release|Any CPU.Build.0 = Release|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Release|x64.ActiveCfg = Release|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Release|x64.Build.0 = Release|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Release|x86.ActiveCfg = Release|Any CPU + {D067D82E-D515-44D1-A832-C79F29418DFC}.Release|x86.Build.0 = Release|Any CPU {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Debug|x64.ActiveCfg = Debug|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Debug|x64.Build.0 = Debug|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Debug|x86.ActiveCfg = Debug|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Debug|x86.Build.0 = Debug|Any CPU {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Release|Any CPU.ActiveCfg = Release|Any CPU {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Release|Any CPU.Build.0 = Release|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Release|x64.ActiveCfg = Release|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Release|x64.Build.0 = Release|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Release|x86.ActiveCfg = Release|Any CPU + {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C}.Release|x86.Build.0 = Release|Any CPU {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Debug|x64.ActiveCfg = Debug|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Debug|x64.Build.0 = Debug|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Debug|x86.ActiveCfg = Debug|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Debug|x86.Build.0 = Debug|Any CPU {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Release|Any CPU.ActiveCfg = Release|Any CPU {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Release|Any CPU.Build.0 = Release|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Release|x64.ActiveCfg = Release|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Release|x64.Build.0 = Release|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Release|x86.ActiveCfg = Release|Any CPU + {EC5E6B2C-2494-40E8-8682-080BA580DDA7}.Release|x86.Build.0 = Release|Any CPU {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Debug|x64.ActiveCfg = Debug|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Debug|x64.Build.0 = Debug|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Debug|x86.ActiveCfg = Debug|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Debug|x86.Build.0 = Debug|Any CPU {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Release|Any CPU.ActiveCfg = Release|Any CPU {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Release|Any CPU.Build.0 = Release|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Release|x64.ActiveCfg = Release|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Release|x64.Build.0 = Release|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Release|x86.ActiveCfg = Release|Any CPU + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C}.Release|x86.Build.0 = Release|Any CPU {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Debug|x64.ActiveCfg = Debug|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Debug|x64.Build.0 = Debug|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Debug|x86.ActiveCfg = Debug|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Debug|x86.Build.0 = Debug|Any CPU {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Release|Any CPU.Build.0 = Release|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Release|x64.ActiveCfg = Release|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Release|x64.Build.0 = Release|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Release|x86.ActiveCfg = Release|Any CPU + {A4375529-E855-4D46-AA4F-B3FE630C3DE1}.Release|x86.Build.0 = Release|Any CPU {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Debug|x64.ActiveCfg = Debug|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Debug|x64.Build.0 = Debug|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Debug|x86.ActiveCfg = Debug|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Debug|x86.Build.0 = Debug|Any CPU {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Release|Any CPU.ActiveCfg = Release|Any CPU {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Release|Any CPU.Build.0 = Release|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Release|x64.ActiveCfg = Release|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Release|x64.Build.0 = Release|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Release|x86.ActiveCfg = Release|Any CPU + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA}.Release|x86.Build.0 = Release|Any CPU {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Debug|x64.ActiveCfg = Debug|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Debug|x64.Build.0 = Debug|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Debug|x86.ActiveCfg = Debug|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Debug|x86.Build.0 = Debug|Any CPU {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Release|Any CPU.ActiveCfg = Release|Any CPU {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Release|Any CPU.Build.0 = Release|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Release|x64.ActiveCfg = Release|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Release|x64.Build.0 = Release|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Release|x86.ActiveCfg = Release|Any CPU + {D7D60BA0-FF7F-4B37-815C-74D487C5176E}.Release|x86.Build.0 = Release|Any CPU {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Debug|x64.ActiveCfg = Debug|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Debug|x64.Build.0 = Debug|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Debug|x86.ActiveCfg = Debug|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Debug|x86.Build.0 = Debug|Any CPU {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Release|Any CPU.ActiveCfg = Release|Any CPU {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Release|Any CPU.Build.0 = Release|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Release|x64.ActiveCfg = Release|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Release|x64.Build.0 = Release|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Release|x86.ActiveCfg = Release|Any CPU + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF}.Release|x86.Build.0 = Release|Any CPU {9F7C4F38-D598-42D9-A9F8-962490483B18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9F7C4F38-D598-42D9-A9F8-962490483B18}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Debug|x64.ActiveCfg = Debug|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Debug|x64.Build.0 = Debug|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Debug|x86.ActiveCfg = Debug|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Debug|x86.Build.0 = Debug|Any CPU {9F7C4F38-D598-42D9-A9F8-962490483B18}.Release|Any CPU.ActiveCfg = Release|Any CPU {9F7C4F38-D598-42D9-A9F8-962490483B18}.Release|Any CPU.Build.0 = Release|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Release|x64.ActiveCfg = Release|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Release|x64.Build.0 = Release|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Release|x86.ActiveCfg = Release|Any CPU + {9F7C4F38-D598-42D9-A9F8-962490483B18}.Release|x86.Build.0 = Release|Any CPU {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Debug|x64.ActiveCfg = Debug|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Debug|x64.Build.0 = Debug|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Debug|x86.ActiveCfg = Debug|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Debug|x86.Build.0 = Debug|Any CPU {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Release|Any CPU.ActiveCfg = Release|Any CPU {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Release|Any CPU.Build.0 = Release|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Release|x64.ActiveCfg = Release|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Release|x64.Build.0 = Release|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Release|x86.ActiveCfg = Release|Any CPU + {E5AFE55D-0932-46A9-BFA3-C8A034037377}.Release|x86.Build.0 = Release|Any CPU {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Debug|x64.ActiveCfg = Debug|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Debug|x64.Build.0 = Debug|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Debug|x86.ActiveCfg = Debug|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Debug|x86.Build.0 = Debug|Any CPU {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Release|Any CPU.ActiveCfg = Release|Any CPU {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Release|Any CPU.Build.0 = Release|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Release|x64.ActiveCfg = Release|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Release|x64.Build.0 = Release|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Release|x86.ActiveCfg = Release|Any CPU + {BEEAAA73-36CD-4178-9C9F-6D036586E7BF}.Release|x86.Build.0 = Release|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Debug|Any CPU.Build.0 = Debug|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Debug|x64.ActiveCfg = Debug|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Debug|x64.Build.0 = Debug|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Debug|x86.ActiveCfg = Debug|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Debug|x86.Build.0 = Debug|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Release|Any CPU.ActiveCfg = Release|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Release|Any CPU.Build.0 = Release|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Release|x64.ActiveCfg = Release|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Release|x64.Build.0 = Release|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Release|x86.ActiveCfg = Release|Any CPU + {493DE3CC-BE24-4206-88C6-7BDE7721EF10}.Release|x86.Build.0 = Release|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Debug|Any CPU.Build.0 = Debug|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Debug|x64.ActiveCfg = Debug|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Debug|x64.Build.0 = Debug|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Debug|x86.ActiveCfg = Debug|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Debug|x86.Build.0 = Debug|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Release|Any CPU.ActiveCfg = Release|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Release|Any CPU.Build.0 = Release|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Release|x64.ActiveCfg = Release|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Release|x64.Build.0 = Release|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Release|x86.ActiveCfg = Release|Any CPU + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399}.Release|x86.Build.0 = Release|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Debug|x64.ActiveCfg = Debug|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Debug|x64.Build.0 = Debug|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Debug|x86.ActiveCfg = Debug|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Debug|x86.Build.0 = Debug|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Release|Any CPU.Build.0 = Release|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Release|x64.ActiveCfg = Release|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Release|x64.Build.0 = Release|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Release|x86.ActiveCfg = Release|Any CPU + {6F4FBCFC-6887-4401-A0B7-A856C91011BA}.Release|x86.Build.0 = Release|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Debug|x64.ActiveCfg = Debug|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Debug|x64.Build.0 = Debug|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Debug|x86.ActiveCfg = Debug|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Debug|x86.Build.0 = Debug|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|Any CPU.Build.0 = Release|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|x64.ActiveCfg = Release|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|x64.Build.0 = Release|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|x86.ActiveCfg = Release|Any CPU + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|x86.Build.0 = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x64.ActiveCfg = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x64.Build.0 = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x86.ActiveCfg = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x86.Build.0 = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|Any CPU.Build.0 = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x64.ActiveCfg = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x64.Build.0 = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x86.ActiveCfg = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x86.Build.0 = Release|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Debug|x64.ActiveCfg = Debug|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Debug|x64.Build.0 = Debug|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Debug|x86.ActiveCfg = Debug|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Debug|x86.Build.0 = Debug|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Release|Any CPU.Build.0 = Release|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Release|x64.ActiveCfg = Release|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Release|x64.Build.0 = Release|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Release|x86.ActiveCfg = Release|Any CPU + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6}.Release|x86.Build.0 = Release|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Debug|x64.ActiveCfg = Debug|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Debug|x64.Build.0 = Debug|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Debug|x86.ActiveCfg = Debug|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Debug|x86.Build.0 = Debug|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Release|Any CPU.Build.0 = Release|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Release|x64.ActiveCfg = Release|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Release|x64.Build.0 = Release|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Release|x86.ActiveCfg = Release|Any CPU + {A0B476AB-E170-443F-B37D-66C8C0F7C69B}.Release|x86.Build.0 = Release|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Debug|x64.ActiveCfg = Debug|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Debug|x64.Build.0 = Debug|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Debug|x86.ActiveCfg = Debug|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Debug|x86.Build.0 = Debug|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Release|Any CPU.Build.0 = Release|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Release|x64.ActiveCfg = Release|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Release|x64.Build.0 = Release|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Release|x86.ActiveCfg = Release|Any CPU + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00}.Release|x86.Build.0 = Release|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Debug|x64.ActiveCfg = Debug|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Debug|x64.Build.0 = Debug|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Debug|x86.ActiveCfg = Debug|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Debug|x86.Build.0 = Debug|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Release|Any CPU.Build.0 = Release|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Release|x64.ActiveCfg = Release|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Release|x64.Build.0 = Release|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Release|x86.ActiveCfg = Release|Any CPU + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10}.Release|x86.Build.0 = Release|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Debug|x64.ActiveCfg = Debug|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Debug|x64.Build.0 = Debug|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Debug|x86.ActiveCfg = Debug|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Debug|x86.Build.0 = Debug|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Release|Any CPU.Build.0 = Release|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Release|x64.ActiveCfg = Release|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Release|x64.Build.0 = Release|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Release|x86.ActiveCfg = Release|Any CPU + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24}.Release|x86.Build.0 = Release|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Debug|Any CPU.Build.0 = Debug|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Debug|x64.ActiveCfg = Debug|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Debug|x64.Build.0 = Debug|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Debug|x86.ActiveCfg = Debug|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Debug|x86.Build.0 = Debug|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Release|Any CPU.ActiveCfg = Release|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Release|Any CPU.Build.0 = Release|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Release|x64.ActiveCfg = Release|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Release|x64.Build.0 = Release|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Release|x86.ActiveCfg = Release|Any CPU + {311939DB-1F11-4F60-8A32-AD6AA71F6D39}.Release|x86.Build.0 = Release|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Debug|x64.ActiveCfg = Debug|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Debug|x64.Build.0 = Debug|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Debug|x86.ActiveCfg = Debug|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Debug|x86.Build.0 = Debug|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Release|Any CPU.Build.0 = Release|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Release|x64.ActiveCfg = Release|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Release|x64.Build.0 = Release|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Release|x86.ActiveCfg = Release|Any CPU + {35F745F2-E3CF-40B9-A033-DD396650192A}.Release|x86.Build.0 = Release|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Debug|x64.ActiveCfg = Debug|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Debug|x64.Build.0 = Debug|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Debug|x86.ActiveCfg = Debug|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Debug|x86.Build.0 = Debug|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Release|Any CPU.Build.0 = Release|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Release|x64.ActiveCfg = Release|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Release|x64.Build.0 = Release|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Release|x86.ActiveCfg = Release|Any CPU + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3}.Release|x86.Build.0 = Release|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Debug|Any CPU.Build.0 = Debug|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Debug|x64.ActiveCfg = Debug|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Debug|x64.Build.0 = Debug|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Debug|x86.ActiveCfg = Debug|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Debug|x86.Build.0 = Debug|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Release|Any CPU.ActiveCfg = Release|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Release|Any CPU.Build.0 = Release|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Release|x64.ActiveCfg = Release|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Release|x64.Build.0 = Release|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Release|x86.ActiveCfg = Release|Any CPU + {80B1AF3E-38B2-409F-8616-E5781C5DD226}.Release|x86.Build.0 = Release|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Debug|x64.ActiveCfg = Debug|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Debug|x64.Build.0 = Debug|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Debug|x86.ActiveCfg = Debug|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Debug|x86.Build.0 = Debug|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Release|Any CPU.Build.0 = Release|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Release|x64.ActiveCfg = Release|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Release|x64.Build.0 = Release|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Release|x86.ActiveCfg = Release|Any CPU + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB}.Release|x86.Build.0 = Release|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Debug|Any CPU.Build.0 = Debug|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Debug|x64.ActiveCfg = Debug|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Debug|x64.Build.0 = Debug|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Debug|x86.ActiveCfg = Debug|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Debug|x86.Build.0 = Debug|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Release|Any CPU.ActiveCfg = Release|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Release|Any CPU.Build.0 = Release|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Release|x64.ActiveCfg = Release|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Release|x64.Build.0 = Release|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Release|x86.ActiveCfg = Release|Any CPU + {71CA649D-A029-45CC-9713-196D9A922403}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -137,22 +736,61 @@ Global GlobalSection(NestedProjects) = preSolution {284366CB-C68F-473E-908A-50A382616AE0} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} {FFFACD28-C300-4046-BCFE-4A7899E88EA3} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} - {716C970D-9614-4265-AC92-57E8B227B98E} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {716C970D-9614-4265-AC92-57E8B227B98E} = {2AF127EE-B198-4914-B3CD-5DA732F53648} {89AB1AE2-6CAA-4809-8B74-D78CBE00B049} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} {892A7A82-4283-4315-B7E5-6D5B70543000} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} {A2D23427-9278-4D52-B31F-759212252832} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} {AC764A9A-9EAF-422B-9223-D3290C3CFD79} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} - {D067D82E-D515-44D1-A832-C79F29418DFC} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {D067D82E-D515-44D1-A832-C79F29418DFC} = {2AF127EE-B198-4914-B3CD-5DA732F53648} {D68B56AC-98DD-4DA7-B4F8-1243538A8A5C} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} - {EC5E6B2C-2494-40E8-8682-080BA580DDA7} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} - {4C513AFC-BA7B-471D-B8F6-268E7AD2074C} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} - {A4375529-E855-4D46-AA4F-B3FE630C3DE1} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} - {F48F201A-4DEE-4D5B-9C0B-59490FE942FA} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} - {D7D60BA0-FF7F-4B37-815C-74D487C5176E} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} - {16B0D424-BB2F-4C0C-90B0-4F7955326ADF} = {DDEC0736-8169-4834-815E-B78E7CE612A4} - {9F7C4F38-D598-42D9-A9F8-962490483B18} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {EC5E6B2C-2494-40E8-8682-080BA580DDA7} = {3F4F1174-109E-4221-8B00-0E3DEC0774CD} + {4C513AFC-BA7B-471D-B8F6-268E7AD2074C} = {3F4F1174-109E-4221-8B00-0E3DEC0774CD} + {A4375529-E855-4D46-AA4F-B3FE630C3DE1} = {3F4F1174-109E-4221-8B00-0E3DEC0774CD} + {F48F201A-4DEE-4D5B-9C0B-59490FE942FA} = {3F4F1174-109E-4221-8B00-0E3DEC0774CD} + {D7D60BA0-FF7F-4B37-815C-74D487C5176E} = {2AF127EE-B198-4914-B3CD-5DA732F53648} + {16B0D424-BB2F-4C0C-90B0-4F7955326ADF} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {9F7C4F38-D598-42D9-A9F8-962490483B18} = {2AF127EE-B198-4914-B3CD-5DA732F53648} {E5AFE55D-0932-46A9-BFA3-C8A034037377} = {DDEC0736-8169-4834-815E-B78E7CE612A4} {BEEAAA73-36CD-4178-9C9F-6D036586E7BF} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {493DE3CC-BE24-4206-88C6-7BDE7721EF10} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {6F4FBCFC-6887-4401-A0B7-A856C91011BA} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {E2D03D72-23F2-409E-B895-45BAEEC75768} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {C9C1D5C8-730A-47C1-8C3F-3A3D92E4D0E6} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {4974D3C8-A572-426F-84A0-7EA7D087EADD} = {2AEF938A-36F0-49B4-868A-E062B2596A1B} + {18E1CCF3-1808-4982-8D0B-D2BEE393F0C3} = {2AEF938A-36F0-49B4-868A-E062B2596A1B} + {E3E95BD1-D4AC-4C30-B157-643C65F6CC0B} = {2AEF938A-36F0-49B4-868A-E062B2596A1B} + {FBD25121-8133-4E7F-B2D0-1F82AF3E1082} = {2AEF938A-36F0-49B4-868A-E062B2596A1B} + {A0B476AB-E170-443F-B37D-66C8C0F7C69B} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {BDE1999F-AA7D-49B7-95B5-02CAC78D1F00} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {6A1D8C3E-52B7-4F0A-9E14-7C5B3D2A8F10} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {7C2E41B9-3D58-4A6F-8B17-5E9A0D3F6C24} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} + {2AF127EE-B198-4914-B3CD-5DA732F53648} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {3F4F1174-109E-4221-8B00-0E3DEC0774CD} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {311939DB-1F11-4F60-8A32-AD6AA71F6D39} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {35F745F2-E3CF-40B9-A033-DD396650192A} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {A3B5E731-CA4E-10DB-FB69-E6CDB85443A3} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {80B1AF3E-38B2-409F-8616-E5781C5DD226} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {72BDC4AA-AF84-4FFC-ACEB-834CA19D0FDB} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {71CA649D-A029-45CC-9713-196D9A922403} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {36F2C53C-EE04-44C7-BADB-6A7182EDC40E} = {DDEC0736-8169-4834-815E-B78E7CE612A4} + {CE692325-32D2-49D2-AF37-3FACDB8979BD} = {36F2C53C-EE04-44C7-BADB-6A7182EDC40E} + {4611ECCF-6029-4917-A9B9-F35AA94555A7} = {36F2C53C-EE04-44C7-BADB-6A7182EDC40E} + {D1906418-E817-44EF-B10F-DB7E40424E23} = {36F2C53C-EE04-44C7-BADB-6A7182EDC40E} + {4898C856-3C78-4E13-BF8A-6FC322121B04} = {36F2C53C-EE04-44C7-BADB-6A7182EDC40E} + {A85A2FDD-166D-4FD8-8D55-644C1CAD9665} = {4898C856-3C78-4E13-BF8A-6FC322121B04} + {995FA248-E191-4AC7-8B13-6BF028B3F0BF} = {A85A2FDD-166D-4FD8-8D55-644C1CAD9665} + {AC1023B1-12D9-43D1-A266-B59A6D2C00D3} = {A85A2FDD-166D-4FD8-8D55-644C1CAD9665} + {3EE7AAF5-C4DD-4982-B0EF-2F26DA8ACD5D} = {A85A2FDD-166D-4FD8-8D55-644C1CAD9665} + {42AF979F-EEE9-43F1-8FD1-ABA989F1D87E} = {4898C856-3C78-4E13-BF8A-6FC322121B04} + {A0FE8C68-8740-4373-B311-627E21518DDC} = {DDEC0736-8169-4834-815E-B78E7CE612A4} + {1A82125A-EA10-4AD1-B8C5-27D3E446052E} = {A0FE8C68-8740-4373-B311-627E21518DDC} + {DB140D73-2B25-43ED-9E1A-118C6326FA06} = {A0FE8C68-8740-4373-B311-627E21518DDC} + {1D6ED755-2D8E-4A3E-A6D0-8EAE3513C739} = {A0FE8C68-8740-4373-B311-627E21518DDC} + {15577495-2C8F-4F34-92F7-AD5352B1126C} = {1D6ED755-2D8E-4A3E-A6D0-8EAE3513C739} + {9FA00C89-09E9-4C1F-ADBF-A71CB6BFA513} = {1D6ED755-2D8E-4A3E-A6D0-8EAE3513C739} + {45CC80FB-737C-417C-A103-D7CADD530591} = {1D6ED755-2D8E-4A3E-A6D0-8EAE3513C739} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1423C027-2C90-417F-8629-2A4CF107C055} diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..9e312e4c9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,589 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +A fork of [loic-sharma/BaGet](https://github.com/loic-sharma/BaGet), A NuGet, Maven, NVM, Docker and symbol +server. The fork targets `net10.0` and has diverged substantially (accounts, V2 feed, validation, +catalog). Some work here is upstreamed as PRs against `loic-sharma/BaGet`. + +## Build and test + +**Always pass `-p:GeneratePackageOnBuild=false`.** `src/Directory.Build.props` sets +`GeneratePackageOnBuild=true` with `PackageOutputPath=$(SolutionDir)Packages\`, and `Packages` is a +**symlink to `D:\Starb\Packages`**, a shared NuGet feed. A plain build publishes packages into it, and two `AfterTargets="Pack"` targets +(MSBuild tasks only, so Windows, Linux and macOS alike) then run: `DeleteOldPackage` removes the package's folder (every version, lower-cased id) from the +global packages folder (`$(NuGetPackageRoot)`, else `NUGET_PACKAGES`, else `~/.nuget/packages`), so the next restore takes the fresh package even with an +unchanged version; `DeleteOlderGeneratedPackages` deletes the older `.nupkg`/`.snupkg`/`.symbols.nupkg` of the same id from `$(PackageOutputPath)`, keeping +what this pack wrote (`@(NuGetPackOutput)`; the name must continue with `.` after the id, so `Extension.BaGet` never touches `Extension.BaGet.Core`). + +| Task | Command | +|---|---| +| Build | `dotnet build BaGet.sln -p:GeneratePackageOnBuild=false` | +| Test (all) | `dotnet test BaGet.sln -p:GeneratePackageOnBuild=false` | +| Test (one project) | `dotnet test tests/BaGet.Core.Tests/BaGet.Core.Tests.csproj -p:GeneratePackageOnBuild=false` | +| Test (one class or method) | add `--filter-class "*UploadPageTests"` or `--filter-method "*Name"` (xUnit v3 filters; VSTest `--filter` is gone) | +| Run | `cd src/BaGet && dotnet run -p:GeneratePackageOnBuild=false` | + +Baseline: **3925 tests** (web APIs split from the screens; Docker not running, last full run of 3923: 3801 passed, 109 skipped, 13 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8 and two timing flakes under full-suite load that pass rerun, `OciRegistryTests.ATokenCannotBeForgedOrOutliveItsLifetime` and `RemoteRepositoryTests.ANotFoundIsRememberedForTheNegativePeriod`; then +2 `ApiOnlyHostTests`). Previous baseline: **3871 tests** (`/api/ui` keys-only; Docker running, last full run: 3854 passed, 0 skipped, 17 failed, all known: `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8, `TelemetryE2ETests` Jaeger x2, `GoogleCloudStreamingTests` x4 (GCS emulator flake, 1 of 10 failed on rerun); the count fell from 3916 because the cookie-driven twin tests of the account and package-ownership screens were replaced by a few screen-only checks). Previous baseline: **3916 tests** (UI API split finished; Docker not running, last full run: 3796 passed, 109 skipped, 11 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8). Previous baseline: **3912 tests** (UI API wave 2 included; Docker not running, last full run: 3791 passed, 109 skipped, 12 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8, the `ClusterStoreAndLeaseTests` lease-renewal timing flake). Previous baseline: **3848 tests** (UI API wave 1 included; Docker not running, last full run: 3727 passed, 109 skipped, 12 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8, the `DatabaseCopyTests` span test). Previous baseline: **3648 tests** (page-model shims removed; Docker not running, last full run: 3528 passed, 109 skipped, 11 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8). Previous baseline: **3662 tests** (Razor Pages to MVC migration and its final review fixes included; Docker not running, last full run: 3540 passed, 109 skipped, 13 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8 and 2 `MvcInfrastructureFacts` fixed right after and rerun green with `BaGet.Web.Tests` 72/72). Previous baseline: **3657 tests** (MVC wave 3 included; full run of all projects, Docker not running: 3536 passed, 109 skipped, 12 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8, the `DatabaseCopyTests` span test; previous baseline 3656 with MVC wave 2; BaGet.Tests alone, Docker not running: 2212 run, 2200 passed, 12 failed = the 11 below + `DatabaseCopyTests` span test, all known; wave 1 baseline was 3655, last full run of all projects: 3535 passed, 109 skipped, 11 failed; Docker not running, last full run: 3535 passed, 109 skipped, 11 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8; projects run one after another inside one `dotnet test` and peak at ~40 GB: **never two `BaGet.Tests` runs at once**, it exhausted a 64 GB machine). Previous baseline: **3608 tests** (wave 0 of the MVC migration included; Docker running, last full run: 3592 passed, 0 skipped, 16 failed, all known: `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8, `TelemetryE2ETests` Jaeger x3 incl. the stalled-collector test, the `DatabaseCopyTests` span test). Previous baseline: **3574 tests** (approval hardening included; last full run without Docker: 3452 passed, 103 skipped, 19 failed = `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8, the `ClusterStoreAndLeaseTests` lease-renewal timing flake; 7 more, from the `BaGet.Web` -> `BaGet.Web.V3` rename (`SiteCssTests` x2, `ApplicationPartsTests` x1, `StaticAssetsTests` x4), are fixed: the project pins `StaticWebAssetBasePath` to `_content/BaGet.Web`). Previous baseline: **3551 tests** (review fixes included; Docker running, last full run: 3537 passed, 0 skipped, 14 failed, all known: `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8, `TelemetryE2ETests` Jaeger x2, the `DatabaseCopyTests` span test). Earlier run at P10 (3533 tests): 3514 passed, 0 skipped, 17 failed = the 13 below, the `TelemetryE2ETests` Jaeger tests x3 (Docker present), plus two timing flakes that pass alone, `ClusterStoreAndLeaseTests.ALeaseIsRenewedWhile...` (600 ms lease starved under full-suite load) and `AdminOperationsTests.RetryValidatesAgain...`). Earlier P9 figure, 3484 tests (no Docker: 3374 passed, 97 skipped, 13 failed = `TelemetryE2ETests` stalled-collector test (Docker present; documented below as failing on a clean checkout), `TelemetryExportTests` x3, `TelemetrySettingsPageTests` x8 and the `DatabaseCopyTests` span test below) across `BaGet.Core.Tests` (997), `BaGet.Tests` (2085), +`BaGet.Protocol.Tests` (118), `BaGet.Azure.Tests` (107), `BaGet.Web.Tests` (58), +`BaGet.Protocol.Samples.Tests` (8), `BaGet.Database.Tests` (20), `BaGet.Telemetry.Tests` (6), `BaGet.Clients.Tests` (44, Docker), `BaGet.Ha.Tests` (6, Docker, Redis; skips without), `BaGet.Storage.Tests` (40, Docker; the GCS emulator is a single-threaded Python server that drops reused connections, so its tests use a no-reuse HTTP handler; one GCS test still failed in 1 of 3 full-suite runs before that, rerun the class if it recurs). On a machine with a local Jaeger +(see the "Enabled local Jaeger" commit; **fixed since**: the harness now starts every host with `Telemetry:Enabled=false`, `TelemetryExportTests` and `TelemetrySettingsPageTests` pass, the cause was the shipped `Enabled=true`) 13 telemetry tests (`TelemetryExportTests`, `TelemetrySettingsPageTests`, +`TelemetryE2ETests`) fail on a clean checkout too; not investigated. Checked at `e213fe0` without Jaeger: 11 of them (`TelemetryExportTests` x3, +`TelemetrySettingsPageTests` x8) fail on a clean checkout, and `DatabaseCopyTests.ACopyEmitsADatabaseCopySpan...` fails in the full run (passes alone). With Docker running, the 2 +`TelemetryE2ETests` (Jaeger container) fail at `173c5a3` too (checked in a detached worktree). `AdminOperationsTests.RetryValidatesAgainAndIndexesWhenItNowPasses` raced the validation worker (the package is served a moment before the submission leaves the queue); it now waits for both. Only the Docker test projects need services; integration tests +use SQLite and a temporary directory. + +`BaGet.Database.Tests` copies between every ordered pair of SQLite / SQL Server / PostgreSQL / MySQL with +`DatabaseCopyService` on Testcontainers servers (`TestcontainersPackageVersion` in `tests/Directory.Build.props`; +images `mssql/server:2022-latest`, `postgres:17`, `mysql:8.4`, pulled on first run). Without a Docker daemon the 20 +tests **skip** (`Assert.Skip`), so the suite stays green; with one they take ~2 minutes. 4 of them +(`EngineUpgradeTests`) are the B7 upgrade on each engine: `PreRepositoryDatabase` (also linked into `BaGet.Tests`) migrates +to the last migration before `AddRepositories` (looked up per provider, timestamps differ), fills the old schema with raw +parameterised SQL, then the current migrations must put every row in repository key 1 and allow the same ID/version in key 2. + +`BaGet.Clients.Tests` (client rigs, B6) runs the real `npm` 10 in `node:22-alpine` and the real `mvn` 3.9 in `maven:3.9-eclipse-temurin-21` (`MavenCliTests`: deploy, resolve, snapshots, 409 rules, private repository; needs the internet for the plugins) (Testcontainers, idle container, scripts `exec`ed with a fresh empty `$HOME` **per run**, so one +script must hold a whole scenario) against a Kestrel server on `0.0.0.0` reached as `host.docker.internal` (WebApplicationFactory has no socket); skips without Docker. +`HostRegistry` is a recording fake: `NpmClientFlowTests` pins what npm sends for a read, `whoami`, `login` (web then CouchDB fallback) and `publish` (`docs/formats.md`). +`BaGetServer` is the **real application** (`Program.BuildApplication` with command-line settings, SQLite and a file store in a temp folder, `RunMigrationsAsync`, then `StartAsync`) on that kind of socket: +`NpmRegistryCliTests` (publish, install, scoped names through `%2f`, dist-tag, deprecate, unpublish, search/ping/whoami/audit, login/logout, a private repository), `NpmLargeTarballCliTests` +(40 MB, server allocations under 24 MB, runs alone in the `AllocationMeasurements` collection) and `NpmRemoteVirtualCliTests` (remote and virtual npm repositories; the upstream of a remote one is a *second* `BaGetServer` +reached as `localhost` by the first, so no fixture registry is needed; one test uses registry.npmjs.org and skips when it cannot be reached). `npm login` needs a terminal, so the tests run npm's own `npm-profile` login. `DockerCliTests` runs the real Docker 27 in a **privileged `docker:27-dind`** (`DockerDaemon`: `--insecure-registry host.docker.internal:{port}`, no TLS, the CLI in the same container on the unix socket, a fresh `DOCKER_CONFIG` per script; images built `FROM scratch`, so no internet) against a `BaGetServer` with accounts on: login (token flow), push/pull of multi-layer and 96 MB images, public/private/limited-key repositories, a multi-platform index (`docker manifest create --insecure`), a deleted manifest, and the `opencontainers/distribution-spec` v1.1.0 conformance image (`ghcr.io/opencontainers/distribution-spec/conformance:v1.1.0`: 75 of 80 specs run, 0 failed; the 5 are skipped by the suite itself). Skips without Docker or privileged containers. + +`BaGet.Telemetry.Tests` (shares `BaGetApplication` etc. from `BaGet.Tests` as linked files; `Containers.cs`) runs a real host against +`jaegertracing/all-in-one:1.76.0` (traces; query API read back) and `otel/opentelemetry-collector:0.140.0` (debug exporter, read back +from the container log) and skips without Docker (~1 minute with). It turns telemetry on through `SettingsService` (no restart) and +covers: trace visible in Jaeger within 10 s (Grpc and HttpProtobuf; ~1-2 s measured), a dead endpoint (requests unaffected, status +failing, restore resumes), Jaeger rejecting metrics/logs (`Unimplemented`; status fails, never silent), metrics/logs only while their +own endpoint is set, and a stalled collector (bounded queue drops spans, memory flat, median push latency within 5 %, off/on blocks +interleaved). `Otlp:Protocol` applies to **every** signal, so a logs endpoint must match it (gRPC port with `Grpc`). + +Tests are **xUnit v3** (`xunit.v3`, version lever `XUnitPackageVersion` in `tests/Directory.Build.props`), so test +projects are executables (`OutputType=Exe`) running on **Microsoft.Testing.Platform**: `global.json` +`"test": { "runner": "Microsoft.Testing.Platform" }` opts `dotnet test` in, and there is no VSTest adapter, +`Microsoft.NET.Test.Sdk` or coverlet collector. `ITestOutputHelper` lives in `Xunit`, not `Xunit.Abstractions`. + +`build.ps1` wraps clean/restore/build, with `-Run` and `-Publish`. + +Three gotchas when running locally: +- It listens on **6060**: `Kestrel:Endpoints:Http:Url` in `appsettings.json` outranks `--urls` and + `ASPNETCORE_URLS`, so they are silently ineffective (override with `Kestrel__Endpoints__Http__Url`). +- `nuget.config` lists an untracked `Packages` folder as a source; create it (`mkdir Packages`) on a clean checkout or restore fails with NU1301. +- `dotnet run` makes the SDK rewrite `src/BaGet/Properties/launchSettings.json` (it drops the IIS + Express profile). Revert it rather than committing it. + +## Every service has a UI counterpart + +Every operation a service, REST endpoint or CLI command offers must also be reachable from the web UI, in the same +change: a feature is not done while it exists only as REST, CLI or a service method. Gate the page like the operation +(same action/permission, antiforgery, password or re-authentication for destructive or access changes, +`MaintenanceGate.ThrowIfClosed` on writes) and link it from the navigation or the page it belongs to. Reviews check it. +Where the UI cannot yet do something the server can (a REST field, a CLI option, a service operation), enrich the UI +to cover it; `docs/ui-coverage.md` maps every capability to its page and gate and must stay complete (`UiCoverageInventoryTests` fails on a controller, controller action (screen) or CLI command with no row there). + +## Every docs page is in the solution and reachable + +Every Markdown file under `docs/` (recursively) is listed in `BaGet.sln` under the `docs` solution folder (subfolders as +nested solution folders), linked from `docs/index.md` or a page reachable from it, and in the `mkdocs.yml` nav. A new, +moved or deleted page updates all three in the same commit. **Exception: plan documents (`docs/plans/`) are never listed, +linked or put in the nav.** + +The SPA samples (`samples/BaGet.Frontend.React`, `samples/BaGet.Frontend.Angular`; not MSBuild projects) are in `BaGet.sln` as linked solution items under `samples/`, one nested solution folder per subfolder; a new or removed tracked file of a sample updates the solution in the same commit (never `node_modules`, `dist`, `.angular`). + +## Architecture + +| Project | Role | +|---|---| +| `BaGet.Core` | Domain: entities, repositories (local and remote), `IPackageDatabase`, `IStorageService`, `ISearchService`, indexing, mirroring and remote caches, options | +| `BaGet.Web.V3` | Web APIs only: V3/npm/Maven/OCI protocols, the `/api/ui` twins of the web screens, `/api/v1`, `BaGetEndpointBuilder`, `IUrlGenerator`; no view controller, no view, no reference to the front ends | +| `BaGet.Web.FrontEnd` | The web screens of the packages (`Controllers/FrontEnd`, `Views`, `ViewModels`) and `AddBaGetFrontEnd()` (registers the three front-end assemblies as application parts, `RepositoryUrlHelperFactory`); namespace root `BaGet.Web.V3` | +| `BaGet.Web.V2` | Legacy V2 OData/Atom feed, gated by `Feeds:EnableV2` | +| `BaGet.Protocol` | Standalone **client** for NuGet V3 (also shipped as a package) | +| `BaGet.Identity.Api` | Account and administration web APIs (`/api/ui` twins, form models they bind, `AddBaGetAccounts`); gated by `Accounts:Enabled`; no view controller, no view | +| `BaGet.Identity.FrontEnd` | Account and administration screens: view controllers (`Controllers/FrontEnd`) and views, `ManageViewModel`, `RepositoryLinks` (namespace root `BaGet.Identity`) | +| `BaGet.Api.Base` | What the APIs share with the screens: the `/api/ui` twin bases (`ApiControllerBase` family), `[UiApi]`, `[RepositoryPage]`, `PageHandlerAttribute`, `IScreenController` + `ScreenEndpoints`, `UiApiSecurityFilter`, `RequestPrincipalResolver`, `ScreenLinks` (namespace root `BaGet.Frontend`) | +| `BaGet.Frontend.Base` | MVC base of the screens: the view controller bases (`UiControllerBase`...), `UiApiInvoker`, `RepositoryUrlHelper`, `NavLinkTagHelper`, the layout and shared partials (`Views/Shared`); referenced only by the two FrontEnd projects (namespace root `BaGet.Frontend`) | +| `BaGet.Identity.Application`, `BaGet.Web.Application` | Use cases, DTOs and business services (accounts, API keys, ownership, `ScreenResult`, `ScreenGate`; web screen data); **no MVC/Razor reference** (`ApplicationLayeringTests`) | +| `BaGet.Catalog`, `BaGet.Validation` | Catalog resources/rebuild, validation pipeline | +| `BaGet.Database.{Sqlite,SqlServer,PostgreSql,MySql}` | One `IContext` + migrations per provider | +| `BaGet.Azure`, `BaGet.Aws`, `BaGet.Gcp`, `BaGet.Aliyun` | Cloud storage/search/table implementations | +| `BaGet` | Host and CLI entry point | + +### Subsystems are chosen at runtime, not at registration + +Storage, database, search and indexing are each resolved through `IProvider` chains: +`DependencyInjectionExtensions.GetServiceFromProviders` walks every registered provider and takes +the first non-null, each provider deciding from configuration (`Database:Type`, `Storage:Type`, +`Search:Type`). To add an implementation, register a provider in +`src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs` and an +`app.AddXyz()` in `HostServiceCollectionExtensions.AddBaGetProviders` (`src/BaGet/Hosting`) — do not resolve concrete types directly. + +### Entry point: minimal hosting + +`src/BaGet/Program.cs` is the entry point (there is no `Startup`); its building blocks are extension methods in `internal static` classes under +`src/BaGet/Hosting/`. `BuildApplication` runs `AddBaGetSettingsOverrides` / `AddBaGetLogging` / `AddBaGetTelemetry` / `ConfigureBaGetWebHost` / +`AddBaGetHost`, then `UseBaGetPipeline`; `Main` adds the commands with `AddBaGetCommands` (`HostCommandLineExtensions`) and runs +`BootstrapAdministratorsAsync` before the host. +`Main` wraps it in a McMaster `CommandLineApplication` (`import downloads [-r repo]`, `catalog rebuild [-r repo]`, `account reset-password|promote|demote|approve `), which +is configured to **collect unrecognised arguments** so host arguments like `--environment` pass +through. + +**Settings overrides file.** `AddBaGetSettingsOverrides` (`HostConfigurationExtensions`) inserts `appsettings.Overrides.json` (path from +`SettingsOverridesPath`, default in the content root / `BAGET_CONFIG_ROOT`) after the last `appsettings*.json` +source and before environment variables and the command line. `SettingsService` / +`SettingsOverridesStore` (`BaGet.Core`) write it; `AddBaGetOptions` records every options type as a +`SettingsSchemaRegistration`, and `[RestartRequired]` / `[SensitiveSetting]` on options classify them. +`[AllowedSettingValues(...)]` (string settings; `Database/Storage/Search:Type`) makes the catalog emit an `Enum` +choice with those values and is also what `ConfigureBaGetOptions` validates against (one list); +`[SettingExample(dependsOn, whenValue, example)]` gives a setting per-value examples (`SettingDescriptor.Examples`), +rendered by `_SettingField` as a placeholder/help line (never the value) via `SettingPresentation`. Examples travel in one `data-examples` JSON attribute (no per-value attribute names); the catalog throws `InvalidOperationException` for duplicate `whenValue`s (case-insensitive) or mixed `dependsOn` on one property. Tests +set `SettingsOverridesPath` to the temp directory; `UseSetting` values arrive through the *last* (chained host) +provider, so they shadow saved overrides — integration tests that save a setting must use keys the harness does +not set. + +**Registration-time configuration reads are load-bearing.** `AddBaGetAccounts` decides from +`Accounts:Enabled` *while registering services*, so configuration must be in place before +`BuildApplication` runs. This is why `tests/BaGet.Tests/Support/BaGetApplication.cs` supplies settings +with `builder.UseSetting(...)` and **not** `ConfigureAppConfiguration`, which is merged too late. +Anything read through `IOptions`/`IOptionsSnapshot` is unaffected. + +**Host hardening (`Proxy:*`, `DataProtection:KeyPath`; user docs `docs/configuration.md`).** Read from configuration at startup, no Settings page row (`ProxyOptions`/`DataProtectionKeyOptions` are bound in `ConfigureBaGetOptions`/`AddBaGetDataProtection`, not registered with `AddBaGetOptions`, so `ui-forms.txt` is unchanged). `ForwardedHeadersOptions` keeps the framework's loopback-only trust plus `Proxy:TrustedProxies`/`TrustedNetworks`; `Proxy:TrustAnyProxy` clears the lists (the old behaviour, opt-in). A single node persists the key ring with `PersistKeysToFileSystem` in `DataProtection-Keys` beside the overrides file (HA keeps it in the database; the application name is left at its default so existing ciphertexts stay valid). `FormOptions.MultipartBodyLengthLimit` is 1 MiB (`ConfigureBaGetOptions.DefaultFormLimit`); actions that take a file carry `[UploadSizeLimit]` (`BaGet.Api.Base`, a `RequestFormLimitsAttribute`, runs before the antiforgery check): add it to a new upload/push action. `RepositoryResolutionMiddleware` sets `HttpContext.Items[ResolvedItemKey]` and `RepositoryResolutionGuardFilter` (global, first) answers 500 to a `{repo}` route without it (a host that skipped `UseRepositoryResolution`). `Main` returns `Task` (`Program.RunAsync`): 1 for invalid options. The overrides file is inserted after the last `appsettings*.json` (user secrets outrank it). Test harness: `BaGetApplication` puts `Telemetry:Enabled=false` in an in-memory source just below the overrides file (outranked by a `SettingsService` save, invisible on the Settings page), because the shipped `appsettings.json` exports to `localhost:4317`; `HostHardeningTests`, `RepositoryResolutionGuardFilterTests`. + +**Read-only gate.** `MaintenanceGate` (`BaGet.Core`, singleton, in memory) closes every database write: +`MaintenanceSaveChangesInterceptor`, added in `AddBaGetDbContextProvider`, throws `MaintenanceException` from +`SaveChanges` while it is closed; `MaintenanceMiddleware` (`BaGet.Web.V3/Middleware`) maps that to 503 + `Retry-After`; the layout +shows a banner. `CloseUntilRestart` cannot be reopened. Code that stores a file and then writes the database must call `MaintenanceGate.ThrowIfClosed` first (`PackageIndexingService`, `ValidatingPackageSubmissionService`, `CatalogWriter`) so a refusal leaves no orphan file. Sign-in must still work (an admin needs the post-copy status): `MaintenanceAwareSignInManager` skips only the lockout-counter reset while closed; a failed attempt is still a refused write. A context built with `MaintenanceGate.AllowWrites(builder)` is +exempt (the copy's target). Code that catches broad `Exception` around a write must not swallow `MaintenanceException` +(controllers, `PackageValidationRunner`); `ValidationWorker` retries after it, `PackageDatabase.AddDownloadAsync` ignores it. +Raw SQL would bypass the gate: there is none outside migrations, keep it so (the one exception, the database copy's +rollback `ExecuteDelete`, runs on the copy's own target context, never on the application's). + +**Repositories.** `Repository`/`Project` (`BaGet.Core/Repositories`); `default` (key `Repository.DefaultKey` = 1) is the +repository at `/`. `Package`, `PackageOwner`, `CatalogEntry`, `PackageValidation`, `AbuseReport`, `PackageSymbol` are `IRepositoryScoped` +(`RepositoryKey`, column default 1 = how the `AddRepositories` migration assigns pre-existing rows; a **Restrict foreign key** to `Repositories`, see *Ownership foreign keys*). +The migration (all four providers) also inserts the `default` row with key 1 (PostgreSQL `setval`s the sequence), so +applying migrations outside the app (`dotnet ef database update`, a script) leaves no gap for a new repository to take key 1. `AbstractContext` filters those six on `IRepositoryContext.Current.Key` with global +query filters evaluated per query (the scope is found through EF's `ApplicationServiceProvider`, so a hand-built +context works in `default`) and stamps new rows on save; anything that must see every repository calls +`IgnoreQueryFilters()` (`DatabaseTable` copy/count/delete, `AccountDeletionService`, `PackageValidationRunner` pending list +and submission lookup). A new per-package table must implement `IRepositoryScoped` and get the filter in +`OnModelCreating`. Whoever picks the repository (routing, a worker, a command) calls `IRepositoryContext.Use(info)` before +querying, or uses `IServiceScopeFactory.CreateRepositoryScope(info)`; the validation runner switches to the queued +submission's repository itself. `IRepositoryService` finds/lists/creates (`RepositoryNames` holds the one name rule); +`EnsureDefaultAsync` restores a missing `default` row (explicit key 1) at startup and before `CreateAsync` +(which refuses when rows exist but none has key 1). The copy target is "empty" with only that seeded row, which +`DatabaseCopyService` deletes before copying the source's rows. Azure Table (`NullContext`) and `Search:Type` = +`AzureSearch` (one global index, document keys without a repository) have the default repository only: +`SupportsMultipleRepositories` is false, `CreateAsync` and `TablePackageDatabase` refuse others and +`RepositoryService.FindAsync` serves `default` only (so remote repositories cannot exist there; `Mirror:*` is read directly). +API keys can be limited to repositories (`ApiKeyRepository`; none = all): `AccountAuthenticationService` puts them in `BaGetPrincipal.RepositoryKeys`, `AccessEvaluator` refuses every action outside them (administrators too) and judges a Read as anonymous; `RepositoryAdministration.DeleteAsync` drops the rows and the keys left with none (else they would turn unlimited). +`IRepositoryAdministration` (list with package counts, `SetAnonymousReadAsync`, `DeleteAsync`: refuses `default` and any repository with packages or a pending validation; its +catalog entries, owners, validations and abuse reports are purged with it, and so is `repos/{name}/` in storage when the store is `IListableStorageService`) backs the admin screens `Repositories`, `RepositoryEdit`, `RepositoryDelete` (`AdminRepositoriesController`, `BaGet.Identity/Controllers/FrontEnd`; logic in the `Admin*UseCase`s of `BaGet.Identity.Application/UseCases/Admin`) +(names are immutable; only `AnonymousRead` is editable; writes call `MaintenanceGate.ThrowIfClosed`; feed URLs derive from `IUrlGenerator`). + +**Identity table names** (`AbstractContext.OnModelCreating`; migration `RenameAspNetTables` x4): the `AspNet` prefix is dropped (`Users`, `Roles`, `UserRoles`, `UserClaims`, `UserLogins`, `UserTokens`, `RoleClaims`; keys, indexes and foreign keys are renamed with them). Older migrations and the upgrade-test seeds (`PreRepositoryDatabase`, `OwnershipUpgradeDatabase`, `OwnershipOrphanCleanup`) keep the old names on purpose: they run before the rename. + +**Ownership foreign keys** (`AbstractContext.BuildOwnershipForeignKeys`; migration `AddOwnershipForeignKeys` x4). `RepositoryKey` -> `Repositories` on every `IRepositoryScoped` table plus `ApiKeyRepositories`, `ReplicationConfigs`, `RetentionPolicies`/`ScanPolicies` (nullable); `ProjectKey` -> `Projects` on `Repositories`, `PermissionTargets`, `RetentionPolicies`, `ScanPolicies` (nullable); `UserId` -> `Users` (formerly `AspNetUsers`, see below) on `ApiKeys`, `GroupMembers`, `OrganizationMembers`; `ReplicationRuns`/`ReplicationItems.ConfigKey` -> `ReplicationConfigs`; `OciTags.ImageKey` -> `OciRepositories`. **No cascade and no navigation property** (public entities unchanged): `Restrict` (`OciTags.ImageKey` is `NoAction`: an image delete cascades to its manifests and from them to the tags, so the check must wait for the end of the statement). Deleting a parent is still done by code, children first: `RepositoryAdministration.DeleteAsync` (+ the format modules' `StagePurgeAsync`, which now also removes Docker images/links/blobs), `AccountDeletionService`, `IAccessAdministration.DeleteProjectAsync` (also the project's retention and scan policies), `ReplicationAdministration.DeleteAsync`, `OciRegistryService.DeleteImageAsync` (tags first). `PermissionGrant`/`ProjectMember.PrincipalId` is polymorphic (user or group): no key. A background write for a deleted parent must skip, not fail: `ArtifactUsageRecorder.FlushAsync` drops the entries of a repository that no longer exists; the scan/replication workers already log and go on. **Upgrade:** the migration first runs `OwnershipOrphanCleanup.Statements` (ANSI `DELETE ... IN (SELECT ...)`, identifiers quoted per engine, children before parents, **before** SQLite rebuilds tables): owned rows of a missing repository are deleted with everything under them; keys/memberships of a missing user are deleted; an API key limited only to missing repositories is **deleted** (dropping its rows would make it unlimited); a policy left with no target is deleted, otherwise the missing reference is set NULL; a permission target of a missing project is **deleted** (nulling would widen it to every repository); a repository of a missing project gets `ProjectKey` NULL. The helper is frozen for that migration. Tests: `OwnershipForeignKeyTests` (model, enforcement, deletions, usage flush, SQLite upgrade), `EngineUpgradeTests.OrphanRowsAreRemoved...` on every engine (`OwnershipUpgradeDatabase`). + +**Format layer** (`BaGet.Core/Formats`, docs `docs/formats.md`). `RepositoryFormat` (`NuGet`, `Npm`, `Maven`, `Docker`; append-only, stored as name). `IFormatModule` (singleton, +registered with `TryAddEnumerable`, collected by `FormatRegistry`, which refuses a duplicate format / route prefix / storage folder or a claim on `repos`) +*describes* a format: `RoutePrefix`, `FeedPath`, `CreatableKinds`, `StorageFolders`, `CreateFields` + `CreateSettings`, `RepositoryLinks`, and +`CountArtifactsAsync` / `GetUsageAsync` / `StagePurgeAsync` (what `RepositoryAdministration` lists and refuses/purges on delete). What it does per request is +scoped `IFormatService`s (`IFormatIndexer`, `IFormatSearchProvider` implemented by NuGet; `IFormatRetentionHooks` and `IFormatScanner` implemented by all four formats, see *Vulnerability scanning*) found with +`GetFormatService(format)`. `NuGetFormatModule` is the NuGet refactor (no behaviour change). `RepositoryService.CreateAsync` asks the module (unknown format or +kind -> `NotSupportedException`; a `fields` overload for module-specific create forms). Format routes go through `BaGetEndpointBuilder.MapRoute(..., format:)`. +`NpmFormatModule` is registered (`CreatableKinds` local and remote, `SupportsVirtual`; a module's `SupportsVirtual` is the only thing that lets `IVirtualRepositoryAdministration.CreateAsync(..., format)` create a virtual repository of its format), so `Npm` repositories can be created: tables `NpmPackages` (repository-scoped), `NpmVersions`, `NpmDistTags` +(migration `AddNpmTables` x4; the registry needed no further schema change). Admin: `/admin/formats` (list), Repositories page (links by module, per-format create form). +The upload picker, header switcher, My packages, access listings and API-key limits cover every format (the `Format == NuGet` filters are gone). A virtual repository is of one format and so are its members (`VirtualRepositories.Flatten`/`ResolveDeploy`, `VirtualRepositoryAdministration.Validate` compare with the virtual row's format). +**Repository pages and formats:** pages are served under `/r/{repo}/` for every repository; `[RepositoryPage(Format = …)]` names a page's format (NuGet unless set; `AnyFormat` for all) and +`RepositoryActionFilter` (the check is `RepositoryPageGate`) answers 404 for a page of another format, redirecting only the NuGet front page (`/Index`) of a repository of another format to the module's `browse` link. +`RepositoryResolutionMiddleware` therefore format-checks only protocol routes, not pages. + +**npm registry** (`BaGet.Core/Formats/Npm`, user docs `docs/npm-registry.md`). `INpmRegistry` is `RepositoryNpmRegistry` (scoped), which forwards **per call** by `IRepositoryContext.Current.Kind` to `NpmRegistryService` (local), `RemoteNpmRegistry` or `VirtualNpmRegistry` (resolved per call: a write to a virtual repository continues in its deploy repository inside the same scope); `NpmRegistryService` (scoped, works in `IRepositoryContext.Current`) holds every operation of a local repository: `GetPackument(abbreviated)`, `OpenTarball`, +`Publish`/`PublishTarball`, dist-tags, `Deprecate`, `UnpublishVersions`/`UnpublishPackage`/`DeleteTarball`, `Search(canRead)`. Reads take no caller (the route or page already required Read); **every write takes the caller** +and goes through `IPackageAuthorizationService` (Push = Deploy for publish and tags, Annotate = deprecate, Manage = Delete after `Npm:UnpublishWindow`; Push is enough inside the window) so routes and pages cannot +differ; results are `NpmResult`/`NpmStatus` (mapped to 400/401/403/404/409 by `NpmController`, `{"error": …}` bodies). Names are `NpmNames` (lower case, `@scope/name`, `%2f` decoded; the one place that validates +names, versions, tags and the tarball path `npm/{name}/-/{file}` under `RepositoryStorage.Scope`). Publish: `NpmPublishBody` copies the `PUT` body to a temp file, strips `_attachments.*.data` in one lexical pass +(keys and base64 may be JSON-escaped by other encoders) and decodes each attachment from the file to another temp file, so memory is the metadata, never the tarball; `NpmRegistryService.PublishAsync` +hashes it (sha512 SRI + sha1), refuses a declared integrity/shasum/length that differs, reads `package.json` out of the tarball (`NpmTarballReader`, bounded) and requires the same name and version, then stores +the file and writes package/version/tags in one transaction (a unique-index race is a 409; a failure deletes the file it stored). The first version always gets `latest`. Publishes (and cache stores) of one version run under a per-process `KeyedLocks` key (`Comparable`: build metadata and prerelease case ignored) with the row check inside the lock; the install fields of the stored manifest (`TarballOwnedFields`, `hasInstallScript`) come from the tarball's `package.json`. A remote repository serves a tarball only under the upstream's exact version spelling. The manifest is stored as published minus +`dist.tarball` (rebuilt per request from `IUrlGenerator.GetNpmRegistryUrl`). Routes: `BaGetEndpointBuilder.MapNpmRoutes` registers every package route in two shapes (`{name}` for `@scope%2fname`, +`@{scope}/{pkg}`); `RepositoryReadFilter` decodes the name for the access patterns (`NpmRouteNames`) and adds a `Bearer` challenge; write routes are method-constrained (WritesOnly) and call +`RequestPrincipalResolver.ResolveForWriteAsync` (API key as Basic password / Bearer / `X-NuGet-ApiKey`, **never the cookie session**). Ownership reuses `PackageOwner` (`OwnershipAuthorizationService.ExistsAsync` asks the +repository's format); `npm login` = `INpmTokenService` (`NpmTokenService`, accounts only): password checked like the sign-in page (lockout, confirmed email, no two-factor), token = an API key limited to the repository. +Pages: `NpmPackages`, `NpmPackage`, `NpmUpload` (BaGet.Web), `Packages/NpmManage` (Identity; owners, tags, deprecate, unpublish with password); `NpmInstallSnippets` builds the commands and `.npmrc` lines. +Search/listings match names and are filtered per package Read (`SearchAsync(canRead)`). Write routes authorize before they look a package up, and a caller without Read on the package gets the same `404 Not found` for a refusal and for a missing package (`NpmController.RespondHidingAsync`; `NpmAccessTests`); a first publish that races another onto the package row retries on the winner's row (`NpmConcurrentPublishTests`). Names and dist-tags are case-sensitive on every engine: SQL Server and MySQL carry a binary collation on `NpmPackages.Name`/`NpmDistTags.Tag` (migration `NpmCaseSensitiveNames`; SQLite/PostgreSQL compare exactly already; `BaGet.Database.Tests.NpmNameCaseTests`). Options `Npm:UnpublishWindow`, `Npm:MaxPublishBytes` (`NpmOptions`). Admin user deletion unpublishes sole-owned npm packages (`AccountDeletionService`). +**Remote npm** (`RemoteNpmRegistry`, `NpmUpstreamClient`; docs `docs/remote-repositories.md#npm-remote-repositories`): the upstream is the generic `RemoteRepositorySettings` (`RemoteProtocol.Npm`, forced from the format by `ForFormat` in `RepositoryService.CreateAsync` and `RemoteRepositoryAdministration.UpdateAsync`/`TestConnectionAsync`; a password with no user name is a bearer token). Packuments are asked as `@scope%2fname`, remembered in `RemoteRepositoryState` under keys `na:`/`nf:`/`nd:` + the name with `/` written `%2f` (because `ClearPackage` splits keys at the first `/`; at most `NpmUpstreamClient.MaxCachedAnswers` per repository), get every `dist.tarball` rewritten to this server, and fall back to the stored rows (`NpmRegistryService.GetPackumentAsync`) when the upstream is 404/offline/down; an upstream that cannot answer with nothing stored is `NpmUpstreamException` = `502` (`NpmController.OnActionExecuted`; a virtual member skips it). A tarball is downloaded once at a time per version, hashed to a temp file, checked against the packument's `integrity`/`shasum`, and stored by `NpmRegistryService.StoreCachedAsync` (gate first; file + rows + tags in one transaction); the packument's tarball URL is used only on the upstream's origin. Writes return Forbidden; search is the stored packages; purge is `NpmRegistryService.PurgeAsync`. +**Virtual npm** (`VirtualNpmRegistry` over `VirtualRepositoryReader`; docs `docs/virtual-repositories.md#npm-virtual-repositories`): `MergePackuments` (versions union, first member per version, dist-tags per tag from the first member that has it, time min created / max modified), first-hit tarball, merged search (per-member `canRead` through `VirtualRepositoryReader.CanReadInMemberAsync`), writes delegated to the deploy repository (routes were already moved there by `RepositoryResolutionMiddleware`). +**Maven repositories** (`BaGet.Core/Formats/Maven`, user docs `docs/maven-repositories.md`). `IMavenRepository` is `RepositoryMavenRepository` (scoped, forwards per call by `IRepositoryContext.Current.Kind`, like npm) to `MavenRepositoryService` (local), `RemoteMavenRepository` or `VirtualMavenRepository`; the local one (scoped) over `MavenArtifacts`/`MavenVersions`/`MavenFiles` (repository-scoped, migration `AddMavenTables` x4) and files under `maven/{group}/{artifact}/{version}/{file}` of `RepositoryStorage`; checksums (sha1/md5/sha256/sha512) are computed once on the way in and kept in the row, `maven-metadata.xml` (group/artifact/version level, snapshot `snapshotVersions`) is generated, never stored. `MavenNames` is the one place that validates ids, versions and the request path (`ParsePath`); the access model and ownership name an artifact `group:artifact`. Settings (`MavenRepositorySettings` JSON in `Repository.Settings`: `Policy` Releases/Snapshots/Both, `AllowRedeploy`, `MaxSnapshotBuilds`) are edited on RepositoryEdit (`IMavenRepositoryAdministration`, audited). `MavenController` (`GET/HEAD/PUT/DELETE maven/{**path}` through `MapRoute` with the Maven format, so only `/r/{repo}/maven/`): reads pass `RepositoryReadFilter` (anonymous = `401` + `Basic` challenge, which makes Maven send the `settings.xml` credentials), writes call `RequestPrincipalResolver.ResolveForWriteAsync` (API key as Basic password, never the cookie) and the service authorizes (Deploy; redeploy of a release needs Delete too); a policy or existing-release refusal is `409`. Pages: `MavenArtifacts`, `MavenArtifact`, `MavenUpload` (BaGet.Web), `Packages/MavenManage` (Identity; the controller's own check 404s a non-Maven repository because it runs before `RepositoryActionFilter`); `MavenSnippets` builds the `settings.xml`/POM/Gradle text. Maven 3.8.1+ blocks plain-http repositories, so `MavenCliTests` replaces the `maven-default-http-blocker` mirror in its `settings.xml`. +**Remote and virtual Maven** (`RemoteMavenRepository` + `MavenUpstreamClient`, `VirtualMavenRepository`; docs `docs/maven-repositories.md#remote-maven-repositories`): `RemoteProtocol.Maven` (set by `ForFormat`). Files: local first, else downloaded to a temp file by `MavenRepositoryService.SpoolAsync`, checked against the upstream's `.sha1`/`.sha256`/`.md5`, stored by `MavenRepositoryService.StoreCachedAsync` (same rows/files as a deploy, no policy/ownership), one download per file (`KeyedLocks`); a text/html 200 for a file is a 404; the moving `-SNAPSHOT` name is never kept and skips the local lookup. Metadata and checksums are remembered in `RemoteRepositoryState` under path-keyed entries (`mm:`/`mc:`/`mf:` + request path; `ClearMatching` + `MavenUpstreamClient.PathPrefix` purge by artifact folder). `HEAD` goes through `IMavenRepository.HeadAsync` (no download). `ResolveAsync` of ambiguous metadata paths reads `groupId`/`artifactId`/`version` of the document (`Identify`), and `RepositoryReadFilter` calls it only after the repository-level Read passed. `MavenUpstreamException` = 502. Virtual: files first-hit, artifact metadata merged (`MergeVersions`: `latest`/`release` = first member's that the union contains), version-level first member, group-level plugins union, classification by document content; writes to the deploy repository. `IVirtualRepositoryAdministration.PreviewAsync(string version)` and `IRemoteRepositoryAdministration.PurgeArtifactAsync` take Maven versions as text. Tests: `RemoteMavenRepositoryTests`, `VirtualMavenRepositoryTests`, `AdminMavenRemoteVirtualTests` (`FakeMavenUpstream`), `MavenRemoteVirtualCliTests` (real mvn; Central test needs internet). + +**Docker registry** (`BaGet.Core/Formats/Docker`, user docs `docs/docker-registry.md`; this paragraph is the local registry, remote/virtual/GC follow). OCI Distribution Spec v1.1 **at the server root**, `/v2/{repo}/{image…}/blobs|manifests|tags|referrers/…`: the BaGet repository is the first path segment of the image name (D2), so the routes are *not* under `r/{repo}/`. They are registered once by `BaGetEndpointBuilder.MapOciRoutes` through `MapRoute(..., serverRoot: true)` with `RepositoryRouteMetadata.ResolvesRepositoryItself` (which implies `AuthorizesItself`): neither `RepositoryReadFilter` nor `RepositoryResolutionMiddleware` touches them; `OciAuthorizationFilter` (a `[ServiceFilter]` on `OciController`, every action except `Base`/`Token`) parses the path (`OciNames.Parse`, from the right, the name having any number of slashes), maps method+kind to an action (`OciHttp.Required`: pull = Read, push = Deploy, delete = Delete; a combination it does not define is refused, no default allow), finds the repository (Docker; local, remote or virtual, see below), asks `OciCallerResolver` (a registry token first, else an API key as Basic password/Bearer through `RequestPrincipalResolver.ResolveForWriteAsync`; never the cookie) and only then `IRepositoryContext.Use`. Refusals: anonymous or a token not covering the request = `401` + `Bearer realm=…/v2/token,service,scope` (**also for a repository that does not exist**, so a private repository is not told from a missing one), a key without Read = `404 NAME_UNKNOWN`, with Read but not the action = `403 DENIED`. `GET /v2/token` (`OciController.Token`) grants per requested `repository:{repo}/{image}:pull,push` scope what `IOciAccess` (access model + the key's `package:push`/`pushversion`/`unlist` scope and glob) allows; the token is `IOciTokenService` (`OciTokenService`: ASP.NET Core data protection over a JSON payload of audience, subject name, expiry and the `(repo, image, actions)` grants; **no API key inside**; `Oci:TokenLifetime`; no revocation, a removed permission applies at expiry). `IOciRegistry` (`OciRegistryService`, scoped, works in `IRepositoryContext.Current`) holds every operation and **authorizes nothing** (a token has no principal; callers decide first): upload sessions over `IStreamingStorageService` (`OciUploads` row = reference + storage upload id, bound to its image; idle ones are dropped when a new upload starts), `CommitAsync` verifies the SHA-256 while streaming, blobs stored once per repository at `docker/blobs/sha256/ab/` and **served only through `OciBlobLinks`** (image to blob; so image-level permissions cannot be bypassed by digest; `OciBlobs.RefCount` = holders, the file goes at 0; `OciBlobLinks.Manifests` counts the manifests using it, raised/lowered by `ExecuteUpdate` `Manifests = Manifests +/- 1` in the push/delete transaction, never written back as a read number, so concurrent pushes cannot lose a reference; Prune, `DeleteBlob` and the GC delete a link only with `Manifests == 0` in the delete's own condition; in-process `OciBlobCommits.LockAsync(path)` serialises an upload's commit+row against a removal's row+file delete; foreign layers (`OciParsedDescriptor.Foreign`) are not required, stored or counted), manifests are `OciManifests` rows holding the JSON exactly as pushed (`OciManifestParser` refuses non-UTF-8/BOM so the digest survives; config, layers and index children must already be linked/present: `MANIFEST_BLOB_UNKNOWN`), tags `OciTags` (case-sensitive: binary collation on SQL Server/MySQL; deleted with their manifest by foreign key), referrers from `OciManifests.SubjectDigest`. Tables migration `AddOciTables` x4; `OciRepositories`/`OciBlobs` are repository-scoped with query filters. `DockerFormatModule` (`RequiresStreamingStorage`, `FeedPath` `v2/{repo}/` = relative to the server root, `RepositoryFeedUrl` handles `{repo}`). Errors are `OciException` (code → status in `OciHttp`); `MaintenanceException` is never caught (503 by the middleware). A read of a reference that is neither tag nor digest is 404 (conformance), only a PUT answers `TAG_INVALID`. Pages: `DockerImages`, `DockerImage` (`?digest=` = manifest detail: config, layers, index platforms) in `BaGet.Web`, `Packages/DockerManage` (delete tag/manifest/image, prune unused layers; Delete action + password) in Identity; the access patterns see the image name as the package id (`RepositoryPageGate` reads the `image` route value); `DockerSnippets`. Options `Oci:*` (`OciOptions`). No upload page (the CLI pushes), no ownership. Tests: Core `OciNamesTests`; `OciRegistryTests` (protocol, token flow, access, deny-by-default route check), `DockerPagesTests` in `BaGet.Tests`; `DockerCliTests` (above). + +**Remote and virtual Docker, GC** (docs `docs/docker-registry.md#remote-docker-repositories`). `IOciRegistry` is now `RepositoryOciRegistry` (scoped, forwards per call by `IRepositoryContext.Current.Kind`, like Maven/npm) to `OciRegistryService` (local; `partial`, the cache support is in `OciRegistryService.Cache.cs`), `RemoteOciRegistry` or `VirtualOciRegistry`; `IOciRegistry.ProbeAsync` is the resolution preview. `RemoteProtocol.Docker` (set by `ForFormat`; `RemoteHttpClientFactory` adds **no** credential handler for it: `OciUpstreamClient` authenticates itself). **`OciUpstreamClient`** (scoped, over `IRemoteUpstreamSource`/`RemoteRepositoryState`/`IRemoteHttpClientFactory.CreateProbe`, redirects followed by hand, max 5, never https to http): first request anonymous, `401` + `Bearer realm,service,scope` -> token from the realm (Basic with the credentials, else anonymous; `account=` the user name), kept per scope in `UpstreamTransport.Tokens` (so a changed URL/credential drops them) until `expires_in` minus 10 s; a `Basic` challenge is answered at the registry's origin (`BasicChallenged`); a password with no user name is a static bearer token. The credential goes to the registry origin and the realm only, never to a redirect target (the CDN a layer is redirected to), and a `401` challenge is answered only when it came from the registry's own origin (a redirect target's realm is never asked). `401`/`403` after authenticating = absent (`IsAbsent`, Docker Hub answers a missing or private image so), not a failure; a refused token request is a failure (`InvalidDataException` with a safe message). Cache keys `om:`/`ob:`/`ol:` + `{image}|{detail}` (`MatchesImage` is what a purge drops); an expired tag is revalidated with `HEAD` and `Docker-Content-Digest` against the cached/stored digest. `UpstreamName` puts a single name under `library/` at Docker Hub hosts only. **Blobs** (`RemoteOciRegistry.CacheWhileStreamingAsync`): stream upstream -> client while a `CachingStream` appends to `OciRegistryService.BeginBlobCacheAsync` (an `OciBlobCacheWriter` = a storage upload recorded as an `OciUploads` row so a crash leaves an expirable session, not a lost file), 8 MiB flushes, the **last bytes are held back until the SHA-256 checked and the row recorded** (a client that has all bytes goes on at once; a mismatch reaches it as a failed download), `RecordBlobAsync(countReferences: true)` sets `OciBlobLinks.Manifests` to the number of stored manifests naming the layer (so cached layers are "used" and the GC leaves them); range requests, a digest already being cached (static `Caching` set) and a closed gate pass through; a layer another image of the repository stores is linked once the upstream `HEAD` confirms it (`LinkRepositoryBlobAsync`). Manifests are stored by `StoreCachedManifestAsync` = `PutManifestCoreAsync(checkReferences: false)` (layers/children arrive later). Writes on a remote repository: `OciException(Denied)` = `403 DENIED`; unreachable/unusable upstream with nothing stored = `OciErrorCode.UpstreamUnavailable` = `502 UNAVAILABLE`. **Virtual** (`VirtualOciRegistry`): members from `IVirtualRepositories.EffectiveMembersAsync`, filtered by `IOciRequestAccess.CanPullAsync` (scoped; `OciAuthorizationFilter` sets it to `OciCallerResolver.AllowsAsync(caller, member, …)`, so a **registry token must carry a pull grant per member**: `OciController.Token` adds them for a virtual scope; keys are judged by the access model), each question in its own `CreateRepositoryScope` (the scope of a blob lives as long as `OciBlobContent.Owner`, because a remote member's caching stream still uses its database), first answer wins, tags/referrers/images merged; writes go through `DeployTargetAsync`. `OciAuthorizationFilter` authorizes a push/delete to a virtual repository against the **deploy repository** (`OciRequest.Target`; a token is checked against the virtual name, a key against the target), runs it there (`IRepositoryContext.Use(target)`) while URLs keep the virtual name, and tells a caller who may pull that a remote/deploy-less repository `403 DENIED`. **GC** (`OciGarbageCollector`, `IOciGarbageCollector`, scoped, one repository of `IRepositoryContext`): expired `OciUploads` sessions; links with `Manifests == 0` older than `Oci:PruneGrace` except images with a non-expired session; blobs with no link left (and unlinked rows older than the grace period); files under `docker/blobs` no row names (`IListableStorageService`; skipped when `OciBlobCommits` shows a commit running or started during the listing, a process-wide counter around "file stored, row not yet written", and the rows are re-read after the listing; other nodes are not fenced); a dry run computes the same plan and changes nothing. Started from the Operations page by `OciGarbageCollectionDryRunOperation`/`OciGarbageCollectionRunOperation` (`IAdminOperation.AppliesTo(repository)` limits the rows to local/remote Docker repositories; `RequiresConfirmation` makes the page ask the password for the run); the schedule is a retention policy with `CollectGarbage` (see *Retention*). Tests: Core `OciUpstreamTests`; `FakeOciUpstream` (in-memory registry with the token flow, CDN redirect, private images, ranges, corrupt blobs, lying digests), `RemoteOciRepositoryTests`, `VirtualOciRepositoryTests`, `OciGarbageCollectorTests`, `AdminDockerRemoteVirtualTests` in `BaGet.Tests`; `DockerRemoteVirtualCliTests` in `BaGet.Clients.Tests` (real Docker pulling through a remote repository whose upstream is a private second BaGet, a public one and the reference `registry:2`, and through a virtual repository; `docker builder prune`/`image prune` between steps, else the daemon skips layers it still has). + +**Vulnerability scanning** (`BaGet.Core/Scanning`, user docs `docs/vulnerability-scanning.md`; `Scanning:*` = `ScanningOptions`, **off by default**). Tables `ScanResults` (repository-scoped, one row per +artifact version named as the format names it: NuGet id lower-cased + normalized version, npm name, Maven `group:artifact`, Docker image + manifest digest; `ScannedAt` null = never succeeded, `Error`, `Highest` -1 = none), +`ScanFindings` (cascade from the result), `ScanPolicies` (`RepositoryKey` or `ProjectKey`, each unique) and `PackageVulnerabilities.Source` (migration `AddScanning` x4; **the model sets no store default on `Highest`**: EF omits a CLR default +and the column default replaced severity 0 with -1). `IFormatScanner` per format (`Engine` Osv|Image, `ListComponentsAsync`, `ListArtifactsAsync`, `GetImageReferenceAsync`); the static `NuGet|Npm|MavenScanComponents.Of` are shared by the stored-version +scan and the deploy check (dependencies only at an exact or lowest-bound version). `IScanService` (scoped, works in the current repository, refuses while the gate is closed) scans through `IVulnerabilitySource` (`OsvVulnerabilitySource`: online +`querybatch` + `vulns/{id}`, or `Scanning:OsvOfflinePath` = a directory/zip matched by `OsvAdvisory.Affects` + `OsvVersions`; singleton `OsvState` holds the caches) or `ITrivyRunner` (`ProcessTrivyRunner`: the executable, credentials in the environment); a failed scan keeps the +earlier findings and sets `Error`. `IScanPolicyService` (a repository's policy else its project's; `ScanPolicyCache` 5 s) and `IScanGate` (scoped): `CheckDownloadAsync` before an artifact is handed out (`PackageContentController`, `NpmController.Tarball`, +`MavenController.Get` for files, `OciController.GetManifest` for non-index manifests), `CheckDeployAsync(components)` before anything is stored (NuGet: controller and Upload page via `NuGetScanComponents.TryRead`; `NpmRegistryService.PublishAsync`; +`MavenRepositoryService.StoreAsync`), `CheckStoredAsync` for Docker (scan after `PUT manifest`, delete the manifest when it reaches the threshold), `RegisterStoredAsync` after storing (Maven: forgets the result only for the main POM) (`PackageIndexingService`, npm publish/cache, Maven store/cache; forgets the earlier result of that name+version, then `RequestScan`; a manifest push uses `RequestScan`) +which queues on the singleton `ScanQueue`; `ScanWorker` (hosted) scans the queue and sweeps repositories by `RescanInterval`. A block is a `ScanBlockedException`, answered `403` by `ScanBlockedFilter` in the protocol's shape (npm `{"error"}`, OCI `DENIED`, text, +HTML for a page); a deploy check whose source is down lets the deploy through. A virtual repository's download check asks the members the caller can read (`VirtualRepositoryReader.ReadableMembersAsync`) in order and the first that holds the version (a result, or stored and scannable) decides, applying its own policy. "Block unscanned" is not enforced without a usable engine, for non-image Docker manifests (`DockerFormatScanner.GetImageReferenceAsync` is null for them; an image is decided by the manifest's media type and its config's media type, never by the self-declared `artifactType`/`subject`) or for the scanner's own pull (`IScanGate.IsScannerPullAsync`: the caller named by `Scanning:TrivyRegistryUser`, else any pull while `ScanInFlight` lists an image that has no successful scan yet, so a rescan never lifts the download-severity block). A refused Docker push puts a moved tag back (`OciManifestPut.PreviousDigest`). For NuGet the findings about the package itself are written to +`PackageVulnerabilities` with `Source` = `osv` (`SetVulnerabilitiesAsync` and the Manage page touch `Source == null` only). Repository and project deletion remove their results and policies. UI: the `_ScanFindings` partial on the four package pages, +`Packages/Scan` (`/scan-artifact`, a repository page for every format via `[RepositoryPage(AnyFormat = true)]`; `ScanAccess` = Manage through `IPackageAuthorizationService`), `Admin/Scanning`, `Admin/ScanRepository`, `Admin/ScanProject`, and the +`vulnerability-scan` `IAdminOperation`. Tests: `Scanning{Npm,NuGet,Maven,Docker,Pages}Tests` (`ScanningHarness`, `FakeOsvServer`, `FakeTrivyRunner`) in `BaGet.Tests`; Core `ScanningRulesTests`, `TrivyRunnerTests`, `OsvLiveTests` (the real OSV API, skips when unreachable). + +**Remote repositories** (`RepositoryKind.Remote`; `BaGet.Core/Repositories/Remote`, docs: `docs/remote-repositories.md`). The upstream +is `RemoteRepositorySettings` as JSON in `Repository.Settings` (no extra table; the password is stored as `protectedPassword` through +`IRemoteCredentialProtector` = data protection, only `RemoteSettingsCodec` reads/writes it, a page never gets it back, nothing logs it). +`UpstreamClientFactory` returns a `RemoteUpstreamClient` for every repository: `IRemoteUpstreamSource` resolves the upstream (remote -> its own +settings; `default` with `Mirror:Enabled` -> the `mirror` remote repository, created/synced at startup by +`IRemoteRepositoryAdministration.EnsureMirrorRepositoryAsync`, its URL/protocol/timeout owned by `Mirror:*`, the rest editable; else none). +`default` with `Mirror:Enabled` is thereby a two-member virtual repository (its own rows, then `mirror`) that keeps its URL and stores what it fetches in its own rows; no stored virtual row stands for it (see *Virtual repositories*). The client does offline mode, the metadata TTL, the negative TTL (only a real 404: +`V2/V3UpstreamClient(propagateErrors: true)` throw everything else, which is never cached as "not found" and is served stale if an expired +answer exists) and records health; `RemoteRepositoryState` (singleton, in memory per node, takes a `TimeProvider`) holds settings (5 s), +answers, counters and the pooled `HttpClient`/`NuGetClient` (a V3 service index is cached by the latter). Credentials go to the upstream's own origin only +(`HostScopedBasicAuthHandler`); replace `IRemoteHttpClientFactory` to change the transport (tests: `ForwardingRemoteHttpClientFactory`; +registering an `HttpClient` no longer affects mirroring). Cached packages are ordinary rows of the remote repository +(`PackageService.MirrorAsync` indexes into the current repository; an npm remote's are ordinary `NpmPackages`/`NpmVersions` rows, see *npm registry*). `StoreLocally=false` is a pass-through +(`IPassThroughUpstreamClient`, `IPackageService.OpenUncachedAsync`): nothing is stored. `Deploy` is never granted on a remote +(`AccessEvaluator.IsAllowedAsync`/`ExplainAsync`, administrators too), `[RemoteRepositoryReadOnly]` answers `403` on push and symbol push +(accounts off too), `AccessRepositoryAccess` hides it from the upload picker. Admin pages: create on `Repositories`, edit/test/cache/purge on +`RepositoryEdit` (create, save, test and purge ask for the password: `AdminRepositoryEditUseCase`/`AdminRepositoriesUseCase`, JSON twin `AdminRepositoriesApiController`; *Test connection* sends the stored password +only while the URL's origin and the user name are unchanged, the rule saving applies, follows redirects only within the typed origin and reads at most 1 MB; `Remote:BlockPrivateAddresses` (`RemoteOptions`, `RemoteAddressPolicy`, checked on create/save/test and on each V3 connection via `RemoteHttpClientFactory`'s `ConnectCallback`) refuses loopback/private/link-local upstreams, default off). A remote repository created with credentials starts with `AnonymousRead` off unless chosen (`IRepositoryService.CreateAsync(..., anonymousRead, ...)`); the auto-created `mirror` and every other repository start anonymous. Purge hard-deletes through `IPackageDeletionService` in a `CreateRepositoryScope`. + +**Virtual repositories** (`RepositoryKind.Virtual`; `BaGet.Core/Repositories/Virtual`, docs: `docs/virtual-repositories.md`). `Repository.Settings` is `VirtualRepositorySettings` +JSON (member names in order, deploy repository name; `VirtualSettingsCodec`; no schema change). `IVirtualRepositories` (scoped) flattens members (`EffectiveMembersAsync`: nested virtuals +expanded in place, each repository once, cycles cut, missing/non-NuGet members skipped) and finds `DeployTargetAsync` (follows virtual deploy repositories to a local one). +**Reads:** `VirtualRepositoryReader` (scoped) lists the members the caller may read (`IAccessEvaluator` Read on the member and on the package, caller from `IRequestCaller`, which +`RepositoryResolutionMiddleware` sets lazily from `RequestPrincipalResolver`) and runs a question in each member's own `CreateRepositoryScope`, so the member's filter, storage path and +upstream apply; a failing member is logged and skipped. The services that answer for a virtual repository wrap the concrete ones and delegate unchanged when the request's repository is +not virtual: `VirtualPackageService` (registered as `IPackageService`; versions = union, one version = first member), `VirtualPackageContentService` (`IPackageContentService`; first member +that has the version, through the member's `DefaultPackageContentService`), `VirtualSymbolStorageService`, `RepositorySearchService` (wraps whatever `ISearchService` is registered last: +`AddRepositoryAwareSearch()`, called at the end of `AddBaGetApplication` and again by `Program` after it registers the provider-chosen search). `DefaultPackageMetadataService` needs no +change (it sits on `IPackageService`). Merged search reads each member only as far as the page needs (first `skip + take + 1` results, 500 per call, `MaxScanPerMember` 10,000; a member of at most `ExactScanPerMember` 2,000 is read completely), keys an id by its first member's entry with versions unioned and downloads +summed, orders by id or summed downloads (a total order, so paging is stable), and reports distinct ids as `totalHits` (exact while every member was read completely, else an upper-bound estimate; downloads sums are windowed); `LastUpdated` is not a virtual +sort. The V2 controller and `VulnerabilityController` take an optional `VirtualRepositoryReader`. URLs come from the request's repository, so every link stays inside the virtual repository. +No catalog: `CatalogController` answers 404 and `CatalogServiceIndexProvider` omits the resource when the repository is virtual. `Statistics`, `ReportAbuse`, `Packages/Manage`, +`Packages/ContactOwners` are 404 on a virtual repository (`[RepositoryPage(NotOnVirtual = true)]`); the Package page hides their links. +**Writes:** `RepositoryResolutionMiddleware` moves a write route (`RepositoryRouteMetadata.WritesOnly` with a non-GET method, or `AuthorizesItself`, but not a route with `WritesContent` false: npm login/logout stay on the repository addressed) of a virtual repository to its deploy +target with `IRepositoryContext.Use(target)` before authentication (403 with no deploy target); the Upload page does the same in `RepositoryActionFilter` (`RepositoryPageGate.RequestedVirtualItemKey` in +`HttpContext.Items` remembers the virtual repository for the view). `AccessEvaluator` never grants Deploy on a virtual repository (like a remote one); `AccessRepositoryAccess` offers a virtual +repository to `WritableAsync`/`CanWriteAsync` when the caller can read it and write to its deploy target. **Admin:** `IVirtualRepositoryAdministration` (create/update with validation: members exist, +NuGet, no self/cycle, deploy repository a member that ends in a local one; `CandidatesAsync`, `ReferencedByAsync`, `PreviewAsync` = side-effect-free "where would it come from": each member's `PackageService.ProbeAsync` = stored copy, then `IUpstreamClient.ProbeAsync` (`RemoteUpstreamClient` applies the same offline / remembered-404 gate as a download), so it cannot diverge from a real request); pages are +`Repositories` (create) and `RepositoryEdit` (members add/remove/up/down, deploy picker, preview; handlers `AddMember`, `RemoveMember`, `MoveMember`, `Deploy`, `Preview`); +`RepositoryAdministration.DeleteAsync` refuses a member of a virtual repository (`RepositoryReferencedException`). `RepositoryService.CreateAsync(..., Virtual)` stays `NotSupported` +(it has no members to take). Tests: `VirtualRepositoryTests`, `VirtualRepositoryAccessTests`, `VirtualRemoteMemberTests` (+ `VirtualDefaultMirrorTests`), `AdminVirtualRepositoriesTests`, +Core `VirtualRepositorySettingsTests`, `RepositorySearchServiceTests`, `VirtualSearchBoundTests` (member call sizes). npm: `RemoteNpmRepositoryTests`, `VirtualNpmRepositoryTests`, `AdminNpmRemoteVirtualTests` +(HTTP/service tests over the in-memory `FakeNpmUpstream` and `ForwardingRemoteHttpClientFactory`), Core `RemoteAndVirtualNpmTests`. + +**Admin operations** (`BaGet.Core/Operations`). `AdminJobService` (singleton) runs `IAdminOperation`s (`DownloadsImportOperation` and the Docker GC operations in Core, +`CatalogRebuildOperation` in `BaGet.Catalog`; register more with `TryAddEnumerable`) in the background in a repository scope, one run per +(operation, repository), status in memory; `TryStart` calls `MaintenanceGate.ThrowIfClosed`. `IValidationAdministration` (impl +`BaGet.Validation/ValidationAdministration`, uses `PackageValidationRunner.ReleaseAsync`/`UseSubmissionRepositoryAsync`) lists pending/quarantined +submissions of all repositories (`IgnoreQueryFilters`) and retries/releases/rejects; `IAbuseReportAdministration` does the same for abuse reports. +`IAdminAudit` (default `LoggingAdminAudit`: a log line) is the seam for the access-audit table; release, reject, retry, resolve and job +start/end go through it. Screens (`AdminOperationsController`): `Operations`, `Validation`, `Abuse`; the Identity project reaches these through the +Core interfaces (it cannot reference Validation/Catalog). Tests: `AdminOperationsTests`. + +**Retention** (`BaGet.Core/Retention`, user docs `docs/retention.md`). `RetentionPolicy` (rules `KeepLast`, `OlderThanDays`, `UnusedDays`, `PrereleaseOnly`, `CacheLimitBytes` (remote only), `UntaggedAfterDays` + `CollectGarbage` (Docker), `NamePatterns`, `ScheduleHours`; one repository **or** one project; not repository-scoped; `RepositoryKey`/`ProjectKey` are optional Restrict foreign keys), `RetentionHold` (repository-scoped; empty `Version` = every version, never null for the unique index) and `ArtifactUsage` (repository-scoped last-download time; a version with none recorded counts as unused from `max(publish, policy.UnusedSince ?? Created)`; `UnusedSince` restarts when UnusedDays, repository, project or name patterns change), migrations `AddRetention` and `AddRetentionUnusedSince` x4. Rules are `RetentionEvaluator.Evaluate`, a pure function (union of rules, minus holds); `RetentionEngine.RunAsync(policyKey, dryRun, actor)` plans through it and, unless a dry run, deletes exactly the plan (holds re-read before each deletion; `MaintenanceException` never swallowed; a real run needs an enabled policy and an open gate) per repository in its own `CreateRepositoryScope`, through the format's `IFormatRetentionHooks` (`NuGetRetentionHooks` = `IPackageDeletionService.TryHardDeletePackageAsync`, `NpmRetentionHooks` = `NpmRegistryService.PurgeAsync`, `MavenRetentionHooks` = `MavenRepositoryService.PurgeAsync`, `DockerRetentionHooks`: a **tag** is the version (`DeleteTagAsync`), untagged manifests are `ListUnreferencedAsync` (not tagged, not an index child, not a referrer of an existing subject; version = digest; `DeleteManifestAsync`); `GetSizeAsync` is asked only for the cache limit). `CollectGarbage` runs `IOciGarbageCollector` after the rules (a dry run reports the pre-deletion state). `RetentionJobs` (singleton) runs policies in the background (one per policy, last report in memory), `RetentionWorker` (hosted, every minute, waits while the gate is closed) starts due schedules (`max(LastRun, ScheduleStart, Created) + ScheduleHours`) and flushes `ArtifactUsageRecorder`. Downloads touch the recorder (an in-memory map flushed in batches, never a DB write on the download path): `PackageService.AddDownloadAsync`, `NpmRegistryService.OpenTarballAsync`, `MavenRepositoryService` file reads, `OciRegistryService.GetManifestAsync`; usage keys are lower case. `IRetentionAdministration` edits policies and holds (gate, validation `RetentionException : AccessModelException`, audit entries `retention.*` in the same save via `AccessAdministration.Audit`; runs also go to `IAdminAudit`). Screens (`AdminRetentionController`): `Retention`, `RetentionPolicy` (dry run without a password, run/save/delete with), `RetentionHolds` (lifting asks the password). Deleting a repository drops its policies, holds and usage rows (`RepositoryAdministration`). Tests: Core `RetentionEvaluatorTests`; `RetentionTests`, `RetentionPagesTests` in `BaGet.Tests`. + +**Replication** (`BaGet.Core/Replication`, user docs `docs/replication.md`). `ReplicationConfig` (a **local** repository, `Direction` Push|Pull, `PeerUrl` + `PeerRepository`, `ProtectedApiKey`, `Enabled`, `OnDeploy`, `ScheduleMinutes`, `PropagateDeletes`, `Conflict` TargetWins|SourceWins; not repository-scoped; `RepositoryKey` is a Restrict foreign key, so are `ConfigKey` of runs and ledger), `ReplicationRun` (the log: status Running|Succeeded|Failed|Interrupted, trigger, counts, bytes, first failures in `Detail`, `ResumedFrom`) and `ReplicationItem` (the ledger of what a configuration copied; **not unique-indexed**: engine collations differ), migration `AddReplication` x4. The peer is another BaGet reached through its own protocols plus `GET /api/v1/replication/inventory/{repository}` (`IReplicationInventory`; needs an `admin:api` key, so the peer key is an administrator's). The key is protected like a remote password (`RemoteSettingsCodec.ProtectSecret`), sent as a bearer token by `IReplicationPeerFactory` over `IRemoteHttpClientFactory.CreateProbe` (the client never follows a redirect itself; every request goes through `ReplicationPeer.SendAsync`, which follows a GET/HEAD redirect by hand and adds NuGet's `X-NuGet-ApiKey` header via `AddCredentials` only on the peer's own origin; so `Remote:BlockPrivateAddresses` and tests' `ForwardingRemoteHttpClientFactory`-style seams apply), dropped when the peer's origin changes, never in a view/API/log/audit (`ReplicationConfigView` redacts). `IFormatReplicator` (scoped, per format, in the local repository's scope; `NuGetReplicator`, `NpmReplicator`, `MavenReplicator` (item = one file, digest sha256), `DockerReplicator` (`PushReplacesInPlace`: a SourceWins push moves the tag without deleting at the peer; the other formats' peers refuse to overwrite, so the engine deletes first; item = a tag, digest = manifest digest; blobs the receiver holds are not sent)) lists, pushes, pulls and deletes one `ReplicaItem` through the format's protocol; `ReplicationPlanner.Plan` is the pure decision (copy / skip / conflict / replace / delete-propagation / forget). `ReplicationEngine.RunAsync` writes the run row first, saves progress every 10 items and the ledger per copied item, ends a transport failure as `Failed` (not one failure per item) and a stop / read-only gate as `Interrupted`; **resume = another run** (plans from what both sides hold now). A pull applies the scanning deploy rules like a push (`NuGetReplicator.PullAsync` runs `CheckDeployAsync` before submitting; `DockerReplicator.PullAsync` runs `CheckStoredAsync` per image manifest and undoes a refused put with `OciPushUndo`, shared with `OciController`); a refusal is an item failure. A `SourceWins` pull replaces through `IFormatReplicator.PullReplacingAsync`: fetch and judge first (NuGet/npm/Maven preflight the scan, `NpmRegistryService`/`MavenRepositoryService.PreflightReplacementAsync`), delete the local copy after; Docker deletes nothing (the tag moves, the undo restores it); a push still deletes at the peer first. `ReplicationJobs` (singleton; one run per configuration, `Cancel`) takes `IJobLease.TryAcquireAsync("replication:{key}")` before every run: the single seam P10 replaces (`InProcessJobLease` is the default); `TryStart(..., notRun)` calls back when the lease is refused so the worker puts a consumed deploy notice back. `ReplicationWorker` (every 15 s) starts due schedules, deploy-triggered pushes (`ReplicationDeployInterceptor` notes new `Package`/`NpmVersion`/`MavenFile` rows and added/moved `OciTag` rows per repository in `ReplicationTrigger`; 5 s quiet period) and marks `Running` rows nobody runs (lease free) `Interrupted`. `IReplicationAdministration` (gate, `ReplicationException : AccessModelException`, audit `replication.*`). Pages `Admin/Replication`, `Admin/ReplicationConfig` (password for save/test/run/resume/delete); API `ReplicationController`. Deleting a repository drops its configurations, log and ledger. Tests: Core `ReplicationPlannerTests`; `ReplicationTests` (two in-process servers via `ReplicationHarness`), `ReplicationPagesTests` in `BaGet.Tests`. + +**High availability** (`BaGet.Core/Ha`, host `src/BaGet/Ha`, user docs `docs/high-availability.md`, which holds the table of every stateful singleton as shared or per node). `Ha:Enabled` (`HaOptions`, all restart-required, read at registration by `AddBaGetHa`) turns a node into a cluster member; off, nothing changes and no Redis exists (`ClusterRuntime.IsEnabled` false, `IJobLease` stays `InProcessJobLease`). `IClusterStore` (get/set/set-if-absent/extend-if-value/delete-if-value/increment/list with TTL) is the only shared backend: `RedisClusterStore` (StackExchange.Redis, version lever `StackExchangeRedisPackageVersion`, lazy connection, `AbortOnConnectFail=false`, keys under `Ha:KeyPrefix`) in the host, `InMemoryClusterStore` for tests. `ClusterJobLease : IJobLease` (key `lease:{job}` = `node|token|since`, renewed every third of `Ha:LeaseDuration`, refused when the store fails so a job is skipped, never doubled) replaces the in-process one; workers take `IJobLease? lease = null` (null = run everything) through `JobLeaseExtensions.AcquireAsync/Acquire`: `retention:schedule`, `retention:policy:{key}` (`RetentionJobs.TryStart`), `replication:{key}`, `operation:{name}:{repo}` (`AdminJobService.TryStart`), `scan:sweep`, `staging:sweep`, `validation:{submission}` (+ a 1-minute requeue of pending submissions in a cluster), `catalog:{repository key}` (`CatalogWriter.CommitAsync` waits up to 30 s so commit timestamps stay ordered across nodes; `IJobLeaseAvailability` lets it tell an unreachable store from a held lease and commit without the lease then). `ClusterSyncService` (hosted, every `Ha:SyncInterval`) publishes the node heartbeat (`node:{id}`) and syncs the **read-only gate** (`MaintenanceGate.Publisher`/`ApplyRemote`/`LocalReason`: `Close` is published as `gate` = `node|reason` and kept alive by its node, only that node `Open`s it, `CloseUntilRestart` stays local), the **access model** (`AccessModelVersion.Publisher`/`BumpFromCluster`, counter `access-version`) and the **database copy status** (`DatabaseCopyService.LocalStatus`/`RemoteStatus`; `TryQueue` refuses a copy while `ClusterRuntime.IsEnabled`: `ClusterRefusal`). Rate limiters (`ContactRateLimiter`, `PasswordResetRateLimiter`) use shared keys when the runtime has a store; `ScanInFlight` marks images in the store; `OciGarbageCollector` skips the "files without a row" step in a cluster (its in-process commit fence cannot see other nodes). `HaBackendRules` + `HaStartupGuard` (and `ValidateStartupOptions`, which makes `Main` stop) refuse HA on SQLite, Azure Table, the `Filesystem` store or without `Ha:ConnectionString`; tests lift it with `new HaBackendRules { AllowLocalBackends = true }` registered after the host's. Data protection keys: `DatabaseXmlRepository` over table `DataProtectionKeys` (encrypted with the PFX of `Ha:KeyCertificatePath` when set, else plain XML and `HaStartupGuard` warns; written through a context from `IDatabaseContextFactory` built with `MaintenanceGate.AllowWrites`, so a closed shared read-only gate never blocks a key) (`DataProtectionKeyEntry`, migration `AddDataProtectionKeys` x4), one application name `BaGet`, only in HA. `ReadinessService` (database `CanConnect`, a one-byte storage put/delete, the store ping as an `Informational` probe: reported, never a 503 cause, since a node serves without Redis; cached 5 s) backs `GET /health/live` and `/health/ready` (`BaGetEndpointBuilder.MapHealthRoutes`, anonymous, 503 + check names only) and the admin page `Cluster` (`IClusterStatusService`: nodes, leases, gate, health). Tests: Core `ClusterStoreAndLeaseTests`; `ClusterTests` (two real nodes in one process on one SQLite file, package folder and in-memory store: `ClusterHarness`); `BaGet.Ha.Tests` (`RedisClusterTests` on `redis:7.4-alpine`, skips without Docker). + +**Account approval.** `Accounts:RequireApproval` (default off) sets `BaGetUser.PendingApproval` (migration `AddUserPendingApproval` x4) on accounts created by `Register` or the first external sign-in (never by `AdminUserCreationService`). `MaintenanceAwareSignInManager.CanSignInAsync` refuses a pending user on every route (password, 2FA, external), `AccountAuthenticationService`/`SessionPrincipalFactory` give a pending user no principal; its `CheckPasswordSignInAsync` override (used by `Login` and `NpmTokenService`) honours the lockout first, counts a wrong password (`AccessFailedAsync`, a refused write while the gate is closed) and answers `NotAllowed` only to the right one, so a pending account cannot be guessed at without limit and a locked-out one reveals nothing (`Login`/npm login show the pending message only on that `NotAllowed`). `AccountApprovalService.ApproveAsync` (`Conflict` on a racing delete) backs `Users` and `UserDetail` handler `Approve` (password, `ThrowIfClosed`) and `baget account approve`; reject = Delete. `AdministratorService.SetAsync` clears `PendingApproval` on every promotion (CLI, `InitialAdministrators`, page, REST). The registration page and `ConfirmEmail` mention the approval also with email configured. REST: no approval endpoint, `UserDto.PendingApproval` only. Tests: `AccountApprovalTests`, `AccountApprovalHardeningTests`. + +**Several OpenID Connect providers** (`Accounts:OpenIdConnectProviders:`, user docs `docs/configuration.md#several-providers`). `OpenIdConnectProviders.Resolve(AccountsOptions)` (`BaGet.Core/Configuration`) turns the single `Accounts:OpenIdConnect` block (id `oidc`, callback `/signin-oidc`, unchanged so linked `UserLogins.LoginProvider = "oidc"` keep working) and the named list (`OpenIdConnectProviderOptions`: `Scopes`, `Parameters`, `UserNameClaim`/`EmailClaim`/`EmailVerifiedClaim`, `AdministratorClaim`+`AdministratorValue`, `GroupClaim`+`GroupMappings`; callback `/signin-oidc-`) into the singleton `OpenIdConnectProviderSet`, which `AddBaGetAccounts` registers and builds one handler per provider from (`OpenIdConnectProviderSetup.Configure`; an invalid id, a repeated id, a named `oidc` beside the configured block or half a mapping throws at startup). The set, not `IOptions`, says what screens offer: `ExternalLogins` (configured / linked providers of a user; `CanReauthenticate` means a linked configured provider) is used by the sign-in screen (`LoginViewModel.ExternalProviders`, one button posting `provider`; `HasExternalProvider`/`ExternalProviderName` stay), `ExternalSignInUseCase` (`StartSignIn(provider, callback)`: no provider = the only one; unknown = 404; the callback reads the provider from the external cookie's `LoginProvider`), re-authentication (`StartReauthenticationAsync(..., provider)`: the only linked provider, else `ReauthenticateViewModel.Providers` to pick), `GET /api/ui/session/external/{provider}` and the account settings *Sign-in providers* section (`LinkExternal`/`LinkCallback` browser-only, `UnlinkExternal` has a twin; password-confirmed; the last way to sign in stays). Accounts are never linked by email: each provider's first sign-in makes its own account; the email is confirmed only by that provider's verified claim. `ExternalProviderMapping` runs at each sign-in through a provider (before the session starts, skipped while the gate is closed): the administrator flag follows the claim (`AdministratorService`, never the last administrator, `IAdminAudit` actor `provider:`) and mapped groups are added/removed (`IAccessAdministration`, audited, unknown groups skipped). The Settings page edits named providers through `SignInProviderSettings` (Accounts section panel; handlers `SaveProvider`/`RemoveProvider` and twins `save-provider`/`remove-provider`; keys written to the overrides file, only providers the file holds can change, the secret is write-only and a blank one keeps it, restart-required); `AccountsOptions.OpenIdConnectProviders` is `[HiddenSetting]` so the catalog and `ui-forms.txt` list no row for it. Public constructors/methods that predate this kept their signatures as overloads (`public-api.txt` only grew). Tests: Core `OpenIdConnectProvidersTests`; `MultipleOpenIdConnectProvidersTests` (`ExternalCookieFilter` takes `provider=` and `c=type=value`), `SignInProvidersSettingsTests`. + +**Admin account tools** (`AdminUsersController`/`AdminOrganizationsController`, `BaGet.Identity`; each action re-asks the admin's password, calls `MaintenanceGate.ThrowIfClosed`, logs at Warning). +`Users` has a separate *Create a user* form (`AdminUserCreationService`: typed, generated-and-shown-once, or invite = unknown password + `PasswordResetLinkSender`). +`UserDetail` (`/admin/users/{name}`) is a list of `
` blocks (account, organizations, API keys with revoke) that other features extend. +`Organizations` / `OrganizationDetail` use `PackageOwnershipService`: `RenameOrganizationAsync` rewrites `PackageOwner.OwnerName` in **every repository** (`IgnoreQueryFilters`) in the same save and refuses a name used by a user or organization; +`DeleteOrganizationAsync` refuses while it owns any package ID in any repository, and removes its grants and project roles (`AccessAdministration.StageCleanupAsync`, shared with `AccountDeletionService`) in the same save with an `organization.delete` audit entry; `SetMemberAdminAsync`/`RemoveMemberAsync` keep one administrator. The `{name}` route segment bars `/ \ ? # %` in names created here. + +**Administration REST API** (`BaGet.Web.V3/Controllers/Api`, DTOs in `Models/Api`, catalog in `Api/Catalog`; bases `AdminApiController`/`AccessApiController` in `Controllers/Base`, `ApiProblems`/`ApiJson` in `Api/`, the filters in `Api/Filters`, `Paged` in `Models/Api`, `/api/v1`, user docs `docs/admin-api.md`). Attribute-routed controllers derived from `AdminApiController` (`[ApiController]`, `AdminApiAuthorizeAttribute`, `ApiExceptionFilterAttribute`), mapped by `BaGetEndpointBuilder.MapAdminApiRoutes` (`MapControllers()`: the only other attribute-routed controllers are the UI controllers that replace Razor Pages; the API ones have no `RepositoryRouteMetadata`/`r/{repo}` twin). They call the **same services as the admin pages** (`IRepositoryService`/`IRepositoryAdministration`, `IRemote/IVirtualRepositoryAdministration`, `IAccessAdministration`, `IRetentionAdministration`, `RetentionJobs`, `IScanPolicyService`, `AdminJobService`, `AdminUserCreationService`, `ApiKeyService`), never page models, so rules cannot diverge; a rule a page enforces in its model (password, "not the last administrator") is repeated in the controller. **Auth:** `RequestPrincipalResolver.ResolveForWriteAsync` for every method (key as Basic password / Bearer / `X-NuGet-ApiKey`; the cookie is never accepted); accepted = the global `ApiKey` (only when one is configured: an open server's "no key" superuser is refused) or an administrator's key with scope `ApiKeyScopes.Admin` (`admin:api`) and no repository limit (the owner's administrator flag is read per call). `Admin` is **not** in `ApiKeyScopes.All` (sessions and npm tokens get `All`); `ApiKeyService.CreateAsync` accepts it for administrators only (`Assignable`), and the API Keys page offers it to them. **Confirmation:** where the page asks the password (`[ApiOperation(Confirm = true)]`), `RequireConfirmationAsync` checks the owner's password in `X-Confirm-Password` (lockout-aware, a wrong one counts as a failed sign-in; the global key is its own confirmation; an owner without a password is refused); where the page asks nothing (repository delete, empty group/target/project create, rename, virtual members, dry run, hold, scan) the API asks nothing. Writes call `ThrowIfClosed` (503 + `Retry-After` as ProblemDetails). **Shape:** `application/problem+json` with a stable `code`, `Paged` lists (`page`, `pageSize` max 200), enums by name (`ApiJson.Options` via `Respond`), names (not ids) in paths and bodies. **Catalog:** every action carries `[ApiOperation(summary, "AdminGroups", "Action", Confirm, Response, Status)]` (the screen that does the same thing); `ApiCatalog.Endpoints` (read from `IActionDescriptorCollectionProvider`) feeds the `/admin/api` page (`ApiCatalogController`) and the coverage tests. **OpenAPI + Scalar** (`BaGet.Web.V3/OpenApi`, `Microsoft.AspNetCore.OpenApi` + `Scalar.AspNetCore`, levers `MicrosoftAspNetCoreOpenApiPackageVersion`/`ScalarAspNetCorePackageVersion`): `AddBaGetOpenApi` registers the documents `ui` (ApiExplorer actions under `api/ui`; security schemes `bearer` and `apiKey` only: no cookie, no Basic; screen-only twins get a "Screen only" description), `v1` (under `api/v1`; `bearer`, `basic`, `apiKey`, never a cookie) and `protocols` (`ProtocolsDocumentTransformer` reads every endpoint with `RepositoryRouteMetadata` from `EndpointDataSource`, since conventional routes are invisible to ApiExplorer); `BaGetEndpointBuilder.MapApiDocumentation` maps `/openapi/{name}.json`, the alias `/api/v1/openapi.json` (= `v1`) and Scalar at `/scalar` in one group whose filter (`ApiDocumentationAccess`) answers 404 unless the caller is a signed-in administrator or an administrator's unlimited `admin:api` key (or the global `ApiKey`). The `/admin/api` page names `/scalar` as text, not a link (`ui-forms.txt` records its links). The in-house generator (`ApiCatalog.OpenApi`, `OpenApiController`) is `[Obsolete]` and unrouted, kept only so `public-api.txt` stays a superset. Tests: `OpenApiDocumentTests`. A new endpoint = the attribute + a row in `docs/ui-coverage.md` (`AdminApiAccessTests` fails for an action without it, a page that does not exist, a missing docs row, or a route that answers anything but 401 to an anonymous caller). Not offered: password reset/invite, account deletion, account approval (users carry `pendingApproval`), organizations, validation/abuse queues, settings, per-version scan, project-admin delegation (server administrators only). Replication is offered (`ReplicationController`: configs, run/resume/stop, runs, test, `inventory/{repository}`). Tests: `AdminApiAccessTests`, `AdminApiRepositoriesTests`, `AdminApiAccessModelTests`, `AdminApiOperationsTests` (+ `AdminApiHarness`). + +**Symbols per package.** Symbols are stored by PDB (`symbols/{file}/{key}`), so `ISymbolRegistry` / `SymbolRegistry` (`BaGet.Core/Storage`) +records a `PackageSymbol` row (lower-cased ID, normalized version, file, key; repository-scoped, Restrict foreign key to the repository) when +`SymbolIndexingService` stores a PDB (after `MaintenanceGate.ThrowIfClosed`; a `MaintenanceException` is rethrown, not turned into +`InvalidSymbolPackage`). It backs the Manage page's Symbols list/delete: `DeleteAsync` removes the rows first, then each PDB via +`ISymbolStorageService.DeletePortablePdbContentAsync` unless another version of the repository still records it. PDBs indexed before the +table existed (migration `AddPackageSymbols`) have no row: still served, not listable (the `.snupkg` is not kept, so no backfill). +Azure Table (`NullContext`) records nothing (`IsSupported` false). Hard-deleting a package leaves its symbols and rows (they keep being served, as documented). +Vulnerability input rules live in `PackageVulnerabilityRules` (`BaGet.Core/Metadata`), shared by `PackageMetadataAdminController` and the Manage page. + +**Repository routes.** `BaGetEndpointBuilder.MapRoute` registers every protocol route (V3, V2, symbols, catalog, +deprecation/vulnerability, repository signatures) twice: plain (the `default` repository) and as `r:` under +`r/{repo}/` (`Routes.RepositoryPathPrefix`, `RepositoryRouteName`); a new route goes through it, never straight to +`MapControllerRoute`. `RepositoryResolutionMiddleware` (after `UseRouting`, before authentication; a host must call +`UseRepositoryResolution`) maps the `{repo}` route value to `IRepositoryContext.Use`; an unknown name, or a repository whose format is not the matched route's +(`RepositoryRouteMetadata.Format`; pages and unmarked endpoints are NuGet's; a plain route of another format meets `default`, which is NuGet) is `404`, never the default. `BaGetUrlGenerator` reads the repository from `HttpContext.RequestServices` on +each call (the registration/search builders are singletons, so an injected scoped context would pin them to one +repository), picks the `r:` route variant and prefixes `AbsoluteUrl`, so every advertised URL stays in the repository and +after the `PathBase`. The V2 feed's base is `IUrlGenerator.GetV2FeedUrl`. **Repository pages.** The screens that act on a repository are controller actions marked `[RepositoryPage]` (Index, Package, +Statistics, ReportAbuse, Upload, the format browse/upload/manage screens, Manage, ContactOwners, Scan, ValidationStatus, Profile, Admin Packages/UserPackages) and are served at their own route and at +`/r/{repo}/…`: `RepositoryActionRouteConvention` adds an `r/{repo}/` **twin selector** (`Order` -1) to every route of such an action (the `/packages` +alias included). A twin is a selector of the same action, never a second route for it: link generation then produces empty `href`s. ASP.NET Core +carries an ambient route value only to links to the *same* action, so `RepositoryUrlHelper` (an `IUrlHelper` decorator from `RepositoryUrlHelperFactory`) +adds the request's `repo` to every `Url.Action` / `asp-action` / `RedirectToAction` link to a `[RepositoryPage]` action; an explicit `repo = x` wins and `repo = null` leaves for the +default repository (a link to any other page is untouched). New repository page: mark its actions `[RepositoryPage]`. The request's +repository is `IRepositoryContext`; `IRepositoryAccess` (`BaGet.Core`, default `OpenRepositoryAccess`: every NuGet repository, default +only when `SupportsMultipleRepositories` is false) is the one place that decides which repositories the UI offers: the header +switcher (`_Layout`, only on repository pages, hidden for fewer than two), the Upload picker, My packages (grouped by repository) +and `RepositoryActionFilter` (404 on a repository the caller cannot read). Every repository advertises its own +`PackageDetailsUriTemplate` / `ReportAbuseUriTemplate`. Links from account/admin pages to a package page of a given repository go through `RepositoryPageLinks` (`BaGet.Identity`; default at `/packages/…`, others `/r/{name}/packages/…`, the pages' twin routes); `AccountDeletionService` works per repository (`SoleOwnedPackage`, deletes in each via `CreateRepositoryScope`). + +**Storage layout** (`RepositoryStorage`, `BaGet.Core/Repositories`): **File storage writes are atomic**: `FileStorageService.PutAsync` writes `..baget-tmp` and moves it into place (never listed), so a failed put leaves nothing at the final path. `default` keeps `packages/…`, `symbols/…`, `catalog/…`, +`validation/…`, `staging/…` byte for byte (existing stores need no migration); every other repository nests the same +layout under `repos/{name}/` (`repos` is no default prefix, so no collision). `PackageStorageService`, +`SymbolStorageService`, `StoragePackageStagingService`, `CatalogWriter`/`CatalogReader` and the validation staging +(`ValidatingPackageSubmissionService.StagedPath(repo, id)`, used by the runner after it switches repository) take an +optional `IRepositoryContext` (null = default). Never build a path from a name without `RepositoryStorage.Prefix`, which +re-validates it. `StagingSweepWorker` sweeps each repository in its own scope. + +**Streaming storage** (`IStreamingStorageService : IStorageService`, `BaGet.Core/Storage`; user docs `docs/formats.md#streaming-storage-b2`). Optional +capability for blobs too big to buffer (Docker layers): `BeginUpload` / `Append(id, offset, chunk)` (wrong offset = +`StorageUploadOffsetException` with the real length) / `Commit(id, path, sha256?)` (path only known at commit) / `Abort`, plus `GetInfo` +(HEAD) and `GetRange`. Implemented by FileSystem, Null, S3 (multipart + `.tail` object + ranged copy), Azure (staged blocks), GCS +(resumable session over HTTP + tail) and Aliyun (as S3; **no emulator**, unverified live). S3/Aliyun/GCS read a range as 64 MiB windows (`WindowedReadStream`, retries from the exact byte); Azure orders staged blocks by the index inside the base64 id, never by id text. Uploads live under `.uploads/`; a node that +lost the running SHA-256 (`UploadDigestTracker`) recomputes it streaming at commit. `IFormatModule.RequiresStreamingStorage` makes +`RepositoryService.CreateAsync` refuse (`StreamingStorage.Require`) a non-virtual repository of that format on a store that cannot stream. +`tests/BaGet.Storage.Tests`: one contract (`StreamingStorageContract`) per provider on Testcontainers (Azurite, S3Mock, `oittaa/gcp-storage-emulator`), +skips without Docker; `BAGET_STORAGE_LARGE_BYTES=5368709120` runs the 5 GB memory test (run one provider at a time: the probe is process-wide). +Kestrel's body limit is off (`Program.cs`); IIS caps a single request (`IISServerOptions.MaxRequestBodySize`, `maxAllowedContentLength`), so chunk or raise them. + +**Access model** (`BaGet.Core/Access`; user docs `docs/access-control.md`). Tables `Groups`, `GroupMembers`, `PermissionTargets`, `PermissionGrants`, +`ProjectMembers`, `AccessAuditEntries` (migration `AddAccessControl` x4; grants/members cascade from their group/target/project). The migration seeds +groups *Everyone*/*Authenticated* (keys 1, 2), targets "Anyone reads every repository" (Read) and "Authenticated users deploy" (Annotate|Deploy|Delete|Manage, +not only Deploy: ownership-based unlist/deprecate/Manage page worked before the model, so B3 equivalence needs them) and one grant each (PostgreSQL `setval`s +the sequences). `IAccessEvaluator` (scoped; `AccessEvaluator`) answers `IsAllowedAsync(principal, repository, packageId?, action)`: +superuser and `IsAdministrator` always, else the union of grants of targets matching repository (globs) and package (include/exclude; a null id is a +repository-level question), for the principal's user id, groups (Everyone/Authenticated implicit), organizations, plus project roles on +`Repository.ProjectKey`. `RepositoryRouteMetadata.AuthorizesItself` exempts the validation-status route from `RepositoryReadFilter` (its controller authorizes Push/Manage per package), `IRepositoryAccess.CanWriteAsync` (Deploy; Read for anonymous) gates the Upload screen in `RepositoryActionFilter` (`RepositoryPageGate`), and `AccessUpgradeCheck.WarnAsync` logs at startup the private repositories nobody can read. `Repository.AnonymousRead` = false drops *Everyone*'s Read there (target grant or project role) (`AccessSnapshot.Granted`); `RepositoryAdministration.SetAnonymousReadAsync` +re-creates an "Anonymous read {name}" target when turning it on finds none. `NullContext` (Azure Table) has no model: Read open, writes for any authenticated +principal. State is one `AccessSnapshot` in the singleton `AccessModelCache` (targets, grants, repositories, project members; per-user memberships loaded lazily +and kept with it), reloaded when `AccessModelVersion` changes or after 30 s; `AccessModelSaveChangesInterceptor` (added next to the maintenance one) bumps the +version after any committed save touching those tables, `Repository`, `Project`, `Organization(Member)`, so no editor can forget; `ExecuteUpdate/Delete` would +bypass it (none do). Edits go through `IAccessAdministration` (audits in the same save, refused by the maintenance gate). `OwnershipAuthorizationService` asks the +evaluator first (Push -> Deploy, Manage -> Delete, new `PackageAction.Annotate` -> Annotate; repository = `IRepositoryContext.Current`), then applies ownership. +**Reads**: `BaGetEndpointBuilder.MapRoute` tags every protocol endpoint with `RepositoryRouteMetadata`; `RepositoryReadFilter` (a global MVC resource filter, so +every host gets it; every HTTP method, since an action without `[HttpGet]` answers any; only routes constrained to write methods, `RepositoryRouteMetadata.WritesOnly`, skip it for those) requires Read on the repository and, for a route with `{id}`, on the package: anonymous -> 401 + +`WWW-Authenticate: Basic realm="BaGet"`, signed in without Read -> 404. Credentials: `RequestPrincipalResolver` (Basic password = API key with the user name +checked against the key's owner, else `X-NuGet-ApiKey`, else the cookie session through `ISessionPrincipalFactory`, implemented by `SessionPrincipalFactory`); +bad credentials count as none. Pages: `RepositoryActionFilter` (a page with `{id}` also needs Read on the package: `CanReadPackageAsync`) -> `IRepositoryAccess` (`AccessRepositoryAccess`, replaces `OpenRepositoryAccess`): anonymous visitor +is challenged (sign-in redirect) when the host has a default challenge scheme, else 404. Database copy treats the built-in groups/targets/grants as seeded rows +(`SeededCountAsync`, removed from the target before copying). Account/organization deletion removes the identity's memberships, grants and project roles. +The Manage page and its link need ownership **and** one of Manage/Delete/Annotate (`ManagePermission.HeldAnyAsync`); each handler then asks the action the protocol asks for the same change (`PackageManageUseCase.RequireAsync`: Delete to unlist/relist/delete/delete symbols, Annotate to deprecate and edit vulnerabilities, Manage for owners and reports); administrators bypass both. Search and V3 listings are filtered per repository only, not per package pattern; `RepositoryReadFilter` does check the package for the V2 by-id endpoints and `v3/autocomplete?id=` (the id from the route or the `id` query value, OData quotes removed). + +**Access admin pages (U3, `BaGet.Identity` `Controllers/FrontEnd`; user docs `docs/access-control.md#admin-pages`).** **Migrated to MVC (wave 2 `mvc-admin-access`): Groups, GroupDetail, Permissions, PermissionDetail, Projects, ProjectDetail, Audit are `AdminGroupsController`, `AdminPermissionsController`, `AdminProjectsController`, `AdminAuditController` (base `AccessControllerBase`, which carries what is said below; views in `Views/Admin{Groups,Permissions,Projects,Audit}`, view models `Models/Access`, logic in `UseCases/Access` over `AccessUseCaseBase`; who may open a project/target screen is `AccessAuthorization`, and the controller picks it from the action's route template: the detail screens have a `{name}` segment); the page models were removed.** `AccessControllerBase` is the base of +`Groups`, `GroupDetail`, `Permissions`, `PermissionDetail`, `Projects`, `ProjectDetail`, `Audit`: it overrides the admin check with a virtual `AuthorizeAsync` (default +server administrator; `Projects`/`ProjectDetail`/`PermissionDetail` also admit the project's `Admin` role holders, found by route value), redirects to +`AccessUnavailable` when `IContext` is `NullContext`, calls `MaintenanceGate.ThrowIfClosed` on every POST, and `ActAsync(password, confirm, change, redirect)` asks for +the password (`IsConfirmedAsync`, the `_ConfirmPassword` partial) and turns `AccessModelException` into the page's `Error`. Password rule: every change except +creating an empty group/target/project and renaming a group. Project administrators may not assign repositories or delete the project, and a project target's preview +is cut to the project's repositories. Reads for the pages are on `IAccessAdministration` (`ListGroups/GetGroup/ListTargets/GetTarget/ListProjects/GetProject/ +ProjectRolesOfUser/IsProjectAdmin/ResolvePrincipal/SearchUsers/Audit(AuditFilter)`, plus `RenameGroup`, `DeleteProject`, `SetRepositoryProject`); the +evaluator explains (`IAccessEvaluator.ExplainAsync` -> `AccessExplanation`/`AccessReason`, from the same `AccessSnapshot.Granted` walk, so explanation and decision cannot +diverge) and summarises a repository (`DescribeAsync` -> `RepositoryAccessSummary.Who(action)`). `AccessPatterns` (public wrapper over the internal `GlobSet`) is what +the pattern preview and test box use. `/admin/users/{name}` got the groups, projects and effective-permission sections, `/admin/repositories/{name}` the effective +access, `/account/access` (`Account/Access`) lists only repositories where the user holds an action (no existence leak). The partials `_Explanation`, `_PatternFields`. + +**UI: controllers and views (the Razor Pages to MVC migration is implemented).** Every BaGet screen is a controller action plus a view; BaGet ships **no `@page` file**. The old page-model types (`LoginModel`, `UsersModel`, `AccountPageModel`, `AdminPageModel`, ..., `RepositoryPageFilter`, `RepositoryPageRouteConvention`; the former `Compat/` folders) were **removed**: a breaking change for code that referenced them; URLs, forms and handler names are unchanged; **a screen is identified by its controller and default GET action** (`ScreenRef`, `ScreenCatalog`), never by a page name: `Url.Page`/`asp-page`/`RedirectToPage` with a BaGet page name no longer resolve (breaking, `docs/devops-manual.md`). `AddRazorPages()` stays registered (a host's own pages, host `Pages/Shared` overrides; BaGet ships no `Pages/` folder: its views, layout and partials are all under `Views/`); BaGet registers **no** page convention or page filter. Non-breaking is defined by three snapshots in `tests/BaGet.Tests/Contracts/`, which must pass unchanged after every UI change: `ui-routes.txt` (`UiRouteContractTests`: templates, twins, order, `METHOD:handler`), `ui-forms.txt` (`UiFormContractTests`: per caller anonymous/user/admin over ~190 addresses: status, redirect, title, forms, antiforgery, links, query-string order included; plus a test that posts every form without a token and expects 400) and `public-api.txt` (`PublicApiSnapshotTests`: a superset check, pruned when the shims were removed); regenerate only for a reviewed contract change with `BAGET_UPDATE_CONTRACTS=1`. +Building blocks (`BaGet.Api.Base` and `BaGet.Frontend.Base`, `Mvc/{Attributes,Screens,UI}` and `Security`, namespaces `BaGet.Frontend.*`): `PageHandlerAttribute` (action selector by `?handler=`, route value then query, unknown = default handler; the actions of one screen are those of the controller that share their own route templates, `PageHandlerAttribute.ScreenOf`; the default action of a screen with named handlers must carry `[PageHandler]`), `ImplicitPageHandlerAttribute` (a default POST that renders the screen, for a form posted to its own URL), `ScreenRef` (`BaGet.Identity.Application/Screens`: controller without the suffix + the action that answers a plain GET, written `AdminUsers/Index`; `ScreenCatalog` has one member per screen, used by `ScreenNext`, `ScreenLink`, `IScreenLinks` and the use cases; `ScreenEndpoints` (`BaGet.Api.Base`) says whether an action is a screen (an action of a controller implementing the marker `IScreenController`, which `UiControllerBase` does and the twins never do, that is not a `[FallbackHandler]`) and which screen it belongs to, and is what `NavLinkTagHelper`, `ScanBlockedFilter`, `RepositoryResolutionMiddleware`, the coverage and contract tests use), `FallbackHandlerAttribute` (the `NoHandler` fallback of a manage controller), `RepositoryPageAttribute` (`Format`/`AnyFormat`/`Upload`/`NotOnVirtual`/`NotOnRemote`/`FrontPage`: `RepositoryActionRouteConvention` adds the `r/{repo}/` twin, the global `RepositoryActionFilter` runs the repository check through `RepositoryPageGate`), `UiControllerBase` (`[AutoValidateAntiforgeryToken]`) and the bases `AccountControllerBase`/`AdminControllerBase`/`AccessControllerBase`/`RepositoryControllerBase`/`RetentionControllerBase`/`ReplicationControllerBase` (admin check, `NullContext` redirect, gate on POST, `ActAsync` password confirmation; shared rules in `AccountSupport`/`AccessSupport`). A controller base's `OnActionExecuting`/`OnActionExecutionAsync` runs before the global repository filter. So the four manage use cases answer 404, not 403, to a caller who cannot read the package (`PackageScreenServices.CanSeeAsync`), and the re-authentication return address is application-relative (`"~"` + path + query) so a path base is kept. Public helper methods of a controller must be `[NonAction]` or non-public. +Controllers (`BaGet.Web.FrontEnd/Controllers/FrontEnd` (view controllers; protocol controllers are in `Controllers/Protocols`): `HomeController` (`/`, `/index`, `/packages`; `[RouteNotForLinks]` keeps links on `/packages`), `PackageController`, `StatisticsController`, `ReportAbuseController`, `ApiCatalogController` (`/admin/api`), `LegalController`, `UploadController`, `NpmBrowseController`, `MavenBrowseController`, `DockerBrowseController`; `BaGet.Identity.FrontEnd/Controllers/FrontEnd` (all view controllers; the JSON twins are in `BaGet.Identity.Api/Controllers/UI`, the bases in `BaGet.Frontend.Base` / `BaGet.Api.Base` `Controllers/Base`): `Account*`, `ProfileController`, `PackageManage`/`NpmManage`/`MavenManage`/`DockerManage`/`ContactOwners`/`ScanArtifact`/`ValidationStatusPageController` (not `ValidationStatusController`, the validation protocol controller), `AdminUsers`/`AdminOrganizations`/`AdminSettings`/`AdminPackages`/`AdminOperations`/`AdminGroups`/`AdminPermissions`/`AdminProjects`/`AdminAudit`/`AdminRepositories`/`AdminRetention`/`AdminScanning`/`AdminReplicationController`). Views are in `Views//.cshtml`, view models in `Models/` and logic in `UseCases/` of the two Application projects (see the JSON UI API paragraph below; no `*Workflow` class exists). `AdminControllerBase.Flash(model)` replaces `[TempData] Message/Error`; a login/account flow answers a `ScreenOutcome`. +Rules for a view: **link by controller/action** (`asp-controller` + `asp-action` + `asp-route-handler="X"` for a named handler, or `Url.Action`; `?handler=` stays in the URL, and the order of route values is part of `ui-forms.txt`: put `handler` after the other route values); an MVC view has no ambient page or action values, so every handler button/form names its controller and action and carries its own `asp-route-*` values. No `asp-page`/`Url.Page` is left: the `nav-link` anchors in `_Layout` use `asp-controller`/`asp-action` (`NavLinkTagHelper` compares them with the current screen), `FormatLink` (public `IFormatModule` data) carries `Controller` + `Action` (`FormatLink.ToScreen`) or a `Path` (`FormatLink.ToPath`), `ApiOperation` takes the screen as strings, `"AdminUsers", "Index"` (controller without the suffix + action; the API assemblies cannot reference the view controllers, so `ScreenCatalogTests` resolves every `[UiApi]`/`[ApiOperation]` name against the registered screens), `RepositoryEditViewModel.BrowseScreen` is a `ScreenRef`; C# code redirects with `RedirectToAction` or answers a `ScreenNext(ScreenCatalog.X)`; `AccountSupport.AbsoluteLink` builds an email link. The layout and the shared partials are in `BaGet.Frontend.Base/Views/Shared` (`_ScanFindings`, used by the package pages only, is in `BaGet.Web.FrontEnd`); BaGet's views name the layout and the `_Avatar`/`_ScanFindings` partials by name (`Layout = "_Layout"`, ``), never by absolute path, so a host copy in its own `Pages/Shared` or `Views/Shared` overrides them (`HostViewOverrideTests`); BaGet has no `Pages/` folder any more (the forwarding stubs for the old `Pages/...` paths were removed). `MapControllers()` maps the UI controllers (attribute routes). A manage controller's `NoHandler` fallback (`[HttpPost, PageHandler, FallbackHandler]` answering 404): without any default POST, routing would answer 404 for a stray `
` before the antiforgery filter could answer 400, and the fallback must stay out of `ui-routes.txt`. A screen with no handler at all (`AccessUnavailable`) is a GET action without `[PageHandler]`. `PackagesModel` (Account, a static class of summarising helpers in `BaGet.Identity.Application/Models/Packages`; `OwnedPackage`, `OwnedVersion`, `RepositoryPackages` are top-level types beside it) holds the owned-package types shared with `Admin/UserPackages`; `ReauthenticateView` (same project) stays (every sensitive form's `_Reauthenticate` partial takes it). **Account screens are split (UI API wave 1, `split-account`):** `AccountController`, `AccountSettingsController`, `AccountOrganizationsController`, `AccountPackagesController` and `ProfileController` only bind the form, call their JSON twin in process (`AccountApiController`, `AccountSettingsApiController`, `AccountOrganizationsApiController`, `AccountPackagesApiController`, `ProfileApiController` under `Controllers/UI`, routes `/api/ui/account/...` and `/api/ui/profiles/{name}`) and render; the rules are the use cases of `BaGet.Identity.Application/UseCases` (`SignInUseCase`, `RegistrationUseCase`, `AccountSettingsUseCase`, `TwoFactorUseCase`, `ApiKeysUseCase`, `AccountOverviewUseCase`, `ProfileUseCase`), registered by `AddBaGetAccounts`. Self-service is cookie-only (an API key is 403; only the public profile accepts one); a form is a `...Form` class with the DataAnnotations (`LoginForm`) and the screen's model derives from it (`LoginViewModel : LoginForm`), so a request never binds the outputs; use cases validate with `ScreenValidator` and answer `ScreenResult`; a redirect to a local address is `ScreenNext.LocalUrl` (`LocalUrls` is the return-URL rule). The external provider's challenge/callback (`ExternalSignInUseCase`) are browser-only and have no twin; `UiControllerBase.Render(modelShowsFormErrors: true)` is for views that print `Model.Error` themselves. **Traps:** a `Views/` named like a type (`Package`, `ApiCatalog`) gets the generated namespace `BaGet.Web.`, which hides that type: give the view its own `@namespace`; **New screen:** controller + view + use case + twin, a `ScreenCatalog` member, a `Controller/Action` token in a row of `docs/ui-coverage.md`, `[RepositoryPage]` if it acts on a repository, and regenerate the snapshots (a reviewed contract *addition*). + +**JSON UI API (implemented; user docs `docs/ui-api.md`, its "Adding a screen" section is the how-to).** Every screen has a JSON twin under `/api/ui/...` that does the work and answers a `ScreenResult` (`Status` Ok/Invalid/NotFound/Forbidden/SignIn/Next, `Model`, `Errors`, `Next`; JSON through `UiApiJson`: camelCase, enums by name); the view action calls the twin **in process** (`UiControllerBase.Api` -> `UiApiInvoker`, same `ControllerContext`) and only `Render`s the answer; a view controller holds no use case or Application service (`ApplicationLayeringTests.AViewControllerHoldsNoUseCaseOrApplicationService`; only the browser-only external-provider step names `ExternalSignInUseCase`), and no `*Workflow` class exists. Logic lives in `BaGet.Identity.Application` and `BaGet.Web.Application` (use cases, DTOs, business services; no MVC/Razor reference, test-enforced); the view controllers and views are in `BaGet.Identity.FrontEnd` / `BaGet.Web.FrontEnd` (MVC base in `BaGet.Frontend.Base`), the twins in `BaGet.Identity.Api` / `BaGet.Web.V3` (shared base in `BaGet.Api.Base`); the API assemblies reference no front end and declare no `Mvc.Controller` (`ApplicationLayeringTests`; the protocol controllers derive `ControllerBase`). The twin's filters do not run in process, so the view controller base runs the same `ScreenGate` (accounts on, mail, signed in, administrator / project administrator (a key is admitted by the twin's `AlsoAllow` only with `admin:api` and no repository limit, like the administration API), access model, writable; `AccountControllerBase`/`AdminControllerBase`/`AccessControllerBase` and `AccountApiControllerBase`/`AdminApiControllerBase`/`AccessApiControllerBase` both ask it) and its own antiforgery and cookie session. Twins derive from `ApiControllerBase` (`BaGet.Api.Base`, `Controllers/Base`; never `[ApiController]`, never a view controller; `[UiApi("AdminUsers", "Index", Handler = ...)]` names the screen: view controller without the suffix + its default GET action), are routed `api/ui/...` (`RepositoryActionRouteConvention` adds `api/ui/r/{repo}/...` for `[RepositoryPage]`; `RepositoryActionFilter` answers JSON 401/404, and 404 to a key limited to other repositories). `UiApiSecurityFilter` (HTTP only) judges, in order: HTTP Basic (**refused with 401**: browsers cache Basic credentials and re-send them cross-site); a **session token** (`Authorization: Bearer bgs.…`, see *Interactive sessions* below; invalid = 401); an **API key** (`Authorization: Bearer` or `X-NuGet-ApiKey` via `RequestPrincipalResolver.ResolveForWriteAsync`: the key's owner acts within its scopes and repository limit; an invalid key is 401, never anonymous; a key beside a session is a key); the **cookie only with a valid antiforgery header** (`X-XSRF-TOKEN`, `UiApiCaller.AntiforgeryHeader`, checked with `IAntiforgery.ValidateRequestAsync` because `IsRequestValidAsync` waves GET through, for every method; `GET /api/ui/antiforgery` hands the token out, bound to the cookie's user; `AddBaGetAccounts` sets `AntiforgeryOptions.HeaderName`); else **anonymous**: `HttpContext.User` is reset (`UiApiCaller.SetAnonymous`, the cookie user remembered for the antiforgery endpoint only), the resolver's per-request cache is forgotten and the request carries `AccountConfirmation.IgnoreSessionItem`, which makes the re-authentication proof (`HasReauthenticatedRecentlyAsync`, the only other cookie read) answer false. The view controllers keep `[AutoValidateAntiforgeryToken]` and their cookie, and their in-process call of the twin skips the HTTP filters. A session (token or cookie+header) is recorded in `HttpContext.Items[RequestPrincipalResolver.InteractiveItem]` as a `BaGetPrincipal` with `IsInteractiveSession` (every scope, no repository limit, administrator read per call); `UiApiCaller.Key` is keys only, `UiApiCaller.Interactive` sessions only, and the resolver returns the session first. Admin twins need an administrator's interactive session, or an administrator's key with `admin:api` and no repository limit (401 without a credential, 403 for another user's session or key: `GateRequest.InteractiveSession` makes `ScreenGate` answer 403 instead of 404); **the global `ApiKey` is refused there with 403** (`ScreenGate.IsAdministratorKey`: it has no owner, so use cases that need the current user could not act). Account self-service and package ownership twins (`AccountApiControllerBase`, `CookieOnly`) are **interactive-only**: over HTTP (`GateRequest.OverHttp`) they answer an interactive session normally (same password confirmations; an account without a password confirms within the window of the token's authentication time, `AccountConfirmation.SessionAuthenticatedItem`) and 403 "use the web screen" to an API key and to an anonymous caller (a leaked CI key must not change the account); the OpenAPI document marks them "Interactive session only". The gate's refusals carry a message (`GateResult.Message`, `ScreenResult.Forbidden(message)`/`SignIn(message)`, in `errors[""]`). Browser-only (no twin, an explicit commented allow-list in `UiApiParityTests`): the external provider's challenge and callback, and the re-authentication step. Contracts: `ui-api.txt` (regenerate with `BAGET_UPDATE_CONTRACTS=1`, never hand-merge), `UiApiParityTests` (every view action of a screen, per screen **and** per handler and GET/POST, has a `[UiApi]` twin except the allow-list and `[ImplicitPageHandler]` re-renders; JSON equals the rendered model), `UiApiAccessTests` (keys, no bare cookie, no Basic, global key), `UiApiAccountTests` (every interactive-only twin is 403 to a key, an anonymous caller and a bare cookie), `UiApiSessionTests`, `OpenApiDocumentTests`, `PublicApiSnapshotTests` (a moved type counts by namespace + name; `[TypeForwardedTo]` required in the old assembly). **Interactive sessions** (`/api/ui/session`, `SessionApiController` in `BaGet.Identity.Api`, no `[UiApi]`, not part of the parity rules; logic `SessionUseCase`/`ExternalSessionUseCase` in `BaGet.Identity.Application`; 404 while accounts are off): `POST /session` (user name + password through `SignInManager.CheckPasswordSignInAsync`: lockout first, wrong password counted, approval/unconfirmed answered only to the right password; an account with two-factor gets a 5-minute `twoFactorTicket`), `POST /session/two-factor` and `/session/recovery-code` (a wrong code is counted and locks), `POST /session/refresh` (rotates, keeps the authentication time), `POST /session/sign-out` (`everywhere` updates the security stamp), `GET /antiforgery`, `GET /session/external/oidc?returnUrl=` + `GET /session/external-callback` (tokens in the URL fragment of `returnUrl`; `SessionReturnUrls.IsAllowed`: a path of this server or an origin in `Cors:AllowedOrigins`, an empty list is *not* "any" here; the page's cookie is dropped). Tokens are `SessionTokenService` (`bgs.` + data protection of `{ user id, security stamp, authentication time, expiry }`, one purpose per `SessionTokenKind` (Access, Refresh, TwoFactor, Exchange), stateless, capped at `Accounts:SessionMaxLifetime` from the authentication time); `SessionAuthenticator` re-checks the account (exists, not pending; **not** lockout, like a cookie session) and the stamp in constant time on every use, so a password change or sign-out-everywhere ends every token. Every action of `SessionApiController` (and the anonymous account twins: register, confirmemail, forgotpassword, resetpassword) carries `[AnonymousSessionEndpoint]` (`BaGet.Api.Base`): `UiApiSecurityFilter` treats an invalid session token there as no credential, refuses a browser `Origin` that is neither this server's nor (unless `SameOriginOnly`) listed in `Cors:AllowedOrigins`, optionally requires an anonymous antiforgery token (`POST /session/cookie`, which signs in with the cookie through `SessionUseCase.CookieSignInAsync`), and `AccountApiControllerBase` lets an anonymous (not key) HTTP caller through; over HTTP (`AccountConfirmation.OverHttpItem`) registration answers tokens instead of setting the cookie and is rate limited with `PasswordResetRateLimiter` (`register:`/`resend:` targets). Over `/api/ui` (`AccountConfirmation.IsHttpSession`) the two-factor setup key needs `X-Confirm-Password`, and enabling two-factor and creating an API key need `password` in the form (`TwoFactorCodeForm.Password`, `ApiKeyForm.Password`). Exchange tokens work once (`ExchangeTokenLedger`: hashes kept until expiry, `IClusterStore` with HA); the SPA binds the redirect with a `state` in `returnUrl`'s query (documented). `SessionReturnUrls` resolves a same-origin path (dot segments, `%2e`) before judging it against `SpaBasePath`. The filter's origin rule also accepts the origin of `Site:PublicUrl`. Registration charges the per-email allowance only after the account exists. The OpenAPI `ui` document is shaped by `UiDocumentShape` (string enums, integers, 400/401/403/404 like 200, optional route values as separate paths; tested in `OpenApiDocumentTests`). The external provider's result is a 60-second `Exchange` token in the fragment (`ExternalSessionUseCase`, `POST /session/exchange`), the callback sets no cookie (`ExternalSignInUseCase.CompleteForSessionAsync`) and cleans only the external cookie. A stamp change caused by the current token session (`MaintenanceAwareSignInManager.RefreshSignInAsync`, which keeps a cookie session signed in) answers renewed tokens in the `X-Session-*` headers (`SessionHeaders`, exposed to CORS). Only `/api/ui` accepts a token: `RequestPrincipalResolver` treats a `bgs.` credential elsewhere as no credential (tested on push, `/api/v1`, the registry). Settings `Accounts:SessionTokenLifetime` (15 min) / `Accounts:SessionRefreshLifetime` (14 days) are `[HiddenSetting]` (the Settings page, and so `ui-forms.txt`, stay unchanged). Tests: `UiApiSessionTests`, `UiApiHostingTests`. **Hosting a single-page application** (`src/BaGet/Hosting/HostFrontendExtensions.cs`, `docs/configuration.md#single-page-applications`): `Cors:AllowedOrigins` (`CorsSettings`, `ConfigureBaGetOptions.AllowedOrigins`, validated in `AddBaGetHost`: an invalid entry stops startup; three policies, `AllowAll` for everything but `/api/ui`, `UiApi` and `UiApiSession`: with a list the listed origins with credentials on `/api/ui` only, with no list any origin without credentials except `session*`/`antiforgery`/`account/*`, which allow none), `Frontend:SpaPath`/`Frontend:SpaBasePath` (`FrontendOptions`: static files under the base path before routing, `MapFallbackToFile(…/{*path:nonfile})` last so nothing is shadowed; root, a fixed list and the first segment of every mapped route refused at startup), `Frontend:SpaLinks` / `!Mvc` with `SpaPath` / `Frontend:SpaUrl` for an application hosted elsewhere (absolute links; `EmailLinksWouldBeDead` stops startup when mail is configured and nothing is linkable; `FrontendOptions.EmailLinkBase`: `SiteOptions.SpaLinkBase`, hidden, set by `AddBaGetAccounts`, makes `AccountLinks`/`AccountSupport.AbsoluteLink` build `{SpaBasePath}/confirm-email|reset-password|sign-in` links and the cookie login path), `Frontend:Mvc=false` (the host does not call `AddBaGetFrontEnd` and `RemoveBaGetFrontEnd` strips the screens' application parts, which the Razor SDK registers on its own for assemblies the host references). A new screen = a use case + DTOs in the Application project, a twin, a view controller that invokes and renders. **Every twin is in the OpenAPI `ui` document** (`ApiControllerBase` carries `[ApiExplorerSettings(IgnoreApi = false)]`, since twins are not `[ApiController]`; `OpenApiDocumentTests` checks each route and method, plain and `r/{repo}`). OpenAPI/Scalar: `docs/scalar.md`. + +**MVC application parts are registered by BaGet, not the host.** `AddBaGetApplicationParts` +(`src/BaGet.Web.V3/Extensions/IServiceCollectionExtensions.cs`) adds every API assembly with controllers; `AddBaGetFrontEnd()` (`BaGet.Web.FrontEnd`, namespace `BaGet`, called by the host after `AddBaGetWebApplication`) adds the front ends (`BaGet.Frontend.Base` for the layout, `BaGet.Identity.FrontEnd`, `BaGet.Web.FrontEnd`), Razor Pages, `RepositoryUrlHelperFactory` and `UiActionMap`; a host without the Web SDK has no generated `[ApplicationPart]` attributes. A new such assembly must be added to one of them. A host that does not call `AddBaGetFrontEnd()` serves the APIs only. The UI static files are `src/BaGet/wwwroot`, served by the host also at `/_content/BaGet.Web` (`UseBaGetPipeline`), the URL the layout links. + +Routes are named constants in `src/BaGet.Web.V3/Routing/Routes.cs`, mapped in `BaGetEndpointBuilder.MapEndpoints` (via `MapRoute`, see *Repository routes*), +and absolute URLs are built only via `IUrlGenerator` — add a member there rather than assembling URLs +in a page or controller. + +### Second databases: `IDatabaseContextFactory` + +Each relational provider registers an `IDatabaseContextFactory` (`BaGet.Core`; `Add{Sqlite,SqlServer,PostgreSql,MySql}Database`, +none for AzureTable) that opens an `IContext` on an *arbitrary* connection string, configured through the same +`Configure` method as the application's own context (`Database:MySqlServerVersion` honoured, else `AutoDetect` +against the target). Resolve `IEnumerable` and match `DatabaseType`; `Create(..., configure)` +takes an `Action` hook. The caller owns and disposes the context. + +`IContext.BeginKeyedInsertAsync` / `EndKeyedInsertAsync(IEntityType)` bracket inserts with explicit generated keys: +SQL Server runs `SET IDENTITY_INSERT` and keeps the connection open between the calls (the setting is per session); +PostgreSQL `setval`s the serial/identity sequence past the max key in `End`; SQLite and MySQL need nothing (explicit +keys advance their counters). + +### Database copy (`DatabaseCopyService`, `BaGet.Core/Entities/Copy`) + +The Settings page's "Copy all data" option queues a `DatabaseCopyRequest` (`TryQueue` closes the gate and refuses a +second copy); `DatabaseCopyWorker` (single-slot channel) runs it; progress is in memory (`Status`), polled via +`?handler=CopyStatus` (admin only). `DatabaseTable.InDependencyOrder` topologically sorts `Model.GetEntityTypes()` by +foreign keys (Identity's tables included), so a new table is covered with no list to keep. Rows are read in batches of +1000 ordered by primary key; they are loaded **tracked** only to capture **shadow properties** (the FK of a package's +types/frameworks/dependencies is shadow) into `CopyRow.Shadow`, then the tracker is cleared. Pre-flight +(`DatabaseCopyPreflight`, given the target's **design-time** model for column types/collations) runs before the target is created or +migrated and reports, only where the target engine enforces it: over-length strings (SQL Server/PostgreSQL/MySQL), case-only +duplicates in unique indexes and keys (columns `NOCASE`/`citext`/`*_ci`, else the engine default: SQL Server, MySQL) and local dates +(PostgreSQL); a non-empty target needing migration is refused with "schema was updated"; `Unspecified` dates are stored as UTC. Verification uses an order-independent key checksum (`DatabaseTable.Checksum`; engines collate differently). Once settings saving starts, a failure keeps the target and closes the gate until restart (`FailAfterSaveAsync`). A cancellation inside `SettingsService.SaveAsync` happens before the file rename, so it rolls back. Test seams +`DatabaseCopyService.AfterBatch` / `BeforeSettingsSaved` / `AfterSettingsSaved` inject failures. Errors are scrubbed of the connection string +(`DatabaseCopyService.Scrub`); never log it. + +### Logging + +The host (and only the host) uses Serilog: `AddBaGetLogging` (`HostLoggingExtensions`) clears the Microsoft providers and calls +`AddSerilog(... ReadFrom.Configuration ... , writeToProviders: true)`, so the `Serilog` section of `appsettings.json` +is the one source of truth for levels and sinks (`SerilogOptions` lists `MinimumLevel:Default` and `EventLog:*` on the Settings page; `MinimumLevel:Override` levels have their own *Log levels per source* panel there (`SettingsService.GetLogLevelOverrides`/`SetLogLevelOverrideAsync`, rules in `LogLevelOverrides`: remove only what the overrides file holds); sinks stay file/env only) (Console, File `logs/baget-.log`, resolved against the content +root / `BAGET_CONFIG_ROOT` for every File sink by `ResolveLogFilePaths`). `ApplyDefaultMinimumLevels` sets a code floor +before `ReadFrom` (Microsoft and `Hosting.Diagnostics` Warning: that logger prints `?apikey=`), so a host with its own +appsettings is safe. A sink with `Enabled=false` is blanked (`DisableSinks`; an empty env var is deleted on Windows). +On Windows a Serilog EventLog sink (Warning+, source `.NET Runtime`, `Serilog:EventLog:Enabled`) replaces the Microsoft +provider that `ClearProviders` removes. SelfLog goes to stderr. MinimumLevel reloads live, sinks need a restart. Libraries keep `Microsoft.Extensions.Logging.ILogger`. There is +**no static/bootstrap logger** (it would throw "already frozen" when `WebApplicationFactory` builds a second host). +`app.UseSerilogRequestLogging()` sits after forwarded headers/path base; its template has the path only, never the +query or headers (API keys); a credential inside a path (npm logout's `-/user/token/{token}`) is masked by `RequestPathRedaction` in the log (`GetMessageTemplateProperties`) and, through `RequestPathRedactingEnricher` (after `FromLogContext`, every string property of every event: the hosting scope's raw `RequestPath` rides on each event logged in a request; `LogScopeRedactionTests`), and in traces (`PathRedactingProcessor`, `url.path`/`url.full`). `writeToProviders` delivers each event twice to a registered `ILoggerProvider`; +tests that count lines use `Distinct()`. The harness switches the sinks off with `Enabled=false`. +`WebApplicationFactory` `UseSetting` gives every parent key of a setting an empty value, which Serilog reads as a sink +name, so a test that needs a working File sink runs `Program.BuildApplication` with command-line args instead. + +### Telemetry + +Libraries emit through `BaGetDiagnostics` (`BaGet.Core/Telemetry`): `Source` (`ActivitySource`) and `Meter`, both named +`BaGet`, plain `System.Diagnostics` (no OpenTelemetry package outside the host). `StartActivity` returns null without a +listener, so spans cost nothing. Spans: `package.index` (`PackageIndexingService`), `package.validate` +(`PackageValidationRunner`), `mirror.fetch` (`PackageService`, `RemoteNpmRegistry`), `database.copy` + `database.copy.table` +(`DatabaseCopyService`); counters `baget.packages.pushed`, `baget.downloads`, `baget.validation.results`. Tags are +`BaGetDiagnostics.Tags` (id, version, result, table, counts); never keys, connection strings or user data, and a failure +records the exception type only (`Fail`). `TelemetryOptions` (`Telemetry:*`, live except `ServiceName` and `Metrics:ExportInterval`, which are `[RestartRequired]`) validates itself +(`Validate()`, called from `ConfigureBaGetOptions`). Tests listen with `DiagnosticsCapture` (linked into `BaGet.Tests`); +the sources are process-wide, so tests that count measurements join its `Diagnostics` collection (runs alone). + +**Export (host only, `src/BaGet/Telemetry`).** `AddBaGetTelemetry` (called from `BuildApplication` next to `AddBaGetLogging`) +always builds the providers; whether anything is exported is decided live from `IOptionsMonitor` +(`AddBaGetOptions` has no change token, so it registers a `ConfigurationChangeTokenSource` for `Telemetry`): +`DynamicSampler` drops everything unless `Enabled` and a traces endpoint are set, then `ParentBased(TraceIdRatio)`; +`ReloadableTraceExporter` / `ReloadableMetricExporter` (`ReloadableExporter`) and `ReloadableOpenTelemetrySink` hold the +real OTLP exporter in a `SwappableHolder` (lease counted: a swap never waits for or cuts an export, the old exporter is +disposed once after its last lease, `ForceFlush` / `Shutdown` reach the current one) and rebuild only when +`TelemetryEndpoints.Key` changes (endpoint, protocol, headers, timeout, level), since every configuration reload fires +`OnChange`. Off = no inner exporter, no connection. Logs are a Serilog sink (added in `AddBaGetLogging`), **not** an +`ILoggerProvider` (`writeToProviders` would export each event twice); it carries `TraceId`/`SpanId`, applies +`Logs:MinimumLevel`, ignores `Grpc.Net.Client` / `System.Net.Http` events (feedback loop) and sees only what the Serilog +levels let through. Traces use `Otlp:Endpoint`; metrics and logs only their own endpoint (Jaeger takes traces only); with +`HttpProtobuf` `/v1/` is appended. Queue bounded (2048, `TelemetryServiceCollectionExtensions.MaxTraceQueueSize`). +`TelemetryStatus` (per signal: last attempt/success, failing since, scrubbed error) is fed by the exporters +(`ExportStatusHandler` for logs); every message goes through `TelemetryStatus.Scrub` (URLs cut to host, header values +replaced). `TelemetryConnectionTester` exports one synthetic span with explicit settings. The Settings page (BaGet.Identity cannot reference the host) reaches both through `ITelemetryDiagnostics` (`BaGet.Core`, implemented by the host's `TelemetryDiagnostics`; null args = saved values): the Telemetry section's status table, and `SettingsModel.OnPostTestTelemetryAsync` (admin, antiforgery, password-confirmed, posted unsaved `v:Telemetry:Otlp:*` fields, blank sensitive Headers = saved, nothing saved; `TelemetrySettingsPageTests`). **Privacy:** the ASP.NET Core +instrumentation redacts `url.query` values and records no headers, `SqlTextRedactingProcessor` strips the SQL text the EF instrumentation always records (`db.query.text`/`db.statement`/`db.query.summary`, renaming a span named from them; `SqlTextRedactingProcessorTests`, `TelemetryExportTests.DatabaseSpansNeverCarrySqlText`); the log sink uses the startup `ServiceName` (not part of the rebuild key), `ReloadableOpenTelemetrySink.Dispose` waits for sinks still leased by an `Emit`; a host without `ITelemetryDiagnostics` (embedded) gets a "no effect here" note on the Settings Telemetry section; logs are exported as written, audit lines with user names included (documented); never add an `Enrich` copying +either (`TelemetryExportTests.NeitherQueryValuesNorHeadersReach...`). **SDK quirks:** `BaseExporter.ParentProvider` (the +resource) has an internal setter, so `ReloadableExporter.Adopt` sets it by reflection on the inner exporter, and the batch +processor's `DroppedCount` is read by reflection; both degrade (empty resource, 0) if the SDK changes. Versions are levers in +`src/Directory.Build.props` (`OpenTelemetryPackageVersion` 1.20.0 needs Options/Configuration 10.0.0, which restores cleanly +beside the EF 10 / Extensions 10.0.13 pins; 1.13.x would avoid that but has known +vulnerabilities; `OpenTelemetry.Instrumentation.EntityFrameworkCore` exists only as prerelease, `1.20.0-beta.1`, and is +behind the live `Traces:Database`). Tests: `InMemoryTelemetry` (replaces `ITelemetryExporterFactory` through the harness's +`configureServices`; telemetry is off in the harness unless a test enables it, saving through `SettingsService` so the +reload path is the Settings page's), `FakeOtlpCollector` (real exporters over HTTP, no Docker), `ReloadableExporterTests`. + +### Tests + +`BaGetApplication : WebApplicationFactory` is the integration harness: real HTTP against the +real pipeline, SQLite in a temp directory, `SystemTime` mocked to 2020-01-01Z. Prefer it over mocking +when the behaviour is observable over HTTP; several real defects here were only caught by a real +client (e.g. the V2 feed's XML declaration). + +**Protocol suites run twice.** `ApiIntegrationTests`, `NuGetClientIntegrationTests`, `NuGetV2ClientIntegrationTests`, +`BaGetClientIntegrationTests`, `V2FeedIntegrationTests` and `CatalogIntegrationTests` are abstract `…Base` classes taking a +repository name; the plain class runs them at `/`, `…SecondRepository` at `/r/second/` (relative URIs resolve against +the client's `BaseAddress`; expected absolute URLs go through `Expect`; every repository's service index has 17 entries). +A new protocol test class should follow the pattern. Helpers: +`CreateRepositoryAsync`, `CreateRepositoryScopeAsync`, `AddPackageAsync(..., repository)`. +`RepositoryLifecycleIsolationTests` pushes/unlists/relists/deprecates in one repository and asserts the other's whole read +surface is unchanged; `UpgradeFromPreRepositoryTests` (B7) starts the real app on a pre-repository SQLite database and +`packages/…` store and asserts everything is served unchanged at `/`, keys/owners still work and no file moves. +`AdminFormatsTests` replaces the real npm module with a fake one that has create fields (its `FakeNpmModule`) to drive the generic format pages end to end. npm: `NpmRegistryTests` (HTTP protocol; the test server decodes +`%2f`, so scoped names arrive as two segments), `NpmAccessTests` (ownership, scopes, window, private repositories, login), `NpmPagesTests` (pages, filter, header), helper `NpmTestPackages` (tarballs and publish bodies), +`CreateNpmRepositoryAsync`. `RepositoryPagesTests` / `RepositoryAccountPagesTests` cover the pages at `/r/second/` (links stay inside, switcher, upload target, My packages grouped, +admin Browse/Upload links, `IRepositoryAccess` refusal = 404); `MvcInfrastructureFacts` (`BaGet.Web.Tests`) `RepositoryUrlHelper`. + +**Access tests** (`BaGet.Tests`): `AccessUpgradeEquivalenceTests` (B3 merge gate: a pre-repository database migrated by the current code behaves as before), +`AccessEvaluatorTests` (decisions, administration, cache, audit, 50-target cost) with `GlobSetTests`, `PrivateRepositoryTests` (401/404/Basic on every protocol route, +page redirect, push permissions), `ManagePermissionTests`, `AccessInspectionTests` (explanations, repository summary, admin reads, rename, project delete, filtered audit, patterns), +`AccessAdminPagesTests` (the U3 pages end to end: roles, passwords, project administrators, audit entries, 503 while closed). A test that needs a private repository removes the seeded targets through `IAccessAdministration`. + +Unit tests reach internals through `InternalsVisibleTo`, declared in each **project file** (not +`AssemblyInfo.cs`): + +| Project | Visible to | +|---|---| +| `BaGet.Core` | `BaGet.Core.Tests`, `BaGet.Tests`, `BaGet.Database.Tests`, `BaGet.Catalog`, `BaGet.Api.Base`, `BaGet.Frontend.Base`, `BaGet.Identity.Api`, `BaGet.Identity.Application`, `BaGet.Web.Application` | +| `BaGet.Identity.Application` | `BaGet.Api.Base`, `BaGet.Frontend.Base`, `BaGet.Identity.Api`, `BaGet.Tests`, `BaGet.Web.Application` | +| `BaGet.Web.Application` | `BaGet.Web.V3`, `BaGet.Frontend.Base`, `BaGet.Web.FrontEnd`, `BaGet.Tests`, `BaGet.Web.Tests` | +| `BaGet.Api.Base` | `BaGet.Frontend.Base`, `BaGet.Identity.Api`, `BaGet.Web.V3`, `BaGet.Tests` | +| `BaGet.Frontend.Base` | `BaGet.Identity.FrontEnd`, `BaGet.Web.FrontEnd`, `BaGet.Tests`, `BaGet.Web.Tests` | +| `BaGet.Identity.Api` | `BaGet.Identity.FrontEnd`, `BaGet.Frontend.Base`, `BaGet.Tests` | +| `BaGet.Web.V3` | `BaGet.Web.FrontEnd`, `BaGet.Tests`, `BaGet.Web.Tests` | +| `BaGet.Identity.FrontEnd` | `BaGet.Tests` | +| `BaGet.Web.FrontEnd` | `BaGet.Tests`, `BaGet.Web.Tests` | +| `BaGet`, `BaGet.Catalog`, `BaGet.Validation`, `BaGet.Database.*` | `BaGet.Tests` (`BaGet` also `BaGet.Telemetry.Tests`, `BaGet.Ha.Tests`) | +| `BaGet.Web` | `BaGet.Tests`, `BaGet.Web.Tests` | +| `BaGet.Azure` | `BaGet.Azure.Tests`, `BaGet.Storage.Tests` | +| `BaGet.Protocol` | `BaGet.Protocol.Tests` | +| `BaGet.Web.V2` | `BaGet.Web.V2.Tests` (no such project; `BaGet.Tests` has no access) | +| `BaGet.Aws`, `BaGet.Gcp`, `BaGet.Aliyun` | `BaGet.Storage.Tests` | + +## Code layout (BaGet.Api.Base, BaGet.Catalog, BaGet.Frontend.Base, BaGet.Identity.Api, BaGet.Identity.Application, BaGet.Identity.FrontEnd, BaGet.Validation, BaGet.Web.Application, BaGet.Web.FrontEnd, BaGet.Web.V3) + +One type per file named like it, no nested types, namespace = the project's `RootNamespace` + folder (folders name the functionality: `Models/`, `UseCases/`, `Services/`, `Routing`, `Filters`, `Middleware`...), and every controller in the folder of its kind: `Controllers/FrontEnd` screens (controllers returning a view), `Controllers/UI` `/api/ui` twins (`ApiController`, deriving the `ApiControllerBase` family), `Controllers/Base` bases, `Controllers/Api` `/api/v1` (deriving `AdminApiController`/`AccessApiController`; `CodeLayoutTests` tells the two apart by base type), `Controllers/Protocols` package protocols. `CodeLayoutTests` enforces it; the only namespace exceptions are `BaGetEndpointBuilder`, `IServiceCollectionExtensions` and `FrontEndServiceCollectionExtensions` (namespace `BaGet`, for discoverability). `Controllers/FrontEnd` exists only in the two FrontEnd projects. + +## Strong naming + +Every project of `BaGet.sln` (src, tests, samples) is signed with `SignKey.snk` at the repository root. The root +`Directory.Build.props` sets `SignAssembly`, `AssemblyOriginatorKeyFile` and `BaGetPublicKey` (the full public key); +`src/` and `tests/Directory.Build.props` import it (MSBuild reads only the nearest props file), samples read it directly. +Public key token `a5ab967c088e8330`. Every `` in a project file needs `Key="$(BaGetPublicKey)"` +(an unsigned friend name is CS1726). The key file is in the repository (so are git worktrees); a checkout without +`SignKey.snk` at its root cannot build. Moq on `internal` types would need `DynamicProxyGenAssembly2` with Castle's +well-known key; none is used today. The only unsigned dependency is Markdig (no CS8002 is raised; .NET loads it). + +## Packaging + +Every packable project's `README.md` is its package readme (`PackageReadmeFile`, set in `src/Directory.Build.props` +when the file exists). It renders on nuget.org, so links must be absolute. + +`Extension.BaGet` (the `BaGet` host) also packs `BaGet.Web/wwwroot` at `wwwroot/` (a `None` item in +`src/BaGet/BaGet.csproj`), for hosts that embed BaGet without the Web SDK's static web assets and serve those +files from `wwwroot/_content/BaGet.Web` (e.g. BaGet.Service). The layout links the files at `/_content/BaGet.Web/...`; the host serves its `wwwroot` there as well (`UseBaGetPipeline`). + +## Package versions + +All shared versions are single levers in `src/Directory.Build.props`; provider projects must read them +rather than pinning literals (divergence there once resolved an EF 8 request to EF 10). + +**Entity Framework is 10.0.13** (`MicrosoftEntityFrameworkCorePackageVersion`, Identity's stores, `Microsoft.Extensions.*`, +Npgsql 10.0.3). MySQL uses `Microting.EntityFrameworkCore.MySql` 10.0.13 (a maintained fork of Pomelo, which stalled at EF 9; same +API, namespaces `Microting.EntityFrameworkCore.MySql.*`, provider name `Microting.EntityFrameworkCore.MySql`); it constrains +`Microsoft.EntityFrameworkCore.Relational` to `[10.0.13, 10.0.999]`, so all four providers move together and EF must not be +raised past that range until Microting releases. `Microsoft.Extensions.*` tracks EF because holding it lower is an `NU1605` +downgrade error. `BaGet.Database.SqlServer` pins `System.Security.Cryptography.Pkcs` 10.0.13 (SqlClient's 9.0.11 is NU1902/NU1903). + +## Migrations + +Each `BaGet.Database.*` project has an `IDesignTimeDbContextFactory` using a hardcoded connection +string and `ServerVersion.Parse` (never `AutoDetect`, which opens a live connection). A schema change +needs a migration **per provider**, and all four must report no pending model changes. + +- Verify a provider without a server: `dotnet ef migrations list --context Context` in its folder. +- **`dotnet ef migrations remove --no-build` has deleted the wrong (previous) migration** on PostgreSQL + and MySQL because of a stale assembly; without `--no-build` it needs a live database. Delete the + generated files by hand and restore the snapshot from `HEAD` instead. +- A migration that adds a foreign key to existing data deletes/detaches the orphan rows first (`OwnershipOrphanCleanup`, see *Ownership foreign keys*); on SQLite put that SQL **before** the operations that rebuild the table. +- Model-level cascade-delete configuration caused `PendingModelChangesWarning` across every integration + test; orphan cleanup lives in `PackageDatabase.HardDeletePackageAsync` instead. + +Documentation is mkdocs (`mkdocs.yml`, `docs/`; `docs/plans/` excluded). `.github/workflows/docs.yml` builds it with `--strict` and deploys it to GitHub Pages (https://pieroviano.github.io/BaGet/) on every push to `main` (Pages source must be "GitHub Actions"). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f12e5d009..72162d982 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,14 +2,28 @@ Please read the [code of conduct] before contributing. -If you want to run from BaGet's source code: +If you want to run from BaGet Extension's source code: -1. Install the [.NET SDK] and [Node.js] -2. Run `git clone https://github.com/loic-sharma/BaGet.git` -3. Navigate to `./BaGet/src/BaGet` -4. Start the service with `dotnet run` -5. Open the URL `http://localhost:5000/v3/index.json` in your browser +1. Install the [.NET SDK] (BaGet Extension targets .NET 10) +2. Run `git clone https://github.com/pieroviano/BaGet.git` +3. Create the local package source with `mkdir BaGet/Packages` (nuget.config lists the untracked `Packages` folder as a package source; restore fails with NU1301 without it) +4. Navigate to `./BaGet/src/BaGet` +5. Start the service with `dotnet run -p:GeneratePackageOnBuild=false` +6. Open the URL `http://localhost:6060/v3/index.json` in your browser + +Every project is strong-name signed with `SignKey.snk` at the repository root (a checkout without it fails to build). + +Always pass `-p:GeneratePackageOnBuild=false` to `dotnet build`, `run` and `test`: `src/Directory.Build.props` +packs on build into the shared `Packages` folder. `dotnet run` may rewrite +`src/BaGet/Properties/launchSettings.json`; revert it rather than committing it. + +Run the tests with `dotnet test BaGet.sln -p:GeneratePackageOnBuild=false` from the repository root. They need no +external services: the integration tests use SQLite in a temporary directory. The harness is +`tests/BaGet.Tests/Support/BaGetApplication.cs`; it passes settings with `builder.UseSetting(...)`, not +`ConfigureAppConfiguration`, because accounts are decided while services are registered. + +A database change needs a migration for each of the four `src/BaGet.Database.*` providers; see the +readme in any of them. [Code of conduct]: CODE_OF_CONDUCT.md [.NET SDK]: https://www.microsoft.com/net/download -[Node.js]: https://nodejs.org/ \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..9cebd119f --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,15 @@ + + + + + true + $(MSBuildThisFileDirectory)SignKey.snk + + 0024000004800000940000000602000000240000525341310004000001000100518ef14d1a0c9efc88ac39397509c94a703ec7a674ed0414a18d3bad86b3618863d9d20204b50c28a13c56df0493d2943f2013a9b4f2bd5a829217698fa2444fbbebd449d6a8942a1278c87fe9ccba10535b9b2b1f47295168308a2b2a85af1fc655f8c736b51fe1d457d1b7be6c807516f58d5d981b112929c5c24f3ff1c0ce + + + diff --git a/Dockerfile b/Dockerfile index ee8ba3c5e..54e0dbd97 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,18 +1,25 @@ -FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base WORKDIR /app +# appsettings.json binds Kestrel to localhost:6060, which is unreachable from outside the +# container; listen on every interface on the exposed port instead. An env file can override it. +ENV Kestrel__Endpoints__Http__Url=http://+:80 EXPOSE 80 -FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build -WORKDIR /src -COPY /src . +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +# src/Directory.Build.props imports the repository-root Directory.Build.props, which signs every assembly with +# SignKey.snk: both must sit one folder above src/. Local data under src/ is kept out by .dockerignore. +WORKDIR /repo +COPY Directory.Build.props SignKey.snk ./ +COPY src ./src +WORKDIR /repo/src RUN dotnet restore BaGet -RUN dotnet build BaGet -c Release -o /app +RUN dotnet build BaGet -c Release --no-restore -p:GeneratePackageOnBuild=false FROM build AS publish -RUN dotnet publish BaGet -c Release -o /app +RUN dotnet publish BaGet -c Release --no-restore --no-build -o /app -p:GeneratePackageOnBuild=false FROM base AS final -LABEL org.opencontainers.image.source="https://github.com/loic-sharma/BaGet" +LABEL org.opencontainers.image.source="https://github.com/pieroviano/BaGet" WORKDIR /app COPY --from=publish /app . ENTRYPOINT ["dotnet", "BaGet.dll"] diff --git a/LICENSE b/LICENSE index 0f682f8de..ddf6ee918 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,5 @@ Copyright 2018 Loic Sharma +Copyright (c) 2026 Piero Viano Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/src/BaGet/wwwroot/.gitignore b/Packages/PlaceHolder.txt similarity index 100% rename from src/BaGet/wwwroot/.gitignore rename to Packages/PlaceHolder.txt diff --git a/SignKey.snk b/SignKey.snk new file mode 100644 index 000000000..b65d05939 Binary files /dev/null and b/SignKey.snk differ diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 000000000..3ae07c41b --- /dev/null +++ b/build.ps1 @@ -0,0 +1,286 @@ +param( + [switch]$Run, # Run the solution after building (starts BaGet Extension) + [switch]$Publish # Clean, restore, build (Release), and publish the solution +) + +# Script configuration - script is in root, solution is in root +# Usage: +# .\build.ps1 - Clean, restore, and build (Debug) +# .\build.ps1 -Run - Clean, restore, build (Debug), and run BaGet Extension +# .\build.ps1 -Publish - Clean, restore, build (Release), and publish to Publish folder +$SolutionPath = Join-Path $PSScriptRoot "BaGet.sln" +$ProjectPath = Join-Path $PSScriptRoot "src\BaGet\BaGet.csproj" +$PublishPath = Join-Path $PSScriptRoot "Publish" + +# Determine build configuration +$Configuration = if ($Publish) { "Release" } else { "Debug" } + +Write-Host "========================================" -ForegroundColor Cyan +Write-Host "BaGet Build Script" -ForegroundColor Cyan +Write-Host "========================================" -ForegroundColor Cyan +Write-Host "" + +# Function to check if a process is running +function Test-ProcessRunning { + param([string]$ProcessName) + $processes = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue + return $null -ne $processes -and $processes.Count -gt 0 +} + +# Function to close processes +function Stop-ProjectProcesses { + Write-Host "Checking for running processes..." -ForegroundColor Yellow + + $processesToCheck = @( + "dotnet" + ) + + $foundProcesses = $false + + foreach ($processName in $processesToCheck) { + if (Test-ProcessRunning $processName) { + $foundProcesses = $true + try { + Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue + Start-Sleep -Seconds 2 + } + catch { + Write-Host " Warning: Could not close all $processName processes: $_" -ForegroundColor Red + } + } + } + + # Check for processes using files in the solution directory + Write-Host "Checking for processes locking solution files..." -ForegroundColor Yellow + try { + $solutionDir = Split-Path $SolutionPath -Parent + $lockedFiles = Get-ChildItem -Path $solutionDir -Recurse -File -ErrorAction SilentlyContinue | + Where-Object { + try { + [System.IO.File]::OpenWrite($_.FullName).Close() + $false + } + catch { + $true + } + } + + if ($lockedFiles) { + Write-Host " Warning: Some files may be locked by other processes." -ForegroundColor Yellow + } + } + catch { + # Ignore errors in file locking check + } + + if (-not $foundProcesses) { + Write-Host "No running processes found." -ForegroundColor Green + } + + Write-Host "" +} + +# Step 1: Close running processes +Stop-ProjectProcesses + +# Step 2: Clean the solution +Write-Host "Cleaning solution..." -ForegroundColor Cyan +try { + # Suppress verbose output from dotnet clean + $originalTerminalLogger = $env:MSBUILDTERMINALLOGGER + $env:MSBUILDTERMINALLOGGER = "off" + + $processInfo = New-Object System.Diagnostics.ProcessStartInfo + $processInfo.FileName = "dotnet" + $processInfo.Arguments = "clean `"$SolutionPath`" --verbosity quiet /nologo /noconsolelogger" + $processInfo.UseShellExecute = $false + $processInfo.RedirectStandardOutput = $true + $processInfo.RedirectStandardError = $true + $processInfo.CreateNoWindow = $true + $processInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden + + $process = New-Object System.Diagnostics.Process + $process.StartInfo = $processInfo + $null = $process.Start() + + # Read and discard all output + $null = $process.StandardOutput.ReadToEnd() + $null = $process.StandardError.ReadToEnd() + $null = $process.WaitForExit() + + # Restore environment + if ($originalTerminalLogger) { + $env:MSBUILDTERMINALLOGGER = $originalTerminalLogger + } else { + Remove-Item Env:\MSBUILDTERMINALLOGGER -ErrorAction SilentlyContinue + } + + if ($process.ExitCode -eq 0) { + Write-Host " Solution cleaned successfully." -ForegroundColor Green + } + else { + Write-Host " Warning: Clean completed with exit code $($process.ExitCode)" -ForegroundColor Yellow + } +} +catch { + Write-Host " Error cleaning solution: $_" -ForegroundColor Red +} +Write-Host "" + +# Step 3: Remove bin and obj directories +Write-Host "Removing bin and obj directories..." -ForegroundColor Cyan +$solutionDir = Split-Path $SolutionPath -Parent +$removedCount = 0 + +try { + # Remove bin directories + $binDirs = Get-ChildItem -Path $solutionDir -Directory -Recurse -Filter "bin" -ErrorAction SilentlyContinue + foreach ($dir in $binDirs) { + try { + Remove-Item -Path $dir.FullName -Recurse -Force -ErrorAction Stop + $removedCount++ + } + catch { + Write-Host " Warning: Could not remove $($dir.FullName): $_" -ForegroundColor Yellow + } + } + + # Remove obj directories + $objDirs = Get-ChildItem -Path $solutionDir -Directory -Recurse -Filter "obj" -ErrorAction SilentlyContinue + foreach ($dir in $objDirs) { + try { + Remove-Item -Path $dir.FullName -Recurse -Force -ErrorAction Stop + $removedCount++ + } + catch { + Write-Host " Warning: Could not remove $($dir.FullName): $_" -ForegroundColor Yellow + } + } + + if (Test-Path "$($solutionDir)\packages") { + Remove-Item -Path "$($solutionDir)\packages" -Recurse -Force -ErrorAction Stop + $removedCount++ + } + + if (Test-Path $PublishPath) { + Remove-Item -Path $PublishPath -Recurse -Force -ErrorAction Stop + $removedCount++ + } + + if ($removedCount -gt 0) { + Write-Host " Removed $removedCount directories." -ForegroundColor Green + } + else { + Write-Host " No bin/obj directories found to remove." -ForegroundColor Green + } +} +catch { + Write-Host " Error removing directories: $_" -ForegroundColor Red +} +Write-Host "" + +# Step 4: Restore NuGet packages +Write-Host "Restoring NuGet packages..." -ForegroundColor Cyan +try { + $restoreResult = & dotnet restore $SolutionPath --verbosity quiet + if ($LASTEXITCODE -eq 0) { + Write-Host " NuGet packages restored successfully." -ForegroundColor Green + } + else { + Write-Host " Error: NuGet restore failed with exit code $LASTEXITCODE" -ForegroundColor Red + exit $LASTEXITCODE + } +} +catch { + Write-Host " Error restoring packages: $_" -ForegroundColor Red + exit 1 +} +Write-Host "" + +# Step 5: Build the solution +Write-Host "Building solution..." -ForegroundColor Cyan +try { + $buildResult = & dotnet build $SolutionPath --configuration $Configuration --no-restore --verbosity quiet + if ($LASTEXITCODE -eq 0) { + Write-Host " Solution built successfully!" -ForegroundColor Green + } + else { + Write-Host " Error: Build failed with exit code $LASTEXITCODE" -ForegroundColor Red + exit $LASTEXITCODE + } +} +catch { + Write-Host " Error building solution: $_" -ForegroundColor Red + exit 1 +} +Write-Host "" + +# Step 6: Publish the solution (if requested) +if ($Publish) { + Write-Host "Publishing solution..." -ForegroundColor Cyan + + # Remove existing publish directory if it exists + if (Test-Path $PublishPath) { + Write-Host " Removing existing publish directory..." -ForegroundColor Yellow + try { + Remove-Item -Path $PublishPath -Recurse -Force -ErrorAction Stop + Write-Host " Existing publish directory removed." -ForegroundColor Green + } + catch { + Write-Host " Warning: Could not remove existing publish directory: $_" -ForegroundColor Yellow + } + } + + try { + Write-Host " Publishing to: $PublishPath" -ForegroundColor Yellow + + # Ensure the publish directory exists + $null = New-Item -ItemType Directory -Path $PublishPath -Force -ErrorAction SilentlyContinue + + # Publish using dotnet publish + Write-Host " Publishing BaGet project..." -ForegroundColor Yellow + $publishResult = & dotnet publish $ProjectPath --configuration $Configuration --output $PublishPath --no-build + if ($LASTEXITCODE -eq 0) { + Write-Host " Solution published successfully!" -ForegroundColor Green + Write-Host " Published files are located at: $PublishPath" -ForegroundColor Green + } + else { + Write-Host " Error: Publish failed with exit code $LASTEXITCODE" -ForegroundColor Red + exit $LASTEXITCODE + } + } + catch { + Write-Host " Error publishing solution: $_" -ForegroundColor Red + Write-Host " Stack trace: $($_.ScriptStackTrace)" -ForegroundColor Red + exit 1 + } + Write-Host "" +} + +# Run the solution (if requested) +if ($Run) { + Write-Host "Running solution..." -ForegroundColor Cyan + + Write-Host " Starting BaGet Extension..." -ForegroundColor Yellow + Write-Host " Navigate to http://localhost:6060/v3/index.json in your browser" -ForegroundColor Cyan + Write-Host " Press Ctrl+C to stop the BaGet Extension" -ForegroundColor Gray + Write-Host "" + + try { + $projectDir = Split-Path $ProjectPath -Parent + Set-Location -Path $projectDir + & dotnet run --urls "http://localhost:6060" --verbosity quiet + } + catch { + Write-Host " Error running solution: $_" -ForegroundColor Red + exit 1 + } + finally { + Set-Location -Path $PSScriptRoot + } +} + +Write-Host "" +Write-Host "========================================" -ForegroundColor Cyan +Write-Host "Build script completed!" -ForegroundColor Cyan +Write-Host "========================================" -ForegroundColor Cyan diff --git a/docs/BaGetSite.png b/docs/BaGetSite.png new file mode 100644 index 000000000..caa0c601d Binary files /dev/null and b/docs/BaGetSite.png differ diff --git a/docs/access-control.md b/docs/access-control.md new file mode 100644 index 000000000..0a11f8172 --- /dev/null +++ b/docs/access-control.md @@ -0,0 +1,156 @@ +# Access control + +Who may **read** a repository and who may **change** packages in it. Two layers, both required for a write: + +| Layer | Decides | Where | +|---|---|---| +| Access model | Which repositories and package IDs a caller may read, deploy to, delete from, annotate, manage | this page | +| Package ownership | Which existing package IDs a user may change | [Accounts](configuration.md#accounts-package-owners-and-api-keys) | + +Needs a relational database (SQLite, SQL Server, PostgreSQL, MySQL). With Azure Table there is no access model: everyone +reads, any authenticated caller writes subject to ownership, as before. + +## Model + +| Entity | Meaning | +|---|---| +| Group | A named set of users. Built-in: **Everyone** (every caller, anonymous included) and **Authenticated** (every caller with valid credentials); their membership is implicit | +| Permission target | Repository patterns (names or `*` globs), package-ID include patterns (default `*`) and exclude patterns, optionally owned by a project | +| Grant | A user, group or organization and the actions it holds through a target | +| Project | Groups repositories (`Repository.ProjectKey`); members hold a role: *Viewer* = Read; *Developer* = Read, Annotate, Deploy; *Admin* = all | +| Audit entry | One row per change to any of the above, and per *Anonymous read* switch | + +| Action | Allows | +|---|---| +| `Read` | Feed, symbols, catalog, registrations, package pages of the repository; npm: packuments, tarballs, search, the browse and package pages | +| `Annotate` | Deprecation and vulnerabilities; npm: `npm deprecate` | +| `Deploy` | Push new packages and versions. Never held on a [remote repository](remote-repositories.md) (not by administrators either): it only holds what the server cached. Never held on a [virtual repository](virtual-repositories.md#writes) either: a push to it is judged on its deploy repository | +| `Delete` | Unlist, relist, delete; Docker: delete tags, manifests and blobs (pull = Read, push = Deploy; the image name is the package id of the patterns, see [Docker registry](docker-registry.md#access)); npm: unpublish (a version younger than `Npm:UnpublishWindow` needs only `Deploy`, see [npm registry](npm-registry.md#unpublish-policy)) | +| `Manage` | The package's Manage page: owners and abuse reports need it; opening the page takes any of Manage, Delete or Annotate. Unlist, relist and delete need `Delete`, deprecation and vulnerabilities `Annotate` (what the protocol asks). An owner needs the action as well as ownership; administrators hold them everywhere | + +Actions are independent: `Deploy` does not imply `Read`. A caller holds an action when **any** applicable grant carries it. +Server administrators and the global API key hold every action everywhere. Include/exclude patterns narrow package-level +checks only: a repository-level question (service index, search) is allowed when some package could match. + +## Upgrade defaults + +The migration seeds what the server did before the model, so nothing changes until an administrator edits it: + +| Target | Repositories | Principal | Actions | +|---|---|---|---| +| Anyone reads every repository | `*` | Everyone | Read | +| Authenticated users deploy | `*` | Authenticated | Annotate, Deploy, Delete, Manage | + +Ownership still applies inside Deploy, Delete, Annotate and Manage. Both targets can be deleted and restored +(`IAccessAdministration.RestoreBuiltInsAsync`). + +## Anonymous read + +`Repository.AnonymousRead` (the *Anonymous read* switch of `/admin/repositories/{name}`) gates the **Everyone** group's +`Read` on that repository: + +| Switch | Effect | +|---|---| +| on (default) | Everyone's Read grants apply. If no target grants Everyone Read on the repository any more, switching on creates the target `Anonymous read {name}` | +| off | Everyone's Read does not apply there, whether it comes from a permission target or from a project role held by Everyone (its other actions still do); callers need a Read grant of their own (user, group, organization or project role) | + +## What a client sees + +| Caller | Private repository | +|---|---| +| Anonymous | `401` with `WWW-Authenticate: Basic realm="BaGet"` on every protocol route (`/` and `/r/{repo}/`) whatever the HTTP method; the routes listed below skip the check and authenticate with an API key | +| Signed in, no Read | `404`, as for an unknown repository or package | +| With Read | served | + +Pages follow the same check, and a page of one package (`/packages/{id}/...`: details, report abuse, manage, contact owners) is also checked against the caller's include/exclude patterns, so a hidden package answers `404` there as on its registration: an anonymous visitor is sent to sign in, a signed-in user without Read gets `404`, and the +repository switcher and search lists only show readable repositories. Search results are filtered per repository, not +per package: a Read grant narrowed by include/exclude patterns protects the per-package routes (registration, content), +but `search`, `autocomplete` and the V2 listings of a repository the caller may read show all its packages. + +Routes that skip the Read check (they authenticate with an API key and are authorized per repository and package by Deploy, Delete or Annotate, so a Deploy-only *drop box* works): + +| Route | Skips | +|---|---| +| Push (`PUT`/`POST` `api/v2/package`), symbol upload, delete, relist, deprecation and vulnerability `PUT`/`DELETE` | write methods only; a `GET`, `HEAD` or `OPTIONS` to them is still checked | +| Validation status (`GET v3/package/{id}/{version}/validation`) | always: the pusher sees what became of its push without Read; the controller itself needs an API key with Push or Manage on that package in that repository (`401` without a key, `403` otherwise) | + +The browser upload page follows the same rule: it needs **Deploy** on the repository (not Read) for a signed-in user, so a Deploy-only user can upload, one with Read only gets `404`, and the repository picker lists the same set. Its "View it" link appears only when the user may read the package. + +## Upgrading + +`Repository.AnonymousRead` could be saved as off before access control existed, when it did nothing; now it makes the repository private. The saved setting is kept. At every startup (migrations enabled) a Warning names each non-default repository with the switch off and no Read grant for anyone but administrators (target grants and project roles counted; the seeded targets give Everyone Read, which the switch gates), so the change is visible. Switch *Anonymous read* on, or grant Read, to silence it. + +## Client setup + +The password is an **API key** (an account's key, or the global `ApiKey`); the user name is the key's owner (any name for +the global key). + +| Client | Setup | Checked | +|---|---|---| +| `dotnet` (restore, search, push) | `dotnet nuget add source https://host/r/second/v3/index.json -n second -u alice -p --store-password-in-clear-text` (add `--allow-insecure-connections` for `http`). Without credentials: `NU1301` 401. Push keeps using `--api-key` | yes, .NET SDK 10.0.402 against a running host | +| `nuget.exe` | `nuget sources add -Name second -Source -Username alice -Password -StorePasswordInClearText`. Without credentials it asks its credential providers, then fails with 401 | yes, 6.2.1 (`install`; its `list` has no V3 support) | +| `NuGet.Config` | `` | yes (what the two above write) | +| Visual Studio | *Tools > Options > NuGet Package Manager > Package Sources*: user name and password on the source; it also prompts on the 401 challenge | no (same NuGet client code as `dotnet`) | +| PowerShellGet (V2 feed `/r/second/api/v2`) | `Register-PSRepository ... -SourceLocation `, then `-Credential` on `Find-Module` / `Install-Module` | no: needs the NuGet provider bootstrap (internet). The V2 routes answer 401 / Basic exactly like V3 (`PrivateRepositoryTests`, real host: 401 anonymous, 200 with Basic) | +| Symbols (Visual Studio) | Same credentials on the symbol server entry (`/api/download/symbols`) | route challenged (401 + Basic) anonymous, served with Basic; the debugger itself not run | + +A wrong password, or the right key with another user name, is `401` again. + +## Request credentials + +Reads accept, in order: `Authorization: Basic` (password = API key), `X-NuGet-ApiKey`, then the browser session. +Credentials that do not authenticate count as none: an open repository stays readable, a private one answers `401`. +Writes are unchanged: `X-NuGet-ApiKey`, authorized per package (`401` no key, `403` not permitted). + +## Repository-scoped API keys + +A key can be limited to some repositories (`ApiKeyRepository`, picked on `/account/apikeys` among the repositories the +user can read; hidden where only `default` exists). Existing and new keys with nothing ticked work in every repository. +Effective rights = the key's scopes and package pattern, intersected with its repositories and with what its user may +do there (this model, then ownership). + +| Request with a limited key | Outcome | +|---|---| +| Write (push, unlist, delete, deprecate) in a repository outside the limit | `403`, also for an administrator's key | +| Read of a repository outside the limit | judged as an anonymous caller: an open repository is served, a private one answers `404` | +| Anything inside the limit | the user's own permissions decide | + +Deleting a repository removes it from the keys limited to it and deletes keys that were limited to it alone (they would +otherwise become unlimited). The user list in `/admin/users/{name}` shows each key's repositories. + +## Cost and cache + +The model is held in memory as a snapshot, rebuilt after any committed change to it (`AccessModelSaveChangesInterceptor` +bumps `AccessModelVersion`) and at most every 30 s (other instances catch up within that time). A check against +50 targets and 20 groups costs a few microseconds (`AccessEvaluatorTests`); a user's group and organization membership +is loaded on first use and kept with the snapshot. + +## Admin pages + +Menu entries *Groups*, *Permission targets*, *Projects*, *Access audit* (administrators) and *My access* (every signed-in +user). Everything answers `404` to anyone else, and, with Azure Table (no access model), sends administrators to +`/admin/access-unavailable`, which says so. Every change is audited, takes effect on the next request, asks for **your +password again** unless it only creates an empty group, target or project (or renames a group), and is refused with `503` while the +server is read-only for maintenance. + +| Page | Does | +|---|---| +| `/admin/groups`, `/admin/groups/{name}` | create, rename, delete (not the built-ins); add members through a user-name search, remove them; lists the grants naming the group | +| `/admin/permissions`, `/admin/permissions/{name}` | create targets and edit their repository / include / exclude patterns; **Preview** shows the repositories the patterns match and a **test box** answers "does `Contoso.Lib` match?" (and which pattern decided), on unsaved edits too; grants per user, group or organization with one box per action; delete; restore the built-in targets | +| `/admin/projects`, `/admin/projects/{name}` | create; assign repositories (a repository is in one project); members with a role (user or group); the project's own targets; delete (keeps the repositories) | +| `/admin/users/{name}` | the user's groups (add/remove), project roles and **effective permissions per repository**, each with the targets and roles that grant them; a package ID box applies include/exclude patterns | +| `/admin/repositories/{name}` | adds who effectively holds Read, Annotate, Deploy, Delete and Manage, the project and the anonymous-read switch | +| `/admin/audit` | the audit log, newest first (200 at most), filtered by actor, subject and UTC dates (`yyyy-MM-dd`, inclusive); also lists the [retention](retention.md) policy, hold and run entries (`retention.*`) | +| `/account/access` | your own effective permissions in each repository where you hold something (nothing is shown about repositories you cannot use), with the reasons; a package ID box | + +**Project administrators** (role *Admin*) are admitted to their own project's page and to its targets, with the limits +below; they see nothing of other projects, groups or the global targets. + +| Who | May | +|---|---| +| Server administrator | everything above | +| Project administrator | set and remove the project's members, create the project's targets, edit their patterns and grants, delete them | +| Project administrator may **not** | assign repositories to the project (it would let them take any repository), delete the project, or touch targets of other projects or global ones | + +A project target applies only to the project's repositories whatever its patterns say, so a project administrator cannot +reach beyond them; the previews show only those repositories. diff --git a/docs/admin-api.md b/docs/admin-api.md new file mode 100644 index 000000000..1aa6bde54 --- /dev/null +++ b/docs/admin-api.md @@ -0,0 +1,86 @@ +# Administration REST API + +`/api/v1` does what the administrator pages do, for scripts. One operation, one page: every endpoint is listed in +[UI coverage](ui-coverage.md) with its page, and the pages and the API call the same services, so rules cannot differ. +The OpenAPI 3 document is `GET /api/v1/openapi.json` (also `/openapi/v1.json`); the signed-in list is the **REST API** page (`/admin/api`). See [OpenAPI and Scalar](#openapi-and-scalar). + +## Authentication + +| Credential | Accepted when | +|---|---| +| API key as `Authorization: Bearer `, as the Basic password, or `X-NuGet-ApiKey` | owner is an **administrator** (checked on every call), key has scope **`admin:api`**, key is not limited to repositories | +| The global `ApiKey` | one is configured (an open server with no key never admits anyone) | + +- Create the key on **API keys** (the scope is offered to administrators only; demoting the owner disables the key at once). +- The browser session is **never** accepted, so a web page cannot drive the API through a signed-in browser. +- No credentials: `401` + `WWW-Authenticate: Bearer`. Valid but not allowed: `403`. +- `admin:api` is not in the scopes sessions and npm tokens receive. + +## Confirmation + +Where the page asks for the password again (**Confirmation: password** in the table), send the key owner's password in +`X-Confirm-Password`. Missing or wrong: `403` `confirmation-required` (a wrong one counts as a failed sign-in and can lock the +account out). An owner with no password: `403` `confirmation-unavailable`. The global key is its own confirmation. + +| Page asks | API asks | +|---|---| +| remote repository create / save / test / purge, anonymous read of a remote repository | yes | +| access changes: grants, patterns, memberships, deletes; user create/promote/demote/group/key revoke | yes | +| retention policy create / save / run / delete, lift a hold; replication create / save / test / run / resume / delete; scanning policy; operation that deletes (`RequiresConfirmation`) | yes | +| create empty group / target / project, rename group, virtual members, repository delete, dry run, place a hold, start a scan, stop a replication | no (as the pages) | + +## Conventions + +| | | +|---|---| +| Errors | `application/problem+json`: `status`, `title`, `detail`, stable `code` (`not-found`, `invalid-request`, `conflict`, `confirmation-required`, `confirmation-unavailable`, `locked-out`, `read-only`, `not-supported`, `unauthorized`, `forbidden`) | +| Status | `400` invalid input, `404` unknown, `409` state forbids it (repository not empty, last administrator, already running), `422` not supported here (no access model on Azure Table), `503` + `Retry-After` while the server is read-only (writes only) | +| Lists | `?page=1&pageSize=50` (max 200) answer `{items, page, pageSize, total}` | +| Names | repositories, groups, users… by name in the path; principals by name in bodies | +| Enums | by name (`"Remote"`, `"Read"`) | +| Created | `201` + `Location`; started jobs `202` (poll the status endpoint) | + +## Resources + +| Path | What | +|---|---| +| `/repositories`, `/formats` | list, create (local/remote/virtual, any format), anonymous read, delete; `/{name}/remote` (upstream, `test`, `cache`, `purge`, `purge-package`), `/{name}/virtual` (members, `preview`), `/{name}/access` | +| `/projects`, `/groups`, `/permission-targets`, `/audit` | the access model; `/permission-targets/preview` | +| `/users` | list, create, administrator flag, groups, keys, effective access | +| `/operations` | list, start, status (catalog rebuild, downloads import, Docker GC, vulnerability scan…) | +| `/retention` | `policies` (CRUD, `dry-run`, `run`), `holds` | +| `/replication` | `configs` (list, show, create, replace, delete, `run`, `resume`, `stop`, `runs`), `test`, `runs/{key}`, `inventory/{repository}` (what a peer calls; its key needs `admin:api`) | +| `/scanning` | overview, per-repository dashboard / results / policy / scan, per-project policy | + +## OpenAPI and Scalar + +Built with `Microsoft.AspNetCore.OpenApi`, written as OpenAPI 3.0, browsed with [Scalar](https://scalar.com) at **`/scalar`** (how to test with it: [Testing the APIs with Scalar](scalar.md)). + +| Document | Address | Holds | +|---|---|---| +| `v1` | `/openapi/v1.json`, alias `/api/v1/openapi.json` | this API (`/api/v1`) | +| `ui` | `/openapi/ui.json` | the JSON twins of every screen (`/api/ui`, see [UI API](ui-api.md)) | +| `protocols` | `/openapi/protocols.json` | NuGet, symbol, npm, Maven and Docker routes, plain and `/r/{repo}/`, read from the mapped endpoints (paths, methods, route parameters, format; bodies are the protocols' own) | + +**Password confirmation (screens and `/api/ui`):** a locked-out account never confirms, and a wrong password counts as a failed sign-in (so repeated guesses lock the account, as with `X-Confirm-Password`). A project administrator's `/admin/projects/{name}` screen carries no `assignable` repositories (only server administrators assign; project administrators use the web screens, `/api/ui` takes administrators' keys and interactive sessions, [UI API](ui-api.md)). + +**Who:** administrators only. A signed-in server administrator (cookie), an administrator's `admin:api` key (not limited to repositories) or the global `ApiKey` (when one is configured) get `200`; everyone else, anonymous included, gets `404`. Scalar's own files are gated the same way. The documents never contain keys or secrets. + +## Not offered over the API + +| Left on the pages | Why | +|---|---| +| password reset, invitation mails, account deletion, account approval (`Accounts:RequireApproval`; user objects carry `pendingApproval`, and promoting a user approves it), organizations, validation queue, abuse reports, server settings | mail or destroy on someone's behalf, or carry secrets; use the pages | +| scanning one version | on the package page (needs Manage on the package, not a server administrator) | +| a project administrator's delegated pages | the API admits server administrators only | + +## Example + +```sh +curl -H "Authorization: Bearer $KEY" https://baget.example/api/v1/repositories?kind=Remote +curl -X POST -H "Authorization: Bearer $KEY" -H "X-Confirm-Password: $PASSWORD" -H "Content-Type: application/json" \ + -d '{"name":"npmjs","format":"Npm","kind":"Remote","remote":{"url":"https://registry.npmjs.org/"}}' \ + https://baget.example/api/v1/repositories +``` + +Routes are mapped by `BaGetEndpointBuilder.MapAdminApiRoutes`; a host that maps its own endpoints must call it. diff --git a/docs/advanced/api.md b/docs/advanced/api.md new file mode 100644 index 000000000..ad073e23c --- /dev/null +++ b/docs/advanced/api.md @@ -0,0 +1,161 @@ +# Server API + +BaGet Extension implements the [NuGet V3 API](https://learn.microsoft.com/nuget/api/overview); clients find +every resource through the service index at `/v3/index.json`. This page lists what it serves, and +the endpoints BaGet Extension adds of its own. Every NuGet route below also exists under `/r/{name}/` for a named [repository](../repositories.md) (`/r/{name}/v3/index.json`); a repository of another format answers `404` on a route of a different format. + +## Service index resources + +| Resource | URL | Notes | +| --- | --- | --- | +| `PackagePublish/2.0.0` | `/api/v2/package` | `PUT` push; `DELETE /{id}/{version}` unlists or hard deletes per [`PackageDeletionBehavior`](../configuration.md#enable-package-hard-deletions); `POST /{id}/{version}` relists | +| `SymbolPackagePublish/4.9.0` | `/api/v2/symbol` | portable PDBs that match the package's assemblies | +| `SearchQueryService` | `/v3/search` (also advertised as `/3.0.0-beta`, `/3.0.0-rc`) | results include `deprecation`, `vulnerabilities`, `owners`, `verified` | +| `SearchAutocompleteService` | `/v3/autocomplete` | also advertised as `/3.0.0-beta`, `/3.0.0-rc`; `take` is clamped to 0..1000 and `skip` to 0 or more on search and autocomplete | +| `RegistrationsBaseUrl` | `/v3/registration` | entries include `deprecation` and `vulnerabilities`; also advertised as `/3.0.0-beta`, `/3.0.0-rc` | +| `PackageBaseAddress/3.0.0` | `/v3/package` | | +| `PackageDetailsUriTemplate/5.1.0` | `/packages/{id}/{version}` | | +| `ReportAbuseUriTemplate/3.0.0-beta`, `-rc` | `/packages/{id}/{version}/report-abuse` | | +| `VulnerabilityInfo/6.7.0` | `/v3/vulnerabilities/index.json` | one page, `/v3/vulnerabilities/base.json`; entries set by hand plus what [scanning](../vulnerability-scanning.md) found about the package version itself | +| `Catalog/3.0.0` | `/v3/catalog/index.json` | not with Azure Table Storage (the `Catalog` resource is not advertised and its routes answer `404`) | +| `RepositorySignatures/5.0.0` | `/v3/repository-signatures/index.json` | only while [repository signing](../configuration.md#repository-signing) is configured | + +The V2 (OData) feed is at `/api/v2`; see [NuGet V2 feed](../configuration.md#nuget-v2-feed). + +## Authentication + +Send the key in the `X-NuGet-ApiKey` header: the global `ApiKey`, or with accounts a per-user key. + +| Request | Needs | +| --- | --- | +| `PUT /api/v2/package`, `PUT /api/v2/symbol` | a key allowed to push the package id | +| `DELETE`/`POST /api/v2/package/{id}/{version}`, deprecation and vulnerability writes | a key with the `package:unlist` scope that may manage the package | +| `GET /v3/package/{id}/{version}/validation` | a key that may push or manage the package | +| every other `GET` in this page | `Read` on the repository ([access control](../access-control.md)); none while the repository is open to everyone, which is the default | + +Reads of a repository that is not open to everyone take `Authorization: Basic` (user name = the key's owner, password = the +API key) or the same `X-NuGet-ApiKey` header: `401` + `WWW-Authenticate: Basic realm="BaGet"` for an anonymous caller, +`404` for an authenticated one without `Read` (nothing says the repository or package exists). + +Writes: `401` without a valid key, `403` for a key that may not act on the package (no `Deploy`/`Delete`/`Annotate` +permission in that repository for the package id, or not its owner). With `IsReadOnlyMode` on, push, +delete, relist and the metadata writes answer `401`. While the [maintenance gate](../configuration.md#read-only-maintenance-gate) is closed (a database copy), +any database write answers `503` with `Retry-After`. + +## Other routes + +| Route | Notes | +| --- | --- | +| `GET /v3/registration/{id}/index.json`, `/v3/registration/{id}/{version}.json` | registration index and leaf | +| `GET /v3/package/{id}/index.json`, `/v3/package/{id}/{version}/{id}.{version}.nupkg`, `.../{id}.nuspec` | versions, package, manifest | +| `GET /v3/package/{id}/{version}/readme`, `.../icon` | the package's readme and icon | +| `GET /v3/dependents` | packages that depend on a package; BaGet Extension's own, not in the NuGet protocol | +| `GET /api/download/symbols/{file}/{key}/{file2}`, `/api/download/symbols/{prefix}/{file}/{key}/{file2}` | symbol download (the symbol server URL) | +| `GET /v3/vulnerabilities/index.json`, `/v3/vulnerabilities/base.json` | vulnerability index and its only page | +| `GET /v3/catalog/index.json`, `/v3/catalog/page{n}.json`, `/v3/catalog/data/{commitId}.json` | catalog index, page, leaf | +| `GET /v3/repository-signatures/{fingerprint}.crt` | the repository signing certificate | +| `GET /api/v2`, `/api/v2/$metadata`, `/api/v2/Packages()`, `/api/v2/Packages(Id='..',Version='..')`, `/api/v2/FindPackagesById()`, `/api/v2/Search()` | V2 feed; `404` when `Feeds:EnableV2` is `false`, while push, delete and relist under `/api/v2/package` and `/api/v2/symbol` are unaffected | + +## Other formats + +| Format | Routes (under `/r/{name}/` unless noted) | Docs | +| --- | --- | --- | +| npm | `npm/{package}` (packument `GET`, publish `PUT`, `…/-rev/{rev}`), `npm/{package}/-/{file}` (tarball), `npm/-/package/{package}/dist-tags[/{tag}]`, `npm/-/v1/search`, `npm/-/ping`, `npm/-/whoami`, `npm/-/v1/login`, `npm/-/user/{userKey}` (`PUT` login), `npm/-/user/token/{token}` (`DELETE` logout), `npm/-/npm/v1/security/advisories/bulk`, `npm/-/npm/v1/security/audits/quick`; a scoped name is `@scope%2fname` or `@{scope}/{pkg}` | [npm registry](../npm-registry.md) | +| Maven | `maven/{**path}`: `GET`/`HEAD` read, `PUT` deploy, `DELETE` | [Maven repositories](../maven-repositories.md) | +| Docker (OCI Distribution Spec 1.1) | at the **server root**: `/v2/`, `/v2/token`, `/v2/{repo}/{image…}/blobs/…`, `manifests/…`, `tags/list`, `referrers/…`; `{repo}` is the BaGet repository | [Docker registry](../docker-registry.md) | + +## Health + +`GET /health/live` answers `200` while the process runs; `GET /health/ready` answers `200` or `503` with the name of each check (database, storage; the shared store is reported only). Both are anonymous, see [High availability](../high-availability.md). + +## Administration + +Repositories, the access model, users, operations, retention, scanning and replication are administered under `/api/v1` with an administrator's +`admin:api` key; see [Administration REST API](../admin-api.md) and its OpenAPI document `GET /api/v1/openapi.json`. + +## Deprecation and vulnerabilities + +These change a package version, so they are authorised like a delete: the global `ApiKey`, or with +[accounts](../configuration.md#accounts-package-owners-and-api-keys) an owner's key with the +`package:unlist` scope, sent in the `X-NuGet-ApiKey` header. + +| Request | Body | +| --- | --- | +| `PUT /v3/package/{id}/{version}/deprecation` | `{"reasons": ["Legacy"], "message": "...", "alternatePackageId": "...", "alternateVersionRange": "[2.0.0, )"}` | +| `DELETE /v3/package/{id}/{version}/deprecation` | | +| `PUT /v3/package/{id}/{version}/vulnerabilities` | `[{"advisoryUrl": "https://...", "severity": 2, "versionRange": "[1.0.0, 1.2.0)"}]`; `[]` clears them | + +* `reasons`: one or more of `Legacy`, `CriticalBugs`, `Other`. +* `severity`: `0` low, `1` moderate, `2` high, `3` critical. +* `alternateVersionRange` is kept only with `alternatePackageId`. +* An omitted `versionRange` means the version itself. + +| Response | Meaning | +| --- | --- | +| `204` | changed | +| `400` | invalid body; the response says why | +| `401` / `403` | not authenticated (or read-only mode) / not allowed for this package | +| `404` | no such package version | +| `501` | the database cannot store this metadata (Azure Table Storage) | + +Owners can do the same from the package's manage page. + +## Validation status + +With the [validation pipeline](../configuration.md#validate-packages-before-serving-them) on: + +`GET /v3/package/{id}/{version}/validation`, with an owner's key or the global `ApiKey` (`401`, `403`, and `404` when the version has no validation record): + +```json +{ + "submissionId": "...", + "status": "Quarantined", + "steps": [ + { "type": "PackageEntries", "state": "Succeeded", "message": null }, + { "type": "PackageSignature", "state": "Failed", "message": "The package must be signed." }, + { "type": "Index", "state": "Failed", "message": "Quarantined: the package failed validation." } + ] +} +``` + +`status` is `Validating`, `Available` or `Quarantined`. + +## Web pages + +Pages marked "accounts" answer `404` while `Accounts:Enabled` is `false`; "sign-in" pages redirect to `/account/login` when anonymous. + +| Page | | +| --- | --- | +| `/`, `/packages` | search (same page) | +| `/packages/{id}`, `/packages/{id}/{version}` | package details | +| `/upload` | browser upload (stage, then confirm or cancel, with a metadata preview) and push instructions; needs an API key, or a sign-in with accounts | +| `/stats` | totals, most downloaded packages, latest versions | +| `/terms`, `/privacy` | the operator's Markdown files from `Site:TermsOfUsePath` / `Site:PrivacyPolicyPath`; linked from the footer only when set | +| `/packages/{id}/{version}/report-abuse` | records a report for the package's owners | +| `/account/login`, `/account/logout`, `/account/register` (needs `Accounts:AllowRegistration`), `/account/loginwith2fa`, `/account/loginwithrecoverycode` | accounts | +| `/account/forgotpassword`, `/account/resetpassword`, `/account/confirmemail` | accounts; `404` unless email (SMTP) is configured | +| `/account/apikeys`, `/account/organizations`, `/account/packages`, `/account/settings`, `/account/twofactor`, `/account/reauthenticate` | accounts, sign-in | +| `/account/profile` | accounts, sign-in; redirects to `/profiles/{name}` | +| `/profiles/{name}` | a user's or organization's packages; accounts | +| `/packages/{id}/manage` | accounts, sign-in; owners: owners, unlist/relist, delete (per `PackageDeletionBehavior`), deprecation, vulnerabilities, symbols (list/delete), abuse reports; administrators: verified flag | +| `/scan-artifact?name=&version=` (also `/r/{repo}/scan-artifact`) | accounts, sign-in; may manage the package: *Scan now* of one version, see [vulnerability scanning](../vulnerability-scanning.md) | +| `/admin/scanning`, `/admin/scanning/{repository}`, `/admin/scanning/projects/{name}` | administrators: scanning overview, a repository's dashboard and policy, a project's policy | +| `/packages/{id}/validation` | accounts, sign-in, validation; push or manage: the validation status of the ID's submissions | +| `/packages/{id}/contact-owners` | accounts, sign-in; `404` unless email is configured | +| `/admin/users` | administrators: promote, demote, reset password, send reset link | +| `/admin/users/{name}/packages`, `/admin/users/{name}/delete` | administrators | +| `/admin/packages` | administrators: packages without owners | +| `/admin/repositories`, `/admin/repositories/{name}`, `/admin/repositories/{name}/delete` | administrators: list, create, edit and delete repositories, see [Repositories](../repositories.md) | +| `/admin/groups`, `/admin/groups/{name}`, `/admin/permissions`, `/admin/permissions/{name}`, `/admin/projects`, `/admin/projects/{name}`, `/admin/audit`, `/admin/access-unavailable` | administrators (projects and their targets also their project administrators): groups, permission targets, projects, access audit, see [Access control](../access-control.md#admin-pages) | +| `/account/access` | accounts, sign-in: your effective permissions per repository | +| `/npm-packages`, `/npm-upload`, `/maven-artifacts`, `/maven-upload`, `/docker-images` (and the package, artifact and image detail pages) | the browse and upload pages of the npm, Maven and Docker repositories, also at `/r/{name}/…`; a page of another format answers `404` | +| `/admin/formats`, `/admin/operations`, `/admin/validation`, `/admin/abuse`, `/admin/cluster` | administrators: format modules, background operations, validation and abuse queues, cluster nodes and health | +| `/admin/retention`, `/admin/retention/{key}`, `/admin/retention/holds` | administrators: retention policies, dry run, legal holds | +| `/admin/replication`, `/admin/replication/{key}` | administrators: replication configurations and the run log | +| `/admin/api` | administrators: the catalog of the [administration REST API](../admin-api.md) | + +[UI coverage](../ui-coverage.md) maps every capability to its page. +| `/admin/settings` | administrators: edit settings (saved to `appsettings.Overrides.json`), see the [Settings page](../configuration.md#settings-page) and [moving to another database](../configuration.md#moving-to-another-database); `404` if the overrides store is unavailable | +| `/admin/settings?handler=CopyStatus` | administrators: JSON progress of the database copy (`phase`, `active`, `finished`, `succeeded`, `restartRequired`, table and row counters, `message`, `errors`) | + +Admin pages answer `404` to everyone else, so their existence is not disclosed. Paths are lowercase. diff --git a/docs/advanced/architecture.md b/docs/advanced/architecture.md new file mode 100644 index 000000000..0c482b41b --- /dev/null +++ b/docs/advanced/architecture.md @@ -0,0 +1,255 @@ +# Architecture + +BaGet Extension is one ASP.NET Core (`net10.0`) host serving the NuGet V3 protocol, an optional V2 feed, a +symbol server, npm, Maven and Docker (OCI) registries, an administration REST API and an MVC (controllers and views) UI. +Storage, database and search are pluggable and chosen from configuration at runtime. + +## Projects + +| Project | Role | +|---|---| +| `BaGet` | Host and CLI entry point: `Program.cs` (configuration, services, pipeline, commands) | +| `BaGet.Core` | Domain: entities, `IContext`, `IPackageDatabase`, storage, search, indexing, remote/virtual repositories, format modules (`Formats`: NuGet, npm, Maven, Docker), access model, retention, scanning, replication, operations, high availability (`Ha`), telemetry, options, settings, maintenance gate, database copy | +| `BaGet.Web.V3` | V3, npm, Maven and OCI controllers (`Controllers/Protocols`), the `/api/v1` administration API (`Controllers/Api`), the `/api/ui` JSON twins of the screens (`Controllers/UI`), `BaGetEndpointBuilder`, `Routes`, `IUrlGenerator` (`Routing`); no view | +| `BaGet.Web.FrontEnd`, `BaGet.Identity.FrontEnd` | The web screens: view controllers (`Controllers/FrontEnd`) and views; `AddBaGetFrontEnd()` | +| `BaGet.Api.Base`, `BaGet.Frontend.Base` | Shared base of the APIs and screens (twin bases, `[UiApi]`, `[RepositoryPage]`); MVC base of the screens (view controller bases, layout, link helpers) | +| `BaGet.Web.V2` | Legacy V2 OData/Atom feed (`Feeds:EnableV2`) | +| `BaGet.Identity` | Accounts, API keys, ownership, administrators, access-model, retention, replication, scanning and other admin pages (`Accounts:Enabled`) | +| `BaGet.Catalog` | V3 catalog resource, writer and rebuild | +| `BaGet.Validation` | Validation queue and worker, validators, repository signing (`Validation:Enabled`) | +| `BaGet.Database.{Sqlite,SqlServer,PostgreSql,MySql}` | One EF Core `IContext` and migrations per provider | +| `BaGet.Azure`, `BaGet.Aws`, `BaGet.Gcp`, `BaGet.Aliyun` | Cloud storage (Azure Blob, S3, Google Cloud, Aliyun OSS), Azure Table database and Azure Search | +| `BaGet.Protocol` | Standalone NuGet V3 **client** library (shipped as a package; used for mirroring) | + +Dependencies point inwards: every project references `BaGet.Core`; only the host references everything. The host also holds the telemetry export (`src/BaGet/Telemetry`) and the Redis cluster store (`src/BaGet/Ha`). + +`BaGet.Identity` cannot reference `BaGet.Validation` or `BaGet.Catalog`; it reaches them through `BaGet.Core` interfaces. + +## Startup — `src/BaGet/Program.cs` + +`Program` holds `Main` and `BuildApplication`; each step is an extension method in `src/BaGet/Hosting/`. + +| Step | What happens | +|---|---| +| `Main` | McMaster `CommandLineApplication`: `import downloads [-r repo]`, `catalog rebuild [-r repo]`, `account reset-password/promote/demote/approve` (`AddBaGetCommands`); the default command runs migrations (while `RunMigrationsAtStartup` is on), promotes initial administrators and runs the host. Unknown arguments pass through to the host. | +| `AddBaGetSettingsOverrides` | `BAGET_CONFIG_ROOT` base path; inserts `appsettings.Overrides.json` (written by the Settings page) after `appsettings*.json`, before environment variables and the command line. | +| `AddBaGetHost` | Options binding and validation (`AddBaGetOptions`), web app, accounts, provider registration (`app.AddXyz()` per subsystem). | +| `AddBaGetFrontEnd` | Adds the screens to a host: `Frontend.Base`, `Identity.FrontEnd` and `Web.FrontEnd` as MVC application parts, Razor Pages, `RepositoryUrlHelperFactory`. A host that serves only the APIs omits it | +| `AddBaGetWebApplication` | Registers the web APIs, without the screens (`/packages` is also routed to the home action; every repository page also at `/r/{repo}/…`, see below; Razor Pages, for a host's own pages, are registered by `AddBaGetFrontEnd` and mapped only when registered; BaGet ships none), the catalog and validation services and `StagingSweepWorker`; `AddBaGetApplicationParts` adds every BaGet assembly with controllers or pages (`Web.V3`, `Web.V2`, `Catalog`, `Validation`, `Identity.Api`; the screens' assemblies are added by `AddBaGetFrontEnd`) as an MVC application part, so a host built without the Web SDK (e.g. a worker service calling `BaGet.Program.Main`) still serves them. A new such assembly must be added there. | +| `UseBaGetPipeline` | Middleware (below), then `BaGetEndpointBuilder.MapEndpoints`. | + +Some configuration is read **while registering services** (e.g. `Accounts:Enabled`, `Email`, provider types), +so those settings need a restart; options read through `IOptionsSnapshot` apply live. + +## Request pipeline + +``` +HostFiltering → (Dev: exception page, status code pages) → ForwardedHeaders → PathBase +→ StaticFiles → Routing → RepositoryResolution → CORS → Authentication → Authorization → OperationCancelled → Maintenance → endpoints +``` + +- `AllowedHosts` drives host filtering: a request with any other `Host` header gets 400. +- Endpoints are named constants in `Routes.cs`, mapped in `BaGetEndpointBuilder.MapEndpoints`; absolute URLs come only from `IUrlGenerator`. +- Every protocol route exists at `/` (the `default` repository) and under `/r/{repo}/`; `RepositoryResolutionMiddleware` + selects the repository from the route (`404` if unknown) and `IUrlGenerator` keeps advertised URLs inside it. +- The repository pages (controller actions marked `[RepositoryPage]`) get an `r/{repo}/` twin of each route (`RepositoryActionRouteConvention`); + `RepositoryUrlHelper` adds the request's `repo` to links to those actions (ASP.NET Core would drop it between different actions) (a screen is + its controller and default GET action, `ScreenRef`). `IRepositoryAccess` decides which repositories the switcher, the + upload picker and `RepositoryActionFilter` offer. +- `MaintenanceMiddleware` turns a `MaintenanceException` into `503` + `Retry-After`. + +## Runtime provider selection + +Each subsystem is an `IProvider` chain. `GetServiceFromProviders` asks every registered provider +and takes the first non-null answer; each provider decides from configuration. + +| Subsystem | Key | Implementations | +|---|---|---| +| Database (`IContext`) | `Database:Type` | Sqlite, SqlServer, PostgreSql, MySql, AzureTable | +| Storage (`IStorageService`) | `Storage:Type` | FileSystem, AzureBlobStorage, AwsS3, GoogleCloud, AliyunOss, Null | +| Search (`ISearchService`, `ISearchIndexer`) | `Search:Type` | Database, AzureSearch, Null | + +New implementation: register a provider in `DependencyInjectionExtensions.Providers.cs` and an `app.AddXyz()` +in `HostServiceCollectionExtensions.AddBaGetProviders` (`src/BaGet/Hosting`). + +## Endpoints + +| Area | Paths | +|---|---| +| Service index | `v3/index.json` | +| npm registry | `r/{repo}/npm/…` (packuments, tarballs, dist-tags, search, login, audit) | +| Maven | `r/{repo}/maven/{**path}` (`GET`/`HEAD`/`PUT`/`DELETE`) | +| Docker (OCI) | `v2/`, `v2/token`, `v2/{repo}/{image…}/blobs\|manifests\|tags\|referrers/…` at the server root | +| Administration API | `api/v1/…`, `api/v1/openapi.json` ([Administration REST API](../admin-api.md)) | +| Health | `health/live`, `health/ready` | +| Publish | `api/v2/package` (PUT push, DELETE delete/unlist, POST relist), `api/v2/symbol` | +| Content | `v3/package/{id}/index.json`, `…/{version}/{id}.{version}.nupkg`, `….nuspec`, `…/readme`, `…/icon` | +| Metadata | `v3/registration/{id}/index.json`, `v3/registration/{id}/{version}.json` | +| Search | `v3/search`, `v3/autocomplete`, `v3/dependents` | +| Deprecation, vulnerabilities | `v3/package/{id}/{version}/deprecation`, `…/vulnerabilities`, `v3/vulnerabilities/*` | +| Catalog | `v3/catalog/index.json`, `v3/catalog/page{n}.json`, `v3/catalog/data/{commitId}.json` | +| Validation, signing | `v3/package/{id}/{version}/validation`, `v3/repository-signatures/*` | +| Symbols | `api/download/symbols/…` | +| V2 feed | `api/v2`, `api/v2/$metadata`, `Packages()`, `FindPackagesById()`, `Search()` | +| UI | `/`, `/packages`, `/packages/{id}/{version}`, `/upload`, `/stats`, `/account/*`, `/admin/*`, `/profiles/*` (full list in the [Server API](api.md)) | + +## Push + +``` +PUT api/v2/package + → IAuthenticationService.AuthenticatePrincipalAsync(api key) → BaGetPrincipal + → IPackageAuthorizationService.AuthorizeAsync(principal, Push, id) + → IPackageSubmissionService.SubmitAsync + validation off → IPackageIndexingService.IndexAsync + validation on → stage + ValidationQueue → ValidationWorker → validators → IndexAsync (or reject) +``` + +`PackageIndexingService.IndexAsync`: + +1. Read the `.nupkg`; reject unsafe entries; extract nuspec, readme and icon. +2. Existing version → `PackageAlreadyExists`, or replace it when `AllowPackageOverwrites` is on. +3. Save files: `packages/{id}/{version}/{id}.{version}.nupkg`, `{id}.nuspec`, `readme`, `icon` (lowercased). Repositories other than `default` store under `repos/{name}/` (e.g. `repos/{name}/packages/…`; symbols, catalog, validation and staging likewise). +4. Add the database row (`IPackageDatabase.AddAsync`). +5. `ISearchIndexer.IndexAsync`. +6. `PackageChangeNotifier` → every `IPackageChangeHandler` (e.g. `CatalogWriter`). Runs after the commit; a + handler's failure is logged, never fails the push. + +Browser uploads (`/upload`) use the same submission, with an extra staging step (`IPackageStagingService`) +between "stage" and "confirm"; `StagingSweepWorker` removes abandoned uploads. + +## Download and mirroring + +`PackageContentController` → `IPackageContentService` → `IPackageService` → `IPackageStorageService`. +`PackageService` indexes a missing version from the repository's upstream (`IUpstreamClient`, V3 +through `BaGet.Protocol` or V2) before serving it; mirrored packages go straight to +`IPackageIndexingService`, never through validation. The `IUpstreamClient` of a request is a `RemoteUpstreamClient`: +`IRemoteUpstreamSource` resolves the upstream of the current repository (a remote repository's own settings; for +`default`, the `mirror` remote repository while `Mirror:Enabled`; none for local repositories), then the client applies +offline mode, the metadata and negative cache periods and stale-on-error, and records the upstream's health +(`RemoteRepositoryState`, in memory). A remote repository that does not store locally is a pass-through +(`IPassThroughUpstreamClient`, `IPackageService.OpenUncachedAsync`). See [Remote repositories](../remote-repositories.md). + +Deletion follows `PackageDeletionBehavior`: `Unlist` (hide) or `HardDelete` (rows and files). +Administrators can always hard-delete from the UI. + +## Formats, remote and virtual repositories + +| Piece | Job | +|---|---| +| `IFormatModule` / `FormatRegistry` (`BaGet.Core/Formats`) | Describes a format (`NuGet`, `Npm`, `Maven`, `Docker`): route prefix, creatable kinds, storage folders, create fields, usage and purge. Per-request work is in scoped `IFormatService`s; see [Formats](../formats.md) | +| `INpmRegistry`, `IMavenRepository`, `IOciRegistry` | Forward per call by `IRepositoryContext.Current.Kind` to the local, remote or virtual implementation | +| Remote (`RepositoryKind.Remote`) | Upstream in `Repository.Settings`; `RemoteUpstreamClient`, `RemoteRepositoryState`; see [Remote repositories](../remote-repositories.md) | +| Virtual (`RepositoryKind.Virtual`) | Ordered members, one deploy repository; see [Virtual repositories](../virtual-repositories.md) | + +## Access model + +`BaGet.Core/Access`: groups, permission targets (repository and package globs), project roles and an audit log; `IAccessEvaluator` decides +(`Read`, `Annotate`, `Deploy`, `Delete`, `Manage`), `RepositoryReadFilter` / `RepositoryActionFilter` enforce Read. See [Access control](../access-control.md). + +## Retention, scanning, replication, high availability + +| Subsystem | Code | Docs | +|---|---|---| +| Retention | `BaGet.Core/Retention` (`RetentionEvaluator`, `RetentionEngine`, `RetentionWorker`) | [Retention](../retention.md) | +| Vulnerability scanning | `BaGet.Core/Scanning` (`IScanService`, `IScanGate`, OSV and Trivy, `ScanWorker`) | [Vulnerability scanning](../vulnerability-scanning.md) | +| Replication | `BaGet.Core/Replication` (`ReplicationEngine`, `IFormatReplicator`, `ReplicationWorker`) | [Replication](../replication.md) | +| High availability | `BaGet.Core/Ha` (`IClusterStore`, `ClusterJobLease`, `ClusterSyncService`), Redis in `src/BaGet/Ha` | [High availability](../high-availability.md) | + +## Authentication and authorization + +| Piece | Behaviour | +|---|---| +| `BaGetPrincipal` | Who a key or session is: superuser flag, administrator flag, scopes, package glob | +| Accounts off | `ApiKeyAuthenticationService`: the global `ApiKey` (or none) is the superuser | +| Accounts on | `AccountAuthenticationService`: global key = superuser, else a hashed per-user key; `SessionPrincipalFactory` for browser sessions | +| `OwnershipAuthorizationService` | Ownership rules (new ID claimed by pusher, owned IDs need an owner, ownerless pre-account IDs only superuser/admin); administrators skip ownership but keep their key's scopes and glob | + +Identity uses EF stores on whichever `IContext` the database provider resolved; the security stamp is checked +on every request. + +## Data + +`AbstractContext : IdentityDbContext, IContext` holds the model: packages, dependencies, +target frameworks, package types, deprecations, vulnerabilities, validations, catalog entries, abuse reports, +users, organizations, owners, API keys, repositories and projects. Each provider subclasses it and owns its +migrations; a schema change needs a migration in all four relational providers. + +### Repositories + +Every package, owner, catalog entry, validation, abuse report and symbol record (`PackageSymbol`: which package version a PDB came from) belongs to a `Repository` (`RepositoryKey`; +`IRepositoryScoped`). `default` (key 1) is the one served at `/` and holds everything that predates repositories: +the `AddRepositories` migration gives existing rows `RepositoryKey = 1`, and startup creates the `default` row +(`IRepositoryService.EnsureDefaultAsync`). Package IDs are unique per repository: `(RepositoryKey, Id, Version)`. + +| Piece | Job | +|---|---| +| `IRepositoryContext` (scoped) | The repository in effect: `Current { Key, Name, Format, Kind }`, `Use(info)` to select. Defaults to `default`. Routing, workers and commands call `Use` (or `IServiceScopeFactory.CreateRepositoryScope(info)`) before any query | +| `AbstractContext` query filters | Filter the six tables above on `Current.Key` per query, and stamp new rows with it on save. `IgnoreQueryFilters()` sees every repository (database copy, account deletion, the validation worker's pending list) | +| `IRepositoryService` | Find / list / create repositories; name rules in one place, `RepositoryNames` (lowercase `[a-z0-9-._]`, 1-64, not a reserved route name) | +| Azure Table | Holds the `default` repository only: creating another is refused, `TablePackageDatabase` refuses any other | + +Other repositories are local, [remote](../remote-repositories.md) (`Repository.Settings` holds the upstream; the password is protected by data protection) or [virtual](../virtual-repositories.md) (`Repository.Settings` holds the member names and the deploy repository; reads run in each member's own scope through `VirtualRepositoryReader`, writes are redirected to the deploy repository). Package and symbol storage paths nest +under `repos/{name}/` for other repositories. + +## Background work + +| Hosted service | Project | Job | +|---|---|---| +| `ValidationWorker` | `BaGet.Validation` | Runs queued validations, then indexes or rejects | +| `StagingSweepWorker` | `BaGet.Web.V3` | Deletes expired browser-upload staging | +| `RetentionWorker` | `BaGet.Core` | Starts due retention schedules, flushes download usage | +| `ScanWorker` | `BaGet.Core` | Scans queued artifacts and sweeps repositories (`Scanning:*`) | +| `ReplicationWorker` | `BaGet.Core` | Starts due and deploy-triggered replications | +| `ClusterSyncService` | `BaGet.Core` | Heartbeat and shared gate / access model / copy status (`Ha:Enabled`) | +| `DatabaseCopyWorker` | `BaGet.Core` | Runs the queued database copy | +| `BackgroundEmailService` | `BaGet.Identity` | Sends queued email (confirmation, reset, contact owners) | + +## Second databases: `IDatabaseContextFactory` + +Each relational provider (`Add{Sqlite,SqlServer,PostgreSql,MySql}Database`; none for AzureTable) registers an +`IDatabaseContextFactory` that opens an `IContext` on an arbitrary connection string, configured like the +application's own context. Resolve `IEnumerable` and match `DatabaseType`; the caller +disposes the context. `IContext.BeginKeyedInsertAsync` / `EndKeyedInsertAsync` bracket inserts with explicit keys +(SQL Server `IDENTITY_INSERT`; PostgreSQL `setval` afterwards; nothing for SQLite and MySQL). + +## Read-only gate + +`MaintenanceGate` (`BaGet.Core`, singleton, in memory) closes every database write. +`MaintenanceSaveChangesInterceptor` throws `MaintenanceException` from `SaveChanges` while it is closed; the +middleware answers `503`; the layout shows a banner. `CloseUntilRestart` cannot be reopened. A context built with +`MaintenanceGate.AllowWrites` (the copy's target) is exempt. Code that catches broad `Exception` around a write +must not swallow `MaintenanceException`. Raw SQL would bypass the gate, so there is none outside migrations. + +## Database copy + +The Settings page's "Copy all data" option queues a `DatabaseCopyRequest` (`DatabaseCopyService.TryQueue` closes the +gate and refuses a second copy); `DatabaseCopyWorker` runs it one at a time. Tables are copied in foreign-key order +(`DatabaseTable.InDependencyOrder`, Identity's included) in batches of 1000 ordered by key; shadow properties are +captured with the row. Pre-flight (`DatabaseCopyPreflight`) runs before the target changes; verification compares +an order-independent key checksum; progress is in memory, served as JSON by `/admin/settings?handler=CopyStatus`. +After settings saving starts a failure keeps the target and closes the gate until restart. See +[Moving to another database](../configuration.md#moving-to-another-database). + +## Settings + +`AddBaGetOptions` records each options type as a `SettingsSchemaRegistration`. `SettingsCatalog` reflects +over them (descriptions from XML docs, `[SensitiveSetting]`, `[RestartRequired]`); `SettingsService` validates +and writes `appsettings.Overrides.json` (path: `SettingsOverridesPath`) through `SettingsOverridesStore`; +administrators edit it on `/admin/settings`. `[AllowedSettingValues]` gives a string setting its choices and is also +what startup validation checks (`Database/Storage/Search:Type`). + +## Tests + +| Project | Covers | +|---|---| +| `BaGet.Core.Tests` | Domain services, settings, storage, indexing (unit) | +| `BaGet.Tests` | Integration: `BaGetApplication : WebApplicationFactory` — real pipeline over HTTP, SQLite in a temp directory, `SystemTime` fixed to 2020-01-01Z | +| `BaGet.Protocol.Tests`, `BaGet.Protocol.Samples.Tests` | Client library | +| `BaGet.Web.Tests`, `BaGet.Azure.Tests` | Web helpers, Azure providers | +| `BaGet.Storage.Tests` | Streaming storage contract per cloud provider on emulator containers; skipped without Docker | +| `BaGet.Clients.Tests` | Real `npm`, `mvn` and `docker` clients against the running server; skipped without Docker | +| `BaGet.Ha.Tests` | Redis cluster store on a container; skipped without Docker | +| `BaGet.Telemetry.Tests` | Telemetry export against Jaeger and an OpenTelemetry Collector containers (traces, metrics, logs, dead and stalled endpoints); skipped without Docker | +| `BaGet.Database.Tests` | Database copy between every pair of SQLite / SQL Server / PostgreSQL / MySQL on Testcontainers servers; skipped without Docker | + +xUnit v3 on Microsoft.Testing.Platform; see [Debugging](debugging.md) for commands. diff --git a/docs/advanced/debugging.md b/docs/advanced/debugging.md index a3e52e448..7aeb5059b 100644 --- a/docs/advanced/debugging.md +++ b/docs/advanced/debugging.md @@ -1,4 +1,55 @@ -# Debugging BaGet +# Debugging BaGet Extension -!!! warning - This page is a work in progress! +## Run + +Every project is strong-name signed with `SignKey.snk` at the repository root; the build fails without it. + +In a fresh clone create the `Packages` folder at the repository root first: nuget.config lists the untracked `Packages` folder as a package source, and restore fails with NU1301 without it. + +``` +cd src/BaGet +dotnet run -p:GeneratePackageOnBuild=false +``` + +`src/Directory.Build.props` packs on every build into the shared `Packages` folder; the flag stops that. +`dotnet run` may rewrite `src/BaGet/Properties/launchSettings.json` (it drops the IIS Express profile): +revert it rather than committing it. + +## Build and test + +``` +dotnet build BaGet.sln -p:GeneratePackageOnBuild=false +dotnet test BaGet.sln -p:GeneratePackageOnBuild=false +dotnet test tests/BaGet.Tests/BaGet.Tests.csproj -p:GeneratePackageOnBuild=false --filter-class "*UploadPageTests" +``` + +Tests need no external services (`BaGet.Database.Tests` uses Docker via Testcontainers and skips its 20 tests without a daemon; `BaGet.Telemetry.Tests`, `BaGet.Storage.Tests`, `BaGet.Clients.Tests` and `BaGet.Ha.Tests` do the same with their containers). `tests/BaGet.Tests/Support/BaGetApplication.cs` runs the real pipeline +over HTTP with SQLite in a temporary directory; it supplies settings with `builder.UseSetting(...)`. +Tests are xUnit v3 on Microsoft.Testing.Platform (opted in by `global.json`); filter with `--filter-class` / +`--filter-method`, which take `*` wildcards. + +## Port + +BaGet Extension listens on `http://localhost:6060`. `Kestrel:Endpoints:Http:Url` in `appsettings.json` outranks +`--urls` and `ASPNETCORE_URLS`, so those have no effect. Override it with the environment variable +`Kestrel__Endpoints__Http__Url`. + +## Logging + +Serilog, configured by the `Serilog` section of `appsettings.json` (see [Logging](../configuration.md#logging)). +Development already logs at `Debug`. Raise a namespace, for example: + +```json +{ "Serilog": { "MinimumLevel": { "Override": { "BaGet": "Debug" } } } } +``` + +Logs also go to `logs/baget-YYYYMMDD.log` under the content root. Level changes in a configuration file apply without a restart. + +## Command line + +| Command | Does | +| --- | --- | +| `dotnet BaGet.dll import downloads [-r ]` | imports nuget.org download counts (into repository ``, default `default`) | +| `dotnet BaGet.dll catalog rebuild [-r ]` | appends the catalog entries missing for existing packages of a repository (default `default`) | +| `dotnet BaGet.dll account reset-password [--email
]` | sets a generated password, switches off two-factor, lifts lockout; needs `Accounts:Enabled` | +| `dotnet BaGet.dll account promote ` / `demote ` | sets or clears the administrator flag; needs `Accounts:Enabled`; the last administrator cannot be demoted | diff --git a/docs/advanced/sdk.md b/docs/advanced/sdk.md index 1c41e1805..0f126b45b 100644 --- a/docs/advanced/sdk.md +++ b/docs/advanced/sdk.md @@ -1,6 +1,6 @@ -# BaGet SDK +# BaGet Extension SDK -You can use BaGet's [`BaGet.Protocol`](https://www.nuget.org/packages/BaGet.Protocol) package to interact with a NuGet server. +You can use BaGet Extension's [`BaGet.Protocol`](https://www.nuget.org/packages/BaGet.Protocol) package to interact with a NuGet server. ## Getting Started @@ -12,12 +12,12 @@ dotnet add package BaGet.Protocol ## List Package Versions -Find all versions of the `Newtonsoft.Json` package: +Find the listed versions of the `Newtonsoft.Json` package: ```csharp NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); -IReadOnlyList> versions = await client.ListPackageVersionsAsync("Newtonsoft.Json"); +IReadOnlyList versions = await client.ListPackageVersionsAsync("Newtonsoft.Json"); foreach (NuGetVersion version in versions) { @@ -56,19 +56,19 @@ foreach (var metadata in items) { Console.WriteLine($"Version: {metadata.Version}"); Console.WriteLine($"Listed: {metadata.Listed}"); - Console.WriteLine($"Tags: {metadata.Tags}"); + Console.WriteLine($"Tags: {string.Join(", ", metadata.Tags ?? Array.Empty())}"); Console.WriteLine($"Description: {metadata.Description}"); } -// Or, find the metadata for a single version of a package. -string packageId = "Newtonsoft.Json" +// Or, find the metadata for a single version of a package +// (throws PackageNotFoundException when the package does not exist). +string packageId = "Newtonsoft.Json"; NuGetVersion packageVersion = new NuGetVersion("12.0.1"); -PackageMetadata metadata = await client.GetPackageMetadataAsync(packageId, packageVersion); +PackageMetadata? single = await client.GetPackageMetadataAsync(packageId, packageVersion); -Console.WriteLine($"Listed: {metadata.Listed}"); -Console.WriteLine($"Tags: {metadata.Tags}"); -Console.WriteLine($"Description: {metadata.Description}"); +Console.WriteLine($"Listed: {single?.Listed}"); +Console.WriteLine($"Description: {single?.Description}"); ``` ## Search for packages @@ -81,6 +81,49 @@ IReadOnlyList results = await client.SearchAsync("json"); foreach (SearchResult result in results) { - Console.WriteLine($"Found package {result.PackageId} {searchResult.Version}"); + Console.WriteLine($"Found package {result.PackageId} {result.Version}"); } ``` + +## Read a catalog + +Types are in `BaGet.Protocol.Catalog`. A mirror follows a server's [catalog](https://learn.microsoft.com/nuget/api/catalog-resource) with +`CatalogProcessor`, which hands each new leaf to an `ICatalogLeafProcessor` you implement and +remembers how far it got in an `ICursor`: + +```csharp +var httpClient = new HttpClient(); +var factory = new NuGetClientFactory(httpClient, "https://api.nuget.org/v3/index.json"); + +var processor = new CatalogProcessor( + new FileCursor("cursor.json", loggerFactory.CreateLogger()), + factory.CreateCatalogClient(), + new MyLeafProcessor(), + new CatalogProcessorOptions + { + DefaultMinCommitTimestamp = DateTimeOffset.MinValue, + MaxCommitTimestamp = DateTimeOffset.MaxValue, + }, + loggerFactory.CreateLogger()); + +await processor.ProcessAsync(); +``` + +## Other calls + +`NuGetClient` also has: + +* `ExistsAsync(packageId)` and `ExistsAsync(packageId, version)`: whether a package or version exists +* `DownloadPackageManifestAsync(packageId, version)`: the `.nuspec` +* `ListPackageVersionsAsync(packageId, includeUnlisted)`: with `true`, also unlisted versions (from the package content resource) +* `AutocompleteAsync(...)`: package id suggestions (for version suggestions use `clientFactory.CreateAutocompleteClient().ListPackageVersionsAsync`) + +`NuGetClientFactoryExtensions.CreateCatalogProcessor` is a shortcut for the wiring in +[Read a catalog](#read-a-catalog). + +## Multiple search endpoints + +When a server's service index lists several endpoints for search or autocomplete, as nuget.org's +does, the client tries them in order and moves to the next on a network failure, a timeout, a 408, +a 429, a 5xx, a dropped connection (`IOException`) or an unreadable response. Any other status, such as a 404, is the server's answer and +is returned as is. The service index is re-read after 40 minutes. diff --git a/docs/configuration.md b/docs/configuration.md index 3b8c34ccf..354f311f1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,6 +1,60 @@ # Configuration -You can modify BaGet's configurations by editing the `appsettings.json` file. +You can modify BaGet Extension's configurations by editing the `appsettings.json` file. + +## Top-level keys + +| Key | Default | Meaning | +| --- | --- | --- | +| `ApiKey` | empty | global key to push and change packages; see [Require an API key](#require-an-api-key) | +| `PathBase` | `.` | path the site is served under (`.` is the root) | +| `AllowedHosts` | `*` | see [Restrict the host names BaGet Extension serves](#restrict-the-host-names-baget-extension-serves) | +| `PackageDeletionBehavior` | `Unlist` | `Unlist` or `HardDelete` | +| `AllowPackageOverwrites` | `false` | accept a push of an existing id and version | +| `IsReadOnlyMode` | `false` | refuses pushes (packages and symbols), deletes, relists, deprecation/vulnerability changes, browser uploads, the manage page's POSTs and an administrator's permanent deletion of a deleted user's packages | +| `RunMigrationsAtStartup` | `true` | apply pending database migrations when BaGet Extension starts | +| `SettingsOverridesPath` | empty (= `appsettings.Overrides.json`) | the file the [Settings page](#settings-page) saves to; relative paths start at the content root (or `BAGET_CONFIG_ROOT`) | +| `Urls` | none | the ASP.NET Core listening-address key; ineffective while `Kestrel:Endpoints` is set, see [Listening address](#listening-address) | +| `Proxy:TrustedProxies`, `Proxy:TrustedNetworks`, `Proxy:TrustAnyProxy` | loopback only | which reverse proxies may set `X-Forwarded-For`/`-Proto`, see [Reverse proxies](#reverse-proxies-and-forwarded-headers) | +| `Cors:AllowedOrigins` | empty (any origin, without credentials) | origins allowed to call BaGet from a browser, see [Single-page applications](#single-page-applications) | +| `Frontend:SpaPath`, `Frontend:SpaBasePath`, `Frontend:Mvc` | none, `/app`, `true` | serve a built single-page application, or run without the server-rendered screens, see [Single-page applications](#single-page-applications) | +| `DataProtection:KeyPath` | `DataProtection-Keys` beside the overrides file | folder of the key ring, see [Data protection keys](#data-protection-keys) | + +## Listening address + +The shipped `appsettings.json` sets `Kestrel:Endpoints:Http:Url` to `http://localhost:6060`. That +setting outranks `--urls` and `ASPNETCORE_URLS`, which therefore have no effect. Override it with the +environment variable `Kestrel__Endpoints__Http__Url`, or edit the file. + +## Reverse proxies and forwarded headers + +BaGet Extension reads the client address and scheme from `X-Forwarded-For` / `X-Forwarded-Proto`, **only when the +request comes from a trusted proxy**. By default that is loopback only (the framework default), so a client that +reaches the server directly cannot spoof its address (the per-client rate limits and the log) or the scheme. +These keys are read at startup, from `appsettings.json`, environment variables or the command line (not the Settings page). + +| Key | Meaning | +| --- | --- | +| `Proxy:TrustedProxies` | proxy addresses separated by `;`, added to loopback: `10.0.0.5;fd00::1` | +| `Proxy:TrustedNetworks` | proxy networks in CIDR form separated by `;`: `10.0.0.0/8;172.16.0.0/12` | +| `Proxy:TrustAnyProxy` | `true` believes every sender (the behaviour before this setting existed). Only safe when clients can reach BaGet through the proxy alone | + +An address or network that does not parse stops startup. Behind a proxy on another address without any of these, the +forwarded headers are ignored: the client address is the proxy's and an `https` front end looks like `http`. + +## Data protection keys + +The key ring encrypts remote repository passwords, replication peer keys, sessions, antiforgery and registry tokens and +reset/confirmation links. A single node keeps it in `DataProtection:KeyPath` (default: a `DataProtection-Keys` folder beside the +[overrides file](#settings-page); a relative path starts at that file's folder), as XML files, encrypted with DPAPI (machine scope) on Windows and **plain XML elsewhere**: treat the folder like the +database and **keep it on a persistent volume** (in Docker it is inside `/var/baget` when `SettingsOverridesPath` is). Losing it +makes stored passwords unreadable (remote upstreams are then called anonymously) and signs everyone out. In a cluster +(`Ha:Enabled`) the keys are in the database and this key is ignored. The folder must be writable: startup stops with a message naming `DataProtection:KeyPath` otherwise. Restart required; not on the Settings page. + +## Exit codes + +`baget` exits with `0` when the command or the server finished, and `1` when the configuration is invalid or a command was +refused or failed, so `restart: on-failure` and systemd see a failed start. ## Require an API key @@ -17,9 +71,41 @@ To do so, you can insert the desired API key in the `ApiKey` field. Users will now have to provide the API key to push packages: ```c# -dotnet nuget push -s http://localhost:5000/v3/index.json -k NUGET-SERVER-API-KEY package.1.0.0.nupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k NUGET-SERVER-API-KEY package.1.0.0.nupkg +``` + +With [accounts](#accounts-package-owners-and-api-keys) enabled, users can also push with keys of their own. + +## Restrict the host names BaGet Extension serves + +The absolute URLs BaGet Extension advertises in its service index, registrations and URI templates are +built from the incoming request's `Host` header. By default BaGet Extension serves any host, because it +is commonly run behind a reverse proxy on a host name it cannot know. If the host names are +known, list them in `AllowedHosts`, separated by semicolons; a request with any other host is +then rejected with a `400` response: + +```json +{ + ... + + "AllowedHosts": "nuget.example.com;nuget.example.com:8080", + + ... +} ``` +| Entry | Matches | +| --- | --- | +| `*` | any host — host filtering is off (the default) | +| `example.com` | that host on any port | +| `example.com:8080` | that host on port 8080 only | +| `*.example.com` | any subdomain of `example.com` | + +!!! info + This is [ASP.NET Core's host filtering](https://learn.microsoft.com/aspnet/core/fundamentals/servers/kestrel/host-filtering) + configuration key. If you embed BaGet Extension in your own application, call `UseHostFiltering` in + its pipeline. + ## Enable read-through caching Read-through caching lets you index packages from an upstream source. You can use read-through @@ -28,7 +114,7 @@ caching to: 1. Speed up your builds if restores from [nuget.org](https://nuget.org) are slow 1. Enable package restores in offline scenarios -The following `Mirror` setting configures BaGet to index packages from [nuget.org](https://nuget.org): +The following `Mirror` setting configures BaGet Extension to index packages from [nuget.org](https://nuget.org): ```json { @@ -46,10 +132,81 @@ The following `Mirror` setting configures BaGet to index packages from [nuget.or !!! info `PackageSource` is the value of the [NuGet service index](https://docs.microsoft.com/en-us/nuget/api/service-index). +| Key | Default | Meaning | +| --- | --- | --- | +| `Enabled` | `false` | index packages from the upstream | +| `PackageSource` | none | the upstream service index URL; required while `Enabled` (startup fails otherwise) | +| `Legacy` | `false` | read the upstream through the NuGet V2 protocol | +| `PackageDownloadTimeoutSeconds` | `600` | timeout of every HTTP request to the upstream (and of `import downloads`) | + +While `Enabled`, a [remote repository](remote-repositories.md#the-mirror) named `mirror` is created from these keys at startup and the +default repository fetches through its settings: set credentials, cache periods or offline mode for the mirror on +`/admin/repositories/mirror`. The URL, protocol and timeout stay owned by these keys. + +## Remote repositories: refuse private upstreams + +An upstream URL (and *Test connection*) makes this server send requests to whatever address the administrator typed, so +an administrator who may create remote repositories can reach what the server can reach (internal services, the cloud +metadata address `169.254.169.254`). Internal feeds are a normal use, hence the default is to allow them. + +| Key | Default | Meaning | +| --- | --- | --- | +| `Remote:BlockPrivateAddresses` | `false` | refuse upstreams that are `localhost`, loopback, private (RFC 1918, `fc00::/7`), link-local, carrier-grade NAT or otherwise non-public, IPv6 forms that carry an IPv4 address (NAT64, 6to4, IPv4-compatible) judged by the address they carry. While on, the system proxy is not used (the target must be seen). Live (no restart) | + +Enforced when a repository is created or saved (the host name or literal address in the URL), when *Test connection* runs +(also after DNS resolution) and on every connection a V3 or npm upstream client opens (a name that later resolves to a private +address, or a redirect to one, is refused; with an HTTP proxy configured the proxy's address is what is checked). A V2 +upstream is contacted by NuGet's own HTTP stack: only the URL's host is checked. `Mirror:PackageSource` is operator +configuration: if it is refused the `mirror` repository is not created (a warning is logged) and fetches fail. + +## npm repositories + +| Key | Default | Meaning | +| --- | --- | --- | +| `Npm:UnpublishWindow` | `72:00:00` | how long after publishing a version its owner may unpublish it with Deploy alone; later unpublishing needs Delete. A key limited to `package:pushversion` always needs Delete. Zero or negative: always Delete. Live | +| `Npm:MaxPublishBytes` | `536870912` | largest `npm publish` request body in bytes (413 above); `0` = no limit. Live | + +See [npm registry](npm-registry.md). + +## Docker repositories + +| Key | Default | Meaning | +| --- | --- | --- | +| `Oci:TokenLifetime` | `00:05:00` | validity of a registry token from `/v2/token` (at least 10 seconds). Live | +| `Oci:Service` | `BaGet` | the `service` named in the registry's `WWW-Authenticate` challenge and expected at the token endpoint. Live | +| `Oci:MaxManifestBytes` | `4194304` | largest manifest or index in bytes (413 above). Live | +| `Oci:UploadExpiry` | `1.00:00:00` | idle time after which an upload session is discarded (checked when a new upload starts, and by the Docker garbage collection). Live | +| `Oci:PruneGrace` | `01:00:00` | how long a layer no manifest uses is kept before *Remove unused layers* or the Docker garbage collection may remove it. Live | + +See [Docker registry](docker-registry.md). + +## Maven repositories + +| Key | Default | Meaning | +| --- | --- | --- | +| `Maven:MaxFileBytes` | `1073741824` | largest file in bytes a deploy or a remote download may store (413 above). Live | + +See [Maven repositories](maven-repositories.md). + +## Vulnerability scanning + +| Key | Default | Meaning | +| --- | --- | --- | +| `Scanning:Enabled` | `false` | master switch; scanning calls OSV.dev, so it is off by default. Live | +| `Scanning:ScanOnDeploy` | `true` | queue a scan when a version is stored. Live | +| `Scanning:RescanInterval` | `1.00:00:00` | versions whose last scan is older are scanned again by a sweep every 10 minutes; `0` = never. Live | +| `Scanning:OsvUrl` | `https://api.osv.dev` | the OSV API root. Live | +| `Scanning:OsvOfflinePath` | empty | a directory or `.zip` of OSV records: scan without the internet. Live | +| `Scanning:OsvTimeout`, `Scanning:OsvCacheLifetime` | `00:00:30`, `01:00:00` | one OSV request; how long an answer per component is reused. Live | +| `Scanning:TrivyPath`, `Scanning:TrivyRegistryHost` | empty | the `trivy` executable and this server's registry address as Docker clients use it; both are needed to scan images. Live | +| `Scanning:TrivyServerUrl`, `Scanning:TrivyInsecure`, `Scanning:TrivyRegistryUser`, `Scanning:TrivyRegistryPassword`, `Scanning:TrivyTimeout` | empty, `false`, empty, empty, `00:10:00` | `--server`, `--insecure`, the credentials Trivy pulls with (the password is a sensitive setting) and the limit of one run. Live | + +See [vulnerability scanning](vulnerability-scanning.md). + ## Enable package hard deletions To prevent the ["left pad" problem](https://blog.npmjs.org/post/141577284765/kik-left-pad-and-npm), -BaGet's default configuration doesn't allow package deletions. Whenever BaGet receives a package deletion +BaGet Extension's default configuration doesn't allow package deletions. Whenever BaGet Extension receives a package deletion request, it will instead "unlist" the package. An unlisted package is undiscoverable but can still be downloaded if you know the package's id and version. You can override this behavior by setting the `PackageDeletionBehavior`: @@ -64,9 +221,20 @@ downloaded if you know the package's id and version. You can override this behav } ``` +This setting also labels the button on a package's management page: it reads "Unlist this version" +by default and "Delete this version permanently" with `HardDelete`, so the page never offers a +deletion the server would only unlist. Two things a hard delete does *not* do: it leaves indexed +symbols being served from `api/download/symbols/...` (delete them first from the Manage page's *Symbols* list), +and an external search index (`Search:Type=AzureSearch`) is re-indexed for the ID after every unlist, relist +and delete (`SearchIndexChangeHandler`). + +Administrators (see [Administrators](#administrators)) can always hard-delete from a package's management +page, after confirming their password, even with the default `Unlist`. The NuGet `DELETE` API keeps +following this setting. + ## Enable package overwrites -Normally, BaGet will reject a package upload if the id and version are already taken. You can configure BaGet +Normally, BaGet Extension will reject a package upload if the id and version are already taken. You can configure BaGet Extension to overwrite the already existing package by setting `AllowPackageOverwrites`: ```json @@ -79,16 +247,559 @@ to overwrite the already existing package by setting `AllowPackageOverwrites`: } ``` -## Private feeds +## Upload through the browser + +`/upload` accepts a `.nupkg` or a `.snupkg` in two steps: the file is staged, what it contains is +shown, and nothing is published until the preview is confirmed. With +[accounts](#accounts-package-owners-and-api-keys) on, the signed-in session is the identity and +ownership decides what it may publish; with accounts off the page asks for the same `ApiKey` a push +needs. `IsReadOnlyMode` refuses both. A `.snupkg` is indexed for a version the server already has - +it never creates a package ID and confers no ownership. The *Upload* navigation entries are hidden +where an upload cannot work: read-only mode, a closed maintenance gate, or accounts off with no `ApiKey`. + +| Operating note | | +| --- | --- | +| Temporary space | Each upload is spooled to `ASPNETCORE_TEMP` (else the system temporary directory) before it is staged, so a browser upload needs free space there equal to the package's size, on top of the staged copy. | +| Size ceiling | No multipart limit of its own on the upload and push endpoints, which carry `[UploadSizeLimit]` (the NuGet and symbol push, the NuGet, npm and Maven upload screens and their `/api/ui` twins); every other form is limited to 1 MiB (`FormOptions.MultipartBodyLengthLimit`, since antiforgery validation buffers the whole form of any POST, anonymous ones included). Beyond it the request is rejected with a bare `400` before the page runs, so the page cannot explain it. Under IIS in-process, `IISServerOptions.MaxRequestBodySize` caps uploads at 250 MB and `requestLimits/maxAllowedContentLength` in `web.config` at 30 MB - the ceilings the push endpoint already has. | +| Unconfirmed uploads | Staged under `staging/` in the configured store, and removed when the preview is confirmed or discarded. Whatever nobody comes back to is swept after 24 hours - on `FileSystem` and `Null` storage; the cloud providers cannot list a prefix yet, so abandoned uploads there accumulate. | +| `Storage:Path` | Do not point it at the web root: static files would then serve the store, `staging/` and `validation/` included. That is a pre-existing misconfiguration rather than something uploads introduce. | + +## NuGet V2 feed + +BaGet Extension serves a NuGet V2 (OData) feed at `/api/v2` for clients that cannot use V3: `nuget list`, +older `Install-Package`, and PowerShellGet. It is on by default. + +`GET /api/v2/$metadata` (and `/r/{repo}/api/v2/$metadata`) returns the entity model as an EDMX document (`application/xml`, OData +2.0): the entity type `NuGetGallery.V2FeedPackage` (key `Id` + `Version`, every property the entries carry, `m:HasStream`: an +entry's content is the `.nupkg`), the entity set `Packages` and the service operations `Search(searchTerm, includePrerelease, +semVerLevel)` and `FindPackagesById(id, semVerLevel)`, so OData tools can generate a client from it. + +To turn the feed off: + +```json +{ + ... + + "Feeds": { + "EnableV2": false + }, + + ... +} +``` + +!!! info + The OData query options `$filter`, `$orderby`, `$select` and `$expand` are ignored; `$skip` and + `$top` are honoured. `Search()` and `Packages()` page by package id (`$top` ids, at most 1000) and + emit a `next` link while more ids follow; they list only the versions the request allows + (`includePrerelease`, and SemVer 2 versions only with `semVerLevel=2.0.0`, like `FindPackagesById()`). + +## Accounts, package owners and API keys -A private feed requires users to authenticate before accessing packages. +Accounts are **on** in the shipped `appsettings.json` (the code default, for hosts embedding BaGet Extension, is +off). With them off, only the global `ApiKey` authenticates. Set `Accounts:Enabled` to `false` to get +that behaviour back; otherwise configure them with: + +```json +{ + ... + + "ApiKey": "NUGET-SERVER-API-KEY", + + "Accounts": { + "Enabled": true, + "AllowRegistration": true + }, + + ... +} +``` + +| Key | Default | Meaning | +| --- | --- | --- | +| `Enabled` | `false` in code, `true` in the shipped file | turns accounts on | +| `AllowRegistration` | `true` | whether `/account/register` creates accounts | +| `RequireApproval` | `false` | a self-registered account (registration page, or first sign-in through the external provider) stays disabled until an administrator approves it on `/admin/users`; accounts an administrator creates are never pending. See [Approving new accounts](#approving-new-accounts) | +| `InitialAdministrators`, `CreateDefaultAdministrator` | none, `true` | see [Administrators](#administrators) | +| `OpenIdConnect:*` | none | see [Sign in with OpenID Connect](#sign-in-with-openid-connect) | +| `OpenIdConnectProviders::*` | none | named providers, see [Several providers](#several-providers) | + +Users then sign in at `/account/login`, create an account at `/account/register` (unless +`AllowRegistration` is `false`), and create API keys at `/account/apikeys`. `/account/packages` +lists the IDs they own, directly or through an organization, and links to each one's +`/packages/{id}/manage`. A key is shown once, and has: + +| Property | Meaning | +| --- | --- | +| Scopes | `package:push` (new IDs and new versions), `package:pushversion` (new versions of owned IDs only), `package:unlist` (unlist, relist, delete, deprecation and vulnerabilities), and for administrators only `admin:api` (the [administration REST API](admin-api.md); never given to sessions or npm tokens) | +| Package glob pattern | the IDs the key applies to, `*` as a wildcard, for example `Contoso.*` | +| Repositories | optional: the repositories the key may be used in (tick them on `/account/apikeys`; none ticked = every repository, as every key was before). See [Repository-scoped keys](access-control.md#repository-scoped-api-keys) | +| Expiry | after which the key stops working | + +Who may change a package: + +* The global `ApiKey` may change any package. +* Pushing a new package ID makes the pusher its owner. +* Only an owner, directly or through an [organization](#organizations), may push new versions of an ID or manage it. +* A package pushed before accounts were enabled has no owner. Only the global `ApiKey` and administrators (see [Administrators](#administrators)) may change it, and pushing to it never makes anyone its owner. + Add owners from its manage page (`/packages/{id}/manage`) to hand it over. + +!!! warning "Upgrade note: keyless pushes are refused" + Earlier releases shipped with accounts off, so a default install accepted `dotnet nuget push` with + no key. With accounts on and `ApiKey` empty, a push without a key now gets **401**; BaGet Extension logs a + warning at startup. Fix CI by pushing with `-k `, using a user key from `/account/apikeys` (or + the global `ApiKey`), or restore the old behaviour with `"Accounts": { "Enabled": false }`. !!! warning - Private feeds are not supported at this time! See [this pull request](https://github.com/loic-sharma/BaGet/pull/69) for more information. + With accounts off, set `ApiKey`. Without it the server is open: anyone may push anything. + +### Approving new accounts + +With `Accounts:RequireApproval` on, `/account/register` creates the account but does not sign the user in, and no route +(password, two-factor, external provider, API key) works for it until an administrator approves it. The user is told to +wait (also when email is configured: the registration result page and the email confirmation page say approval is needed; the confirmation mail does not). A +sign-in attempt with the right password says the account awaits approval; a wrong password gets the usual "incorrect" +message and counts as a failed attempt, so a pending account locks out like any other and a locked-out one answers +"locked" whatever the password (passwords are not revealed; a "locked" answer shows the name exists, as for every account). `npm login` follows the same rule. + +- **Approve:** `/admin/users` shows an "Awaiting approval" label and a count, and `/admin/users/{name}` the status; *Approve* (on either page) asks for your password and is refused with `503` while the read-only gate is closed. The approval is logged at Warning. Command line: `baget account approve `. +- **Promotion approves:** making a user an administrator (`account promote`, `Accounts:InitialAdministrators`, the Users page, the REST API) also approves the account, so a recovery never leaves the only administrator unable to sign in. +- **Reject:** delete the account (*Delete* on the same page). +- Turning the setting off does not approve existing pending accounts; approve them first. Existing accounts are never pending. +- Not offered over the REST API (which only reports `pendingApproval` on the user objects); the pages and `account approve` are the way. + +### Administrators + +An account can be an **administrator**: a flag kept in the database, on the account. An administrator +reaches `/admin/users` (the "Users" entry of the account menu), where they promote and demote other +accounts, each time confirming with their password (or by signing in again with the provider, for an +account without one). Everyone else, and every request while accounts are off, gets 404 there. + +#### Default administrator + +| | | +| --- | --- | +| User name | `Admin` | +| Password | `Admin1234!` | +| Created | at startup, only when accounts are on (`Accounts:Enabled`, the default) and the database has **no users at all** (a fresh install) | +| Not created | when any user exists (an upgraded server, or users registered first), or `Accounts:CreateDefaultAdministrator` is `false` | + +The password is public: sign in at `/account/login` and change it at once on **Account > Settings** (`/account/settings`). +Every start logs a warning while `Admin` still has it; nothing else forces the change. `Admin` is an ordinary account: +once another administrator exists it can be demoted or deleted on `/admin/users`. + +Lost access: `baget account reset-password Admin` sets a generated password (printed once) and switches off two-factor +authentication, and `baget account promote ` makes any existing account an administrator (see the table below). + +```json +"Accounts": { + "InitialAdministrators": "alice;bob" +} +``` + +| Setting or command | Meaning | +| --- | --- | +| `Accounts:InitialAdministrators` | User names, separated by `;`, promoted at start **only while no administrator exists** (it bootstraps an empty server). Only accounts that already exist are promoted; once any administrator exists the list is ignored, so registering a listed name later grants nothing and a demotion is not reversed. | +| `Accounts:CreateDefaultAdministrator` | Default `true`. On a server with **no users at all**, startup creates the administrator `Admin` with password `Admin1234!` (email counted as confirmed, so it can sign in while SMTP is configured). Every start warns until the password is changed. Set `false` to bootstrap only through `InitialAdministrators` or `account promote`. | +| `Accounts:SessionTokenLifetime`, `Accounts:SessionRefreshLifetime`, `Accounts:SessionMaxLifetime` | Defaults `00:15:00`, `14.00:00:00` and `30.00:00:00`. Lifetime of the access and refresh tokens of `POST /api/ui/session`, and the longest a session lasts from the sign-in however often it is refreshed ([sessions](ui-api.md#sessions-for-a-single-page-application)). Not shown on the Settings page; a changed password or "sign out everywhere" ends every token regardless. | +| `baget account promote ` | Makes the user an administrator. Needs `Accounts:Enabled`; exit code 1 for an unknown user. | +| `baget account approve ` | Enables a self-registered account that waits for approval (`Accounts:RequireApproval`). Needs `Accounts:Enabled`; exit code 1 for an unknown user. `promote` approves too. | +| `baget account demote ` | Removes the flag. Exit code 1 for an unknown user or the last administrator. | + +* The **last administrator cannot be demoted, and cannot delete their account**: promote another user first. + If every administrator is lost anyway, use `baget account promote` or `InitialAdministrators` (the latter works again once no administrator is left). +* **Package powers.** An administrator skips *ownership* only, never a key's scopes or glob (a push-only key an + administrator made for CI stays push-only; use a separate non-admin account for CI keys): + + | Where | Power | + | --- | --- | + | API | Push a version of, or unlist, any existing ID (needs `PushVersion`/`Push`, or `Unlist`). A new ID still needs `Push` and makes the pusher its owner. | + | `/packages/{id}/manage` | Opens for any ID, ownerless ones included, with a "managing as an administrator" banner. Writes by a non-owner administrator are logged (`Administrator {Admin} ran {Handler} on {PackageId}`). | + | Manage, *Delete permanently* | Hard-deletes one version, or every version and the owners (*Danger zone*), whatever `PackageDeletionBehavior` says. Needs the administrator's password (or a fresh provider sign-in); logged. Read-only mode refuses it. | + | Manage, *Verified* | Marks or clears the ID as verified (reserved); owners see the state but cannot change it. | + | `/admin/users/{name}/packages` | The IDs a user owns, with owners and a link to Manage. | + | `/admin/packages` | IDs with no owner (predating accounts, or left without one) in every repository, 50 per page; a Repository column appears once one is outside `default`, and each link goes to that repository's page. | +| Manage, *Vulnerabilities* | Owners and administrators add or remove a version's advisories (http/https URL, severity low to critical, optional version range); the same rules as the `PUT .../vulnerabilities` API. | +| Manage, *Deprecation* | Reasons, message, alternate package and alternate version range, with the rules of the `PUT .../deprecation` API. | +| Manage, *Validation status* | With validation on, a link to `/packages/{id}/validation`: each version's newest submission and the verdict and message of every step (the page form of `GET /v3/package/{id}/{version}/validation`; needs push or manage). | +| Manage, *Symbols* | Lists the PDBs each version's symbol package contributed and deletes them (database rows and stored content; content another version still lists is kept). Only symbols indexed after this list was introduced are recorded: older ones keep being served but cannot be listed or deleted per package. Not available with Azure Table. | +| Package page, *Manage package* | Shown only to an owner (directly or through an organization) or an administrator. | +* The check reads the database on every request, so a demotion applies at once. + +**User powers** (`/admin/users`; each action asks for the administrator's password, and none applies to your own row, which stays on `/account/settings`): + +| Action | Behaviour | +| --- | --- | +| Name (`/admin/users/{name}`) | The user's detail page, built from sections: account, organizations, API keys (see below). | +| Packages | Opens `/admin/users/{name}/packages`. | +| Create a user | The *Create a user* form: name, optional email, and a typed password, a generated one (blank field; shown **once**, like a reset) or *Send an invitation* (needs SMTP and an address): the account gets an unknown random password and is mailed a reset link to choose its own. A name used by a user or organization is refused. The address counts as confirmed. Logged at `Warning`. | +| Reset password, *Generate* | Replaces the password with a generated one, shown **once** on the response (no redirect, `Cache-Control: no-store`, never stored or logged). Two-factor is switched off, a lockout lifted, an unconfirmed email address marked confirmed, the user's sessions end. | +| Reset password, *Email link* | Mails the user a reset link. Only offered while SMTP is configured and the user has an address; no rate limit. | +| Delete (`/admin/users/{name}/delete`) | Removes the account, its API keys and its ownerships. The last administrator cannot be deleted. | + +* **API keys of any user** (`/admin/users/{name}`): lists description, scopes, package pattern, repositories and dates (never the key or its hash) and revokes one. Needs the administrator's password; logged. +* **Organizations** (`/admin/organizations`, `/admin/organizations/{name}`; every action asks for the password, 503 while the server is read-only for maintenance): + + | Action | Behaviour | + | --- | --- | + | List | Every organization with member, administrator and owned package-ID counts (all repositories). | + | Rename | Updates the organization and every `PackageOwner` row naming it, **in every repository**, in one save. Refused if the name is a user's or another organization's (a change of case is fine), blank, over 256 characters or has `/ \ ? # %`. | + | Delete | Removes the organization and its memberships. Refused while it owns a package ID in any repository (remove it as an owner first). | + | Members | Add by user name (optionally administrator), promote/demote, remove. An organization always keeps at least one administrator. | + +* **Account deletion by an administrator** is never blocked by ownership. A package ID the user alone owned is either + *left without owners* (the default: only administrators and the global API key manage it, like IDs that predate accounts) + or *deleted permanently with all its versions*, in **every** repository the user was sole owner in (the confirmation lists each as `ID (repository)`). The user is removed first; a failure while deleting packages is reported + and never rolls the deletion back. +* **Organizations**: if the user is the last organization administrator and others remain, the longest-standing member + becomes administrator. If the user is the only member and the organization owns packages, the organization is kept without members; + one that owns nothing is deleted. +* **Audit log**: resets, reset links and deletions are logged at `Warning` with the administrator and the user, never a password. + +### Email (optional) + +Email is off until `Email:Smtp` has a `Host` and a `From`. While it is off, nothing that needs email +is offered, and sign-in does not require a confirmed address. When it is on, sign-in requires one. + +```json +{ + "Email": { + "Smtp": { + "Host": "smtp.example.com", + "Port": 587, + "UserName": "baget", + "Password": "...", + "EnableSsl": true, + "From": "BaGet Extension " + } + } +} +``` + +| Key | Default | +| --- | --- | +| `Host`, `From` | none; both required to switch email on | +| `Port` | `587` | +| `EnableSsl` | `true` | +| `UserName`, `Password` | none | + +`EnableSsl` uses implicit TLS on port 465 and STARTTLS otherwise; `false` sends in the clear. A send failure is logged and +reported to the user as a failure. + +**Links in emails need `Site:PublicUrl`.** Confirmation and password-reset links are never built from +the request's `Host` header, which anyone can forge (a forged `Host` on "forgot password" would +otherwise put the attacker's address in the victim's mail). + +| Configuration | Links point at | +|---|---| +| `Site:PublicUrl` set (absolute http/https, a path is allowed: `https://example.com/feed`) | `Site:PublicUrl` | +| No `PublicUrl` (whatever `AllowedHosts` says) | **email is switched off** and a startup warning says so | + +`AllowedHosts` does not help: even a restricted host list leaves the scheme to `X-Forwarded-Proto`, +which a client can spoof to downgrade a link to `http`. + +```json +{ "Site": { "PublicUrl": "https://packages.example.com" } } +``` + +An invalid `PublicUrl` fails startup. While email is switched off for this reason, nothing that needs +it is offered and sign-in does not require a confirmed address, exactly as with no SMTP. + +Other rules with email on: + +* Changing the email address, setting a first password, deleting the account and turning two-factor + off or resetting it ask for the current password. An account without a password (external sign-in + only) must instead sign in again with its provider (the provider is asked to prompt for credentials + again) within the last 5 minutes (the provider must return an `auth_time` claim inside that window, otherwise the sign-in is refused); without a configured provider it cannot do these, and an + administrator uses `baget account reset-password`. +* "Forgot password" answers identically, in the same time, for known and unknown accounts: the mail is + sent from a background queue. One reset mail per account per 10 minutes is the real protection; 60 mails per client + address per 10 minutes is a backstop. There is no site-wide cap, which would let one caller block everyone's + reset. State is in memory, per process, and bounded by the number of accounts; excess requests are answered the same and mail nothing. Requests for names that do not exist use up + nothing. Known limit: the client address comes from `X-Forwarded-For`, which is believed only from a trusted + proxy ([Reverse proxies](#reverse-proxies-and-forwarded-headers)); behind a proxy that sets no such header all callers share one + address. Hence the per-client backstop is high and the per-account limit is what holds. +* OpenID Connect accounts are confirmed only when the provider sends `email_verified=true`; otherwise a + confirmation link is mailed and the user signs in again once it is followed. A provider that sends no + email address cannot create accounts while email is on. +* Contact owners uses the sender's address only if it is confirmed. +* Browser sessions are checked against the database on every request, so a deleted user's other + sessions, or sessions of a user whose password was reset, stop working immediately. + +Without email, an administrator recovers an account from the command line: + +``` +baget account reset-password +``` + +It prints a generated password, switches off the user's two-factor authentication and lifts any +lockout, and marks the user's email address confirmed (the administrator at the console is trusted). +It needs `Accounts:Enabled` and works with or without SMTP. + +**Turning SMTP on with existing users.** Sign-in then requires a confirmed address. A user with an +address who knows their password can use "Forgot password" (following the link confirms it). A user +with no address cannot sign in: the administrator runs +`baget account reset-password --email
`, which sets the address, marks it confirmed +and prints a new password. The Users page does the same: its *Confirm* section takes the address, used by *Generate a password*. + +Email also enables **Contact owners** on a package page (`/packages/{id}/contact-owners`, signed-in +users only). The message goes, one email each, to the owning users with a confirmed address and to the +administrators of owning organizations, with the sender in `Reply-To`; the sender never sees owner +addresses. One message per sender per package every 10 minutes, counted in memory per process (it +resets on restart and is not shared between instances). Without email the page answers 404 and the +link is not shown. + +### Avatars + +Owners, profiles and the account menu show a [Gravatar](https://gravatar.com) (`d=retro`), keyed by +the MD5 of the user's email, or of the name for organizations and users without an email. Every +avatar is a request from the visitor's browser to gravatar.com carrying that hash. A private feed can +turn them off, which shows initial-letter placeholders instead: + +```json +{ "Site": { "UseGravatar": false } } +``` + +`Site:UseGravatar` defaults to `true`. + +### Organizations + +Signed-in users create organizations at `/account/organizations`. An organization can own packages +like a user; its members act for it, and its administrators add and remove members. User and +organization names share one namespace. + +### Sign in with OpenID Connect + +To let users sign in with an external provider such as Microsoft Entra ID: + +```json +{ + ... + + "Accounts": { + "Enabled": true, + "OpenIdConnect": { + "Authority": "https://login.microsoftonline.com//v2.0", + "ClientId": "", + "ClientSecret": "", + "DisplayName": "Microsoft" + } + }, + + ... +} +``` + +`Authority` and `ClientId` are required: without both, the provider is not offered. `DisplayName` (default `OpenID Connect`) labels the sign-in button. Register `https:///signin-oidc` as the redirect URI. The first sign-in creates an account, +whatever `AllowRegistration` says: the provider decides who may sign in. This single block is the provider with id `oidc`. + +#### Several providers + +`Accounts:OpenIdConnectProviders:` lists named providers, each with its own button on the sign-in page. Restart-required (the handlers are registered at startup); an invalid entry stops startup. Edit them on the Settings page (Accounts section, *Sign-in providers*; password-confirmed, the secret never shown back, a blank secret keeps the saved one) or in the configuration: + +```json +"Accounts": { + "Enabled": true, + "OpenIdConnectProviders": { + "entra": { + "DisplayName": "Microsoft", + "Authority": "https://login.microsoftonline.com//v2.0", + "ClientId": "", + "ClientSecret": "", + "Scopes": "groups", + "Parameters": { "domain_hint": "example.com" }, + "AdministratorClaim": "roles", + "AdministratorValue": "baget-admin", + "GroupClaim": "groups", + "GroupMappings": { "": "Developers" } + }, + "google": { + "DisplayName": "Google", + "Authority": "https://accounts.google.com", + "ClientId": "", + "ClientSecret": "" + } + } +} +``` + +The `` is the authentication scheme, the stored login-provider name (`UserLogins.LoginProvider`) and part of the callback path: 1 to 32 lower-case letters, digits and `-` (read without case, kept lower-case; used once). Register `https:///signin-oidc-` as the redirect URI (`/signout-callback-oidc-` after a sign-out). A provider without `Authority` and `ClientId` is not offered. `oidc` is reserved while the single block is configured (startup error); with the block unconfigured a named `oidc` works (callback `/signin-oidc-oidc`). + +| Field | Meaning | +|---|---| +| `Authority`, `ClientId`, `ClientSecret`, `DisplayName` | As the single block (the name defaults to the id) | +| `Scopes` | Extra scopes separated by spaces or `;` (`openid profile email` are always requested) | +| `Parameters` | Extra authorization request parameters (`domain_hint`, `login_hint`...). Never replace what BaGet sets: `prompt` and `max_age` of a re-authentication, `state`, `nonce`, `redirect_uri`, `client_id`, `scope`, `response_type`, `response_mode`, PKCE | +| `UserNameClaim`, `EmailClaim`, `EmailVerifiedClaim` | Claims read for the new account (defaults `preferred_username`, `email`, `email_verified`; the user name falls back to the email's local part). The address is confirmed only when *that provider's* verified claim is `true` | +| `AdministratorClaim` + `AdministratorValue` | Opt-in, together. See below | +| `GroupClaim` + `GroupMappings` | Opt-in. Claim value to BaGet group name; a value holds no `:` | + +Claim names are those of the token (`roles`, `groups`, `email`). The OpenID Connect handler renames some incoming claim types (`role` and `roles` become the .NET role claim type, `group` a URI, `email`, `sub`, `given_name` and `family_name` likewise; `groups` is not renamed): a name is matched as written and as the handler renames it, so `roles` and `role` find the same claim. Claims must be in the ID token. + +**Several providers, several accounts.** The first sign-in through a provider creates its own account; nothing is linked by email. A signed-in user links further providers (and unlinks them) under *Sign-in providers* on the account settings page (password-confirmed; the only way to sign in cannot be unlinked). Re-authenticating (for an account without a password) uses a provider linked to the account, asking which when there are several. + +**Administrator and group mapping.** With `AdministratorClaim`/`AdministratorValue` set, **the provider decides who is an administrator** for the users who sign in through it: at each of their sign-ins the flag is set when the claim holds the value and cleared when it does not (never the last administrator; a promotion also approves a pending account). Grant it only to a provider you trust with administrator rights, and only claims the provider controls. With `GroupMappings`, each sign-in adds the user to the mapped groups whose value is present and removes them from the mapped groups whose value is absent; other groups are untouched and a group name that does not exist is logged and skipped (never created). Users who never sign in through that provider are not affected. Changes go through the usual services (the access model refreshes) and are audited with the actor `provider:` (`account.promote` / `account.demote` in the admin audit, `group.member.add` / `.remove` in the access audit). While the server is read-only the mapping waits for the next sign-in. + +### Verified packages + +An owner can be marked as verified for a package ID, which search reports as `verified`. There is no +page for this yet; it is set through `PackageOwnershipService.SetVerifiedAsync`. + +## Single-page applications + +A frontend written against [`/api/ui`](ui-api.md) can run on its own origin, or be served by BaGet. Restart-required; not on the Settings page. An invalid value stops startup. + +| Setting | Default | Meaning | +| --- | --- | --- | +| `Cors:AllowedOrigins` | empty | Origins (`https://app.example.com`), separated by `;`. **Empty**: the APIs answer any origin *without credentials* (they authenticate with headers a page sets itself), except the endpoints that sign a visitor in or prepare for it (`/api/ui/session*`, `/api/ui/antiforgery`, `/api/ui/account/*`), which are same-origin only, so no other page can script them from visitors' browsers. **A list**: those origins may call `/api/ui` with credentials (the cookie with its antiforgery header, readable answers, the `X-Session-*` headers) and call the session endpoints; nothing else changes: the package protocols, `/api/v1` and the registry keep "any origin, no credentials", so listing an origin gives it no more reach there than any web page has. The cookie sign-in endpoints stay same-origin. The same list says where the external sign-in may return (`returnUrl`) | +| `Frontend:SpaPath` | empty | Folder with a built application (it must contain `index.html`, else startup fails). Relative paths start at the content root | +| `Frontend:SpaBasePath` | `/app` | URL path it is served under: its files, and `index.html` for any other GET below it (client-side routes; a missing file with an extension stays 404). Fallback endpoints have the lowest priority, so `/api`, the protocol routes and the screens are never shadowed; the root, the first segment of any route BaGet maps (derived at startup) and a fixed list (`api`, `v3`, `v2`, `r`, `scalar`, `openapi`, `health`, `_content`, `admin`, `account`, `packages`, `upload`, ...) are refused at startup. Same-origin external-sign-in return addresses must lie under it | +| `Frontend:Mvc` | `true` | `false` serves no server-rendered screen (no `Views`, no `/account/login`, no home page) and the host answers the APIs (and the application) only; emails then link to the application ([routes](ui-api.md#sessions-for-a-single-page-application)) and the cookie's login path is `{SpaBasePath}/sign-in` | +| `Frontend:SpaUrl` | empty | Absolute address of a single-page application hosted **elsewhere** (`https://app.example.com`): account emails link to `{SpaUrl}/confirm-email` and `/reset-password`. Takes precedence over `SpaLinks`. With `Frontend:Mvc=false` and email configured, one of `SpaPath`, `SpaUrl` or `SpaLinks=true` is required, else the host does not start (no email link may point at a 404) | +| `Frontend:SpaLinks` | `true` only with `SpaPath` set when `Mvc=false` | `true` makes emails link to the application's routes (`confirm-email`, `reset-password`, `sign-in` under the base path) even with the screens on, or with no `SpaPath` (an application a reverse proxy serves there); `false` keeps the screens' links | + +## Search sort + +The package list offers *Most downloaded* and *Recently updated* beside relevance (web UI only; the V3 +search API has no sort parameter and is unchanged). The `Database` search provider sorts on the +server. `AzureSearch` and Azure Table do not (the index has no sortable `published` field, and Table +storage cannot order), so the control is hidden there. + +## Validate packages before serving them + +The validation pipeline is **off** by default (`Validation:Enabled` and `RequireSignedPackages` default to `false`); with it off a push is indexed at once. Turn it on with: + +```json +{ + ... + + "Validation": { + "Enabled": true, + "RequireSignedPackages": false + }, + + ... +} +``` + +A push is then answered `202 Accepted`, and the package is checked in the background before it +appears. Until then it cannot be found or downloaded. The checks are: + +* every entry in the package has a safe path; +* a signed package's signature is intact and valid (untrusted roots are allowed); +* with `RequireSignedPackages`, the package is signed; +* any validator you register by implementing `IPackageValidator`, for example a malware scanner. + +A package that fails is quarantined and never served. Its owners can see why with +`GET /v3/package/{id}/{version}/validation`, sending their API key in `X-NuGet-ApiKey`. +Pending validations resume when BaGet Extension restarts. A run that throws (not a failed step) is queued again up to 5 times, after 30 s doubling each time, then stays pending until the next start or an administrator rejects it (a reject stops a validation still running on that node and waits for it, so nothing is published afterwards; the runner also re-checks the submission right before indexing). + +**Symbols:** a `.snupkg` needs the published package, which exists only once validation releases it. Pushed earlier, it answers `404` (with the reason in the body) and is not kept: push it again after the release (`dotnet nuget push` of a `.nupkg` sends the `.snupkg` right behind it, so with validation on push the symbols in a second step). + +Administrators see and decide on stuck submissions of **every repository** at `/admin/validation` +(menu: *Validation queue*): + +| Action | Effect | +|---|---| +| Retry | Resets the steps to pending and queues the submission again (needs the staged file) | +| Release | Indexes the quarantined package although validation failed. Needs the administrator's password; logged as a warning and recorded with `IAdminAudit`; the failed verdicts stay on record | +| Reject | Deletes the staged file and the submission's rows; also for a submission stuck pending. Needs the password; audited | + +Release applies to quarantined submissions only, Reject also to pending ones; all three are refused with `503` while the server is read-only for maintenance. + +### Repository signing + +BaGet Extension can repository-sign every package that passes validation: + +```json +{ + ... + + "Validation": { + "Enabled": true, + "RepositorySigningCertificatePath": "/secrets/repository-signing.pfx", + "RepositorySigningCertificatePassword": "...", + "RepositorySigningServiceIndexUrl": "https://nuget.example.com/v3/index.json" + }, + + ... +} +``` + +The certificate needs the code signing usage. `RepositorySigningServiceIndexUrl` must be your public, +`https` service index URL: NuGet rejects repository signatures for any other scheme. BaGet Extension then +advertises the certificate through the `RepositorySignatures/5.0.0` resource. Signing is on while +`RepositorySigningCertificatePath` is set; if `RepositorySigningServiceIndexUrl` is not an absolute `https` URL, +the package fails the final indexing step and is quarantined. + +## Catalog + +BaGet Extension keeps a [NuGet catalog](https://learn.microsoft.com/nuget/api/catalog-resource), an +append-only log of package changes that mirrors can follow. It needs no configuration. Packages +pushed before the catalog existed are added with: + +``` +dotnet BaGet.dll catalog rebuild +``` + +Each repository has its own catalog; `catalog rebuild --repository ` rebuilds a repository other than `default`. +Administrators can also start it, `import downloads` and (Docker repositories) the [garbage collection](docker-registry.md#garbage-collection) (with a dry run), per repository at `/admin/operations` (menu: *Operations*): +a background job, one run at a time per operation and repository, with its last status (counts or error) kept in +memory until the next start. Starting is refused with `503` while the server is read-only for maintenance. + +The catalog is not available with Azure Table Storage. + +## Legal pages + +`Site:TermsOfUsePath` and `Site:PrivacyPolicyPath` point at Markdown files (absolute, or relative to the +content root). They are served at `/terms` and `/privacy`, and the footer links to each only while its +path is set; BaGet Extension ships no legal text. A page whose path is unset or whose file is missing answers 404. +The path must end in `.md` and contain no `..` segment (the pages are public, so no other file may be served); any +other value is refused when saved on the Settings page and at startup. + +```json +{ "Site": { "TermsOfUsePath": "legal/terms.md", "PrivacyPolicyPath": "legal/privacy.md" } } +``` + +## Private feeds + +A repository can require authentication to read: switch off *Anonymous read* on `/admin/repositories/{name}` (or remove +the *Anyone reads every repository* permission target) and anonymous callers get `401` with a Basic challenge, which +NuGet clients answer with an API key as password. See [Access control](access-control.md) for the model, the upgrade +defaults (nothing changes until you edit them) and the client setup. Needs [accounts](#accounts-package-owners-and-api-keys) +for per-user keys, and a relational database. + +**Upgrading.** A repository whose *Anonymous read* was saved as off before access control existed becomes private on upgrade (the switch did nothing before). The setting is kept, and a startup Warning names every such repository with no Read grant for anyone but administrators, until you switch it on or grant Read. + +## Storage + +`Storage:Type` picks where package and symbol content lives (case-insensitive): + +Shipped default `FileSystem`; the code has none, and a missing or unknown `Type` fails startup. Cloud +providers require their identifying keys (bucket or container, region, credentials) and fail startup without them. + +| `Type` | Keys under `Storage` | Guide | +| --- | --- | --- | +| `FileSystem` (default) | `Path`; empty means the current working directory | [local](installation/local.md) | +| `AzureBlobStorage` | `ConnectionString`, or `AccountName` and `AccessKey`; `Container`; `DownloadUriExpiry` (default 10 minutes) | [Azure](installation/azure.md) | +| `AwsS3` | `Region`, `Bucket`, `Prefix`; `AccessKey` and `SecretKey` (or `UseInstanceProfile`, `AssumeRoleArn`) | [AWS](installation/aws.md) | +| `GoogleCloud` | `BucketName` | [Google Cloud](installation/gcp.md) | +| `AliyunOss` | `AccessKey`, `AccessKeySecret`, `Endpoint`, `Bucket`, `Prefix` | [Alibaba Cloud](installation/aliyun.md) | +| `Null` | none; stores nothing | | + +## Search + +`Search:Type` picks the search index (shipped default `Database`; a missing or unknown value fails startup): + +| `Type` | Notes | +| --- | --- | +| `Database` (default) | searches the package database | +| `AzureSearch` | `AccountName` and `ApiKey` under `Search` | +| `Null` | no search results | ## Database configuration -BaGet supports multiple database engines for storing package information: +BaGet Extension supports multiple database engines for storing package information: - MySQL: `MySql` @@ -97,6 +808,10 @@ BaGet supports multiple database engines for storing package information: - PostgreSQL: `PostgreSql` - Azure Table Storage: `AzureTable` +!!! info + Azure Table Storage only stores packages. Accounts, the catalog, the validation pipeline, + statistics, abuse reports, deprecation and vulnerabilities need one of the relational databases. + Each database engine requires a connection string to configure the connection. Please refer to [ConnectionStrings.com](https://www.connectionstrings.com/) to learn how to create the proper connection string for each database engine. You may configure the chosen database engine either using environment variables or by editing the `appsettings.json` file. @@ -125,15 +840,27 @@ The database settings are located under the `Database` key in the `appsettings.j } ``` -There are two settings related to the database configuration: +There are three settings related to the database configuration: - **Type**: The database engine to use, this should be one of the strings from the above list such as `PostgreSql` or `Sqlite`. -- **ConnectionString**: The connection string for your database engine. +- **ConnectionString**: The connection string for your database engine. Examples: + + | `Type` | Example | + | --- | --- | + | `Sqlite` | `Data Source=baget.db` | + | `SqlServer` | `Server=localhost;Database=BaGet;Trusted_Connection=True;TrustServerCertificate=True` | + | `PostgreSql` | `Host=localhost;Port=5432;Database=baget;Username=baget;Password=` | + | `MySql` | `Server=localhost;Port=3306;Database=baget;User=baget;Password=` | + | `AzureTable` | `DefaultEndpointsProtocol=https;AccountName=;AccountKey=;EndpointSuffix=core.windows.net` | + +- **MySqlServerVersion**: MySQL only, for example `8.0.36`. When empty, BaGet Extension detects the version by connecting to the server; set it to avoid that connection. ## IIS server options IIS Server options can be configured under the `IISServerOptions` key. The available options are detailed at [docs.microsoft.com](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.iisserveroptions) -Note: If not specified, the MaxRequestBodySize in BaGet defaults to 250MB (262144000 bytes), rather than the ASP.NET Core default of 30MB +Note: If not specified, the MaxRequestBodySize in BaGet Extension defaults to 250MB (262144000 bytes), rather than the ASP.NET Core default of 30MB + +A Docker registry (large layers sent in one `PATCH`) also needs `requestLimits maxAllowedContentLength` in `web.config` raised (30 MB default, 4 GB ceiling); see [Streaming storage](formats.md#streaming-storage-b2). ```json { @@ -146,3 +873,220 @@ Note: If not specified, the MaxRequestBodySize in BaGet defaults to 250MB (26214 ... } ``` + +## Logging + +The host logs with [Serilog](https://serilog.net), configured only from the `Serilog` section (levels, sinks, +retention); libraries log through `Microsoft.Extensions.Logging` and need no change. The old `Logging` section is +no longer read. + +| Where | What | +| --- | --- | +| Console | `[HH:mm:ss LVL] SourceContext: message`, Information and up | +| `logs/baget-YYYYMMDD.log` | same events, daily files, 14 kept, rolls at 50 MB (`baget-YYYYMMDD_001.log`) | +| Windows Application event log | Windows only: Warning and up, source `.NET Runtime` (as before, no administrator right needed) | + +- **Reload.** `Serilog:MinimumLevel:Default` and `Override` change **live** when a configuration file reloads + (`appsettings*.json`, `appsettings.Overrides.json`; environment variables and the command line are read once). + Sinks, their arguments, `Enabled` and the `EventLog` keys need a **restart**. +- A relative file `path` resolves against the content root (or `BAGET_CONFIG_ROOT`), not the working directory, for + every `File` sink under `WriteTo` (found by `Name`, keyed by name or by array index). An absolute path is used as is. + In Docker point it into the volume: `Serilog__WriteTo__File__Args__path=/var/baget/logs/baget-.log`. + A file sink that cannot write (an unwritable folder under IIS) is not silent: Serilog's self-log goes to stderr. +- **Levels.** Without any configured level the host applies `Default` Information, `Microsoft` Warning, + `Microsoft.Hosting.Lifetime` Information and `Microsoft.AspNetCore.Hosting.Diagnostics` Warning; the `Serilog` section + then replaces them one by one (a host with its own `appsettings.json` stays safe). `Override` lowers or raises a + namespace (`Microsoft.EntityFrameworkCore`, `System`: `Warning`). Quieter, like the previous default: + `Serilog__MinimumLevel__Default=Warning`. `appsettings.Development.json` uses `Debug`. +- `Microsoft.AspNetCore.Hosting.Diagnostics` at Information logs every full request URL, query string (`?apikey=`) + included. It stays at Warning unless you lower it explicitly: that is your choice, and then keys reach the log. +- Sinks are named under `WriteTo` (`Console`, `File`), so one can be tuned with an environment variable such as + `Serilog__WriteTo__File__Args__retainedFileCountLimit=30`. Other sinks need their package referenced by the host. +- **Disable a sink** on any platform with `Enabled=false`: `Serilog__WriteTo__File__Enabled=false` (or + `Serilog:WriteTo:0:Enabled` for an array entry). An empty `Name` also works but an empty environment variable is + deleted on Windows (and probably in IIS `web.config`), so use `Enabled`. +- **Windows event log.** The Windows event log gets Warning and up, as `WebApplication.CreateBuilder` did before Serilog. + `Serilog:EventLog:Enabled=false` turns it off; `Serilog:EventLog:Source` (default `.NET Runtime`, which exists on every + Windows) must already be registered if changed. +- Request logging: one line per request, `HTTP GET /v3/index.json from responded 200 in 12.3 ms`, after + forwarded headers so the client is the real one. Level: Warning for 5xx or an exception, Debug for static files, + Information otherwise. The line has the path only: no query string, headers or body, so API keys never reach the log; the one credential that rides in a path (npm logout's token segment) is logged as `Redacted`, and masked in traces too. + Quiet only that line: `Serilog__MinimumLevel__Override__Serilog.AspNetCore.RequestLoggingMiddleware=Warning`. +- The Settings page lists `Serilog:MinimumLevel:Default` (live) and `Serilog:EventLog:Enabled` / `Source` (restart). The *Log levels per source* panel under it lists `Override` levels and sets or removes them live (password-confirmed; a level a configuration file or the environment sets can be given another level but not removed there). Sinks and their arguments are arrays of package-specific objects it cannot show: edit the file or the environment. + +## Telemetry + +Off in code (`Telemetry:Enabled` is `false`), but the shipped `appsettings.json` sets `Enabled` to `true` with `Otlp:Endpoint` `http://localhost:4317` (`Grpc`), so a local collector such as Jaeger is used when present; set `Telemetry__Enabled=false` to switch it off. The server emits traces and metrics with `System.Diagnostics` (`ActivitySource` / `Meter` named `BaGet`); +the host exports them over OTLP (OpenTelemetry) only while `Telemetry:Enabled` is true and an endpoint is set. Logs go +out through a Serilog sink. Keys apply **without a restart**, except `ServiceName` and `Metrics:ExportInterval` +(read at startup): + +| Key | Default | Meaning | +|---|---|---| +| `Telemetry:Enabled` | `false` in code, `true` in the shipped file | Master switch. Off: spans are not recorded, nothing is queued, no connection is made | +| `Telemetry:ServiceName` | `baget` | `service.name` of every signal, read once at startup (restart) | +| `Telemetry:Otlp:Endpoint` | empty | Traces collector, absolute http(s) URL, for example `http://jaeger:4317`; empty = no traces | +| `Telemetry:Otlp:Protocol` | `Grpc` | `Grpc` (port 4317) or `HttpProtobuf` (4318; `/v1/traces`, `/v1/metrics`, `/v1/logs` is appended) | +| `Telemetry:Otlp:Headers` | empty | `key=value,...` request headers, for an API key (sensitive: masked on the Settings page, never logged or shown) | +| `Telemetry:Otlp:Timeout` | `00:00:10` | Per-export timeout | +| `Telemetry:Traces:Enabled` / `SamplingRatio` / `Database` | `true` / `1.0` (0 to 1) / `true` | Trace export, share of new traces kept (a trace sampled upstream is kept), database command spans | +| `Telemetry:Metrics:Endpoint` / `ExportInterval` | empty / `00:01:00` | Metrics collector (empty = not exported) and period (restart) | +| `Telemetry:Logs:Endpoint` / `MinimumLevel` | empty / `Information` | Logs collector (empty = not exported) and lowest Serilog level | + +An invalid endpoint (not absolute http or https), protocol, level, a sampling ratio outside 0 to 1 or a non-positive +duration stops the server at startup. + +**Jaeger** accepts traces only (its OTLP receiver answers `Unimplemented` to metrics and logs), so metrics and logs have +their own endpoints, for example an OpenTelemetry Collector. A typical setup: + +``` +Telemetry__Enabled=true +Telemetry__Otlp__Endpoint=http://jaeger:4317 +``` + +A push then shows in Jaeger (UI on 16686) as one trace: the ASP.NET Core request, `package.index`, and the database commands. +See the [Docker example](installation/docker.md#tracing-with-jaeger). + +**Traced:** incoming requests (static files excluded), outgoing HTTP calls (mirror, upstream), database commands +(`Telemetry:Traces:Database`; the SQL text, also under the newer database semantic conventions, is removed from the spans before export), the spans `package.index`, `package.validate`, `mirror.fetch`, +`database.copy` (one `database.copy.table` child per table). **Metrics:** `baget.packages.pushed`, `baget.downloads`, +`baget.validation.results`, plus ASP.NET Core, HTTP client and .NET runtime metrics. + +**Never exported:** query-string values (the instrumentation records `apikey=Redacted`), request headers (such as +`X-NuGet-ApiKey`), SQL text, connection strings; the OTLP `Headers` value. Spans and metrics carry no user names or email addresses. Logs +reach the collector exactly as Serilog would write them, so they **do** include whatever the application logs, such as the +audit lines naming the acting administrator and the affected user (settings changes, administrator promotion, password +resets, account deletion); point `Logs:Endpoint` only at a collector you trust with that. The +`Microsoft.AspNetCore.Hosting.Diagnostics` Warning floor still keeps request URLs out; each log event carries `TraceId` / `SpanId` of the request it was written in. + +**Never blocks, never throws into a request.** Spans wait in a bounded queue (2048) and are dropped when the collector is +down; export runs on a background thread with the `Otlp:Timeout`. Failures are kept in `TelemetryStatus` (per signal: last +attempt, last success, failing since, scrubbed last error without headers or URL paths). `TelemetryConnectionTester` +sends one test span to the settings given, saving nothing. + +**On the Settings page** (a host that does not export telemetry, such as an embedded one, shows a note that these settings have no effect there; they stay editable for a host sharing the file) the Telemetry section starts with a status table, one row per signal: *Off* (telemetry or the +signal is disabled), *Not configured* (no endpoint), *Configured, nothing exported yet*, *Last export ok at ...* or +*Failing since ...* with the scrubbed error (and the spans dropped when the queue was full). **Test connection** sends one +test span (10 s timeout) to the **endpoint, protocol and headers currently typed in the form**, saved or not, and shows +*Connection ok* or the scrubbed error; nothing is saved and telemetry is not switched on. It asks for your password like a +save, is for administrators only, and a blank *Headers* field tests with the saved headers (tick *Clear* to test with none). + +Changing the endpoint, protocol, headers or timeout rebuilds the exporter in place; the old one finishes its running export +first and no queued span is lost. Any configuration reload fires this check, but an exporter whose settings did not change +is kept. + +## Settings page + +Settings changed on the server's Settings page are saved to a JSON file, so `appsettings.json` and its +comments stay untouched. The file is `appsettings.Overrides.json` in the content root (or in +`BAGET_CONFIG_ROOT`); set `SettingsOverridesPath` (also as the environment variable +`SettingsOverridesPath`) to put it elsewhere. + +| Source, lowest to highest precedence | Notes | +| --- | --- | +| `appsettings.json`, `appsettings.{Environment}.json` | shipped defaults | +| **the overrides file** | saved by the Settings page, reloaded when it changes; sits right after the last `appsettings*.json`, so user secrets (Development) outrank it | +| environment variables, command line | an operator's explicit setting still wins; the page marks a saved value that one of these overrides, because the saved value then has no effect | + +- A setting read only at startup (`Accounts`, `Email`, `Database`, `Storage`, `Search`, `Mirror`, + `Site:PublicUrl`, `PathBase`, `AllowedHosts`, `Urls`, `RunMigrationsAtStartup`, `IISServerOptions`, `Ha`, + `Serilog:EventLog`, `Telemetry:ServiceName`, `Telemetry:Metrics:ExportInterval`, and the options of the cloud storage and search providers) is marked + **restart required**; every other setting applies to the next request. The page lists the changes waiting for a restart. +- A secret (API keys, connection strings, passwords, client secrets) is write-only: the page shows it masked, + a blank field keeps the current value, and "Clear" saves an empty one. It is stored in plain text in the + overrides file, as it would be in `appsettings.json`. +- A change is validated before it is written, using the same rules as at startup. A failure that exists without the + change (an unused cloud provider's incomplete options) does not block a save. +- The file is written atomically, so the folder must be writable. In a container, point `SettingsOverridesPath` + into a mounted volume, see [Docker](installation/docker.md). To recover from a bad value, edit or delete the file. +- The page logs which keys changed and who changed them, never the values. + +### Using the Settings page + +- Open **Server settings** in the account menu (needs `Accounts:Enabled`; administrators only, anyone else gets a 404). The left list picks the + section shown (the first, *General*, on load); the others are hidden. The server renders the chosen section: the one that failed to save, else + *Telemetry* after *Test connection*, else `?section=`, else the first. In the browser a click switches without a reload and sets the URL + fragment (`#`, kept on reload and back); links work without JavaScript. A section id is its key (`Database`), `general` for the top-level + settings. The page has one form per + section, each with its own **Save** button (a save returns to `?section=#`); saving asks for your password (an account without one signs in + again with its provider instead). +- Each setting shows its key, its description, and badges: **Restart required**, **Saved override** (tick *Reset to + default* to remove it) and **Overridden by environment variable / command line** (the saved value then has no effect). +- A secret field is blank: leave it empty to keep the value, type to replace it, tick *Clear* to empty it. +- Only changed values are saved. A value that fails to parse or validate is listed above its section and nothing in + that section is saved. Settings of other kinds (maps) are shown read-only. +- `Database:Type`, `Storage:Type` and `Search:Type` are drop-downs of the allowed values (matched ignoring case; a + current value that is empty or not in the list is kept as the selected entry, so saving never changes it). A value + outside the list is refused when saved, and at startup. +- `Database:ConnectionString` shows an example for the selected `Database:Type` as a placeholder (only while no value + is stored) and as an "Example for ..." line; both change when you pick another type. The example is never put in + the field's value. +- A setting no file sets shows the built-in default (for example `Feeds:EnableV2` is ticked) and can be changed from it. +- If the overrides file cannot be written (a read-only content root) or is not valid JSON, the page shows the error, + naming the path, instead of failing; point `SettingsOverridesPath` at a writable file. + +## Read-only maintenance gate + +While a maintenance job (such as a database copy) runs, BaGet Extension makes the database read-only with an +in-memory gate (`MaintenanceGate`). It is not a setting and is never saved: a restart opens it. + +| While the gate is closed | Behaviour | +| --- | --- | +| Any other database write (push, delete, unlist, sign-up, failed sign-in, API keys, owners, abuse reports, Settings page save) | refused with **HTTP 503** and `Retry-After: 60` | +| Reads: feeds, search, downloads, pages | work; a download is served but not counted | +| Pushes (also with `Validation:Enabled`, which stages the file) and catalog entries | refused before any file reaches storage, so a retry after the gate opens is clean | +| Sign-in | a correct password completes: the failed-attempt counter reset (an incidental write) is skipped, so an administrator can sign in after a copy to see the status and restart instructions. A wrong password, sign-up and every other write stay refused (counting a failed attempt is a write) | +| Validation worker | logs a warning, keeps the submission pending and retries every 30 s | +| Pages | show a "Read-only" banner with the reason | + +- A database copy is refused on a node with `Ha:Enabled` (cluster nodes cannot be made read-only together). +- After a job that needs a restart (a successful database copy) the gate is closed **until restart**: writes accepted + before the restart would land in the old database and be lost. +- In a cluster ([High availability](high-availability.md)) a closure made by `Close` (a running copy) is shared by every node + and held by the node that made it; the until-restart closure stays on its own node (restart them all). +- Every write goes through EF `SaveChanges`, which an interceptor checks; a context built with + `MaintenanceGate.AllowWrites(optionsBuilder)` is exempt, so the job holding the gate can write to its own target. + +## High availability + +`Ha:*` runs several nodes behind a load balancer; it is off by default and every key needs a restart. A node refuses to start +with `Ha:Enabled` on SQLite, Azure Table, the file system store or without `Ha:ConnectionString`. See +[High availability](high-availability.md) for the keys, what is shared and the health endpoints. + +| Key | Default | Meaning | +| --- | --- | --- | +| `Ha:Enabled` | `false` | Cluster mode | +| `Ha:Backend` | `Redis` | The only backend | +| `Ha:ConnectionString` | empty | Redis connection string (sensitive) | +| `Ha:NodeName` | machine name + suffix | Name on the Cluster page | +| `Ha:KeyPrefix` | `baget` | Prefix of every Redis key | +| `Ha:KeyCertificatePath` / `Ha:KeyCertificatePassword` | empty | PFX that encrypts the data protection keys kept in the database (same on every node; password sensitive). Unset = keys stored unencrypted, warned at start. See [High availability](high-availability.md) | +| `Ha:LeaseDuration` | `00:00:30` | How long a lease of a stopped node holds (min 3 s) | +| `Ha:SyncInterval` | `00:00:02` | Heartbeat and pick-up interval (min 100 ms) | + +## Moving to another database + +On the Settings page, changing `Database:Type` or `Database:ConnectionString` between two **relational** databases +(SQLite, SQL Server, PostgreSQL, MySQL, in any direction, also the same engine on another server) shows +**Copy all data to the new database** (ticked). With it ticked, Save does not save: it queues a copy, and the settings +are saved only after the copy is verified. Unticked, or with AzureTable on either side (no option shown), Save behaves +as before. + +| Step | Detail | +| --- | --- | +| 1. Read-only | The [gate](#read-only-maintenance-gate) closes when the copy is accepted (pushes etc. get 503). | +| 2. Source | Checked first, before the target is created, migrated or changed. Refused if it has pending migrations or holds what the target cannot, judged per target engine and column: strings longer than the model's maximum length (SQL Server, PostgreSQL, MySQL; SQLite does not enforce lengths), values of a unique index or key (primary or alternate) differing only by case where the target column compares case-insensitively (SQL Server and MySQL by default; any `COLLATE NOCASE` / `citext` / `*_ci` column; not SQLite or PostgreSQL by default), local-time dates (PostgreSQL). All problems are listed at once, before anything is copied. | +| 3. Target | Must be reachable (a new SQLite file or a database the login may create is created) and, after its schema is migrated, **every table empty**. A current target that holds rows is refused and nothing is changed; one that needed migrating and then proves not empty keeps its updated schema, and the refusal says so. | +| 4. Copy | Tables in foreign-key order (Identity's included), 1000 rows per batch, original keys kept; SQL Server `IDENTITY_INSERT` and PostgreSQL sequences are handled, so keys generated later continue after the highest copied one. | +| 5. Verify | Row counts and an order-independent checksum of the keys (engines sort text differently) must match per table. | +| 6. Save | `Database:Type`, `Database:ConnectionString` (and `MySqlServerVersion` if changed) are saved. The gate **stays closed until you restart** BaGet: writes accepted before the restart would land in the old database. | + +- On any failure before step 6 (also a shutdown while the settings are being written, before the file is replaced) the rows copied are deleted from the target (never from the source), the gate reopens, no setting is + saved and the page lists the errors; fix the cause and retry. A crash mid-copy leaves a partly filled target that must + be emptied before a retry (a non-empty target is refused). +- A failure **after** step 6 began (saving the settings) never deletes the target: the verified copy is kept, the gate stays closed until restart and the page reports the error; check the `Database` settings before restarting. +- The source is never modified or deleted: to roll back, restore the old `Database` settings. +- Package files are not copied: they live in `Storage`, which is unchanged. +- One copy at a time; while it runs, every Settings save is refused with 503. Progress shows on the Settings page + (also as JSON at `/admin/settings?handler=CopyStatus`, administrators only). +- Connection strings are never logged or shown in errors. diff --git a/docs/custom-frontend.md b/docs/custom-frontend.md new file mode 100644 index 000000000..abbf3ac38 --- /dev/null +++ b/docs/custom-frontend.md @@ -0,0 +1,166 @@ +# Building a custom frontend (React, Angular) + +Every BaGet screen is a thin MVC view over a JSON endpoint under `/api/ui` that does the work. A single-page application (SPA) can call +the same endpoints and replace the HTML screens, or add to them. Two working samples are in the repository: + +| Sample | Stack | +|---|---| +| [`samples/BaGet.Frontend.React`](https://github.com/pieroviano/BaGet/tree/main/samples/BaGet.Frontend.React) | Vite, React 18, TypeScript, react-router, `openapi-fetch` | +| [`samples/BaGet.Frontend.Angular`](https://github.com/pieroviano/BaGet/tree/main/samples/BaGet.Frontend.Angular) | Angular (standalone components, signals), `HttpClient` with a typed wrapper | + +Reference: [UI API](ui-api.md) (endpoints, who may call, sessions), [configuration](configuration.md#single-page-applications) (settings). + +## 1. Choose how the SPA signs in + +| Mode | Use when | How | +|---|---|---| +| **Session token** (recommended) | The SPA runs on any origin (its own server, a CDN, a dev server) or on BaGet's | `POST /api/ui/session` returns an access token (15 min) and a refresh token (14 days, capped by `Accounts:SessionMaxLifetime`). Send `Authorization: Bearer bgs.…` on every `/api/ui` call | +| **Cookie + antiforgery** | The SPA is served by BaGet itself (same origin) and you prefer an HttpOnly cookie to a token in JavaScript | `GET /api/ui/antiforgery`, then `POST /api/ui/session/cookie` with the `X-XSRF-TOKEN` header; afterwards every `/api/ui` call sends the cookie **and** the header | + +API keys also work on `/api/ui` (scripts, kiosks), but an API key is refused on the account and package-ownership screens: a person must sign in. + +## 2. Configure BaGet + +| Setting | Development (SPA on `http://localhost:5173`) | Production | +|---|---|---| +| `Cors:AllowedOrigins` | `http://localhost:5173` | the SPA's origin, or empty when BaGet serves it | +| `Frontend:SpaPath` | (empty) | folder holding the built `index.html` (BaGet serves it) | +| `Frontend:SpaBasePath` | | `/app` (default); the SPA's routes live below it | +| `Frontend:Mvc` | `true` | `false` to run the SPA alone (the HTML screens are removed) | +| `Frontend:SpaUrl` | `http://localhost:5173` | absolute address of an SPA hosted elsewhere; emails link to it | +| `Frontend:SpaLinks` | | `true` (default when `Mvc=false` and BaGet serves the SPA): emails link to the SPA routes below | +| `Site:PublicUrl` | | the public address; email links and the same-origin check use it | + +With `Frontend:Mvc=false` and email configured, BaGet refuses to start until it knows where the SPA lives (`SpaPath`, `SpaUrl` or `SpaLinks`). + +Notes: +- With `Cors:AllowedOrigins` empty, a page of another origin **cannot** call the session and account endpoints. A separate-origin SPA must be listed. A listed origin gets credentialed access to `/api/ui` only. +- Behind a TLS proxy, configure the trusted proxy (`Proxy:*`) or `Site:PublicUrl`, otherwise the server sees `http` and refuses `https` origins. +- The SPA must implement these routes under `SpaBasePath`, used by emails and redirects: `confirm-email?userId=&code=[&email=]`, `reset-password?userId=&code=`, `sign-in`. + +## 3. Generate a typed client + +The OpenAPI document `ui` describes every endpoint, its body and its `ScreenResult` answer (success and error statuses). + +```bash +# An administrator's API key with the admin:api scope (or the global ApiKey) can read the document. +curl -H "X-NuGet-ApiKey: $KEY" https://baget.example.com/openapi/ui.json -o openapi/ui.json +npx openapi-typescript openapi/ui.json -o src/api/schema.d.ts +``` + +Commit `openapi/ui.json` and the generated `schema.d.ts`; regenerate after upgrading BaGet. In the document, enums are strings +(`"Ok"`, `"SignIn"`), the error statuses `400`/`401`/`403`/`404` carry the same `ScreenResult` schema as `200`, and a screen with an optional +segment has one path per form (`/api/ui/packages/{id}` and `/api/ui/packages/{id}/{version}`). + +## 4. Handle the answer: `ScreenResult` + +Every endpoint answers the same envelope; read the body for **every** HTTP status (errors carry it too): + +| `status` | HTTP | Do | +|---|---|---| +| `Ok` | 200 | render `model` | +| `Invalid` | 400 | show `errors` (key = field name, case-insensitive; `""` = the whole form) next to the form, keep `model` | +| `SignIn` | 401 | go to the sign-in route (after one refresh attempt, see below) | +| `Forbidden` | 403 | show `errors[""]` (e.g. "administrators only", "use the web screen") | +| `NotFound` | 404 | not found, or not visible to this caller | +| `Next` | 200 | navigate to `next.screen` (`{ controller, action }`) with `next.routeValues`; show `next.message` / `next.error` once | + +`next.screen` names an MVC screen; map it to your route with one table, for example +`{ "AdminUsers/Index": "/admin/users", "Package/Index": "/packages/:id/:version?" }`. A read-only answer `503` (problem details, +`Retry-After`) means the server is in maintenance. + +## 5. Session handling + +1. **Sign in**: `POST /api/ui/session { userName, password }`. If the answer has `twoFactorRequired`, ask for the code and post + `{ ticket, code }` to `/session/two-factor` (or `{ ticket, recoveryCode }` to `/session/recovery-code`). +2. **Store**: keep the access token in memory; the refresh token in `sessionStorage` (one tab, gone when it closes) or in memory only + (sign in again after a reload). Never put tokens in `localStorage`, cookies you set yourself, or URLs. +3. **Call**: add `Authorization: Bearer ` to `/api/ui` calls only (never to third-party hosts). +4. **Refresh**: on a `401`, call `POST /session/refresh { refreshToken }` **once** (share one refresh between concurrent calls), store + the new pair, retry the call; if the refresh fails, sign in again. +5. **Renewed tokens**: some account actions (password change, two-factor setup) change the account's security stamp, which ends every + older token. The answer then carries the new pair in `X-Session-Access-Token`, `X-Session-Access-Expires`, + `X-Session-Refresh-Token`, `X-Session-Refresh-Expires`: adopt them. +6. **Sign out**: forget the tokens; `POST /session/sign-out { everywhere: true }` ends every session of the account. +7. **Confirmations**: sensitive actions take the user's password in the body, like the screens' password boxes (the setup key of + two-factor and creating an API key ask it too, in `X-Confirm-Password` or the body). + +**External sign-in (OpenID Connect).** Offer one button per provider of `GET /api/ui/session/providers` (anonymous; `model.providers: [{ id, displayName }]`, empty when none), and navigate the browser to +`/api/ui/session/external/?returnUrl=?state=` after saving `state` in `sessionStorage`. BaGet redirects +back to `?state=…#exchange_token=…`. On that route: + +```ts +const params = new URLSearchParams(location.hash.slice(1)); +history.replaceState(null, '', location.pathname); // remove the token from history and Referer +if (new URLSearchParams(location.search).get('state') !== sessionStorage.getItem('oidc-state')) throw new Error('state mismatch'); +const result = await post('/api/ui/session/exchange', { exchangeToken: params.get('exchange_token') }); +``` + +The exchange token lives 60 seconds and works once; checking `state` stops an attacker from signing a victim in to the attacker's account. + +## 6. React + +```ts +// src/api/client.ts (openapi-fetch) +import createClient, { type Middleware } from 'openapi-fetch'; +import type { paths } from './schema'; + +export const api = createClient({ baseUrl: import.meta.env.VITE_BAGET_URL ?? '' }); + +let refreshing: Promise | null = null; +const auth: Middleware = { + onRequest({ request }) { + if (session.access) request.headers.set('Authorization', `Bearer ${session.access}`); + return request; + }, + async onResponse({ request, response }) { + session.adoptRenewed(response.headers); // X-Session-* headers + if (response.status !== 401 || request.url.includes('/api/ui/session')) return response; + refreshing ??= session.refresh().finally(() => (refreshing = null)); + if (!(await refreshing)) return response; // let the page show the sign-in route + const retry = request.clone(); + retry.headers.set('Authorization', `Bearer ${session.access}`); + return fetch(retry); + }, +}; +api.use(auth); +``` + +Build with `vite build --base /app/` to serve it from BaGet. See the sample for the router table, forms with `errors` and the screens. + +## 7. Angular + +```ts +// src/app/session/session.interceptor.ts +export const sessionInterceptor: HttpInterceptorFn = (req, next) => { + const session = inject(SessionService); + if (!session.isApiCall(req.url)) return next(req); + const send = () => next(session.withBearer(req)).pipe(tap(e => e instanceof HttpResponse && session.adoptRenewed(e.headers))); + return send().pipe( + catchError(err => err.status === 401 && !req.url.includes('/api/ui/session') + ? session.refreshOnce().pipe(switchMap(ok => ok ? send() : throwError(() => err))) // single-flight refresh + : throwError(() => err))); +}; +``` + +Register it with `provideHttpClient(withInterceptors([sessionInterceptor]))`; build with `ng build --base-href /app/`. Treat +`HttpErrorResponse.error` as the `ScreenResult` body. See the sample for the guard, the reactive-form error helper and the screens. + +## 8. Host it + +| Where | Steps | +|---|---| +| Own origin (CDN, static host) | build, deploy, add the origin to `Cors:AllowedOrigins` | +| Served by BaGet, beside the HTML screens | build with base `/app/`, copy the output to the server, set `Frontend:SpaPath` | +| Served by BaGet, instead of the HTML screens | as above, plus `Frontend:Mvc=false` (emails then link to the SPA) | + +BaGet serves the files below `SpaBasePath` and answers `index.html` for unknown routes there (client-side routing); it never shadows +`/api`, the protocols or the screens, and refuses a base path that would. + +## Security checklist + +- Tokens only in memory / `sessionStorage`; the `Authorization` header only to BaGet. +- A strict Content-Security-Policy on the SPA (a token readable by script is only as safe as the page against XSS). +- List exact origins in `Cors:AllowedOrigins`; never a wildcard. +- Check `state` on external sign-in and remove the fragment at once. +- Send passwords for confirmations only when the user types them; never cache them. diff --git a/docs/devops-manual.md b/docs/devops-manual.md new file mode 100644 index 000000000..b0a401a21 --- /dev/null +++ b/docs/devops-manual.md @@ -0,0 +1,105 @@ +# DevOps manual + +Build, release, deploy, run and monitor BaGet Extension. Details are in the linked pages. + +## 1. Build and test + +| Task | Command | +|---|---| +| Build | `dotnet build BaGet.sln -p:GeneratePackageOnBuild=false` | +| Test | `dotnet test BaGet.sln -p:GeneratePackageOnBuild=false` | +| Publish the host | `dotnet publish src/BaGet -c Release -o artifacts -p:GeneratePackageOnBuild=false` | +| Local wrapper | `build.ps1` (clean, restore, build; `-Run`, `-Publish`) | + +- Always pass `-p:GeneratePackageOnBuild=false`: otherwise a build packs into `Packages\`, a shared NuGet feed. +- Create the `Packages` folder on a clean checkout (`mkdir Packages`), or restore fails with `NU1301`. +- Needs the .NET 10 SDK. Tests are xUnit v3 on Microsoft.Testing.Platform. +- Projects `BaGet.Clients.Tests`, `BaGet.Storage.Tests`, `BaGet.Database.Tests`, `BaGet.Telemetry.Tests` and `BaGet.Ha.Tests` use Docker (Testcontainers) and skip without it. + +## 2. CI and release (`.github/workflows`) + +| Workflow | Trigger | Does | +|---|---|---| +| `main.yml` (Build) | push / pull request on `main`, manual | Build and test on Ubuntu | +| `docs.yml` (Docs) | push on `main` | `mkdocs build --strict`, deploys to GitHub Pages | +| `release.yml` (Release) | manual; inputs `releaseVersion`, `packageSource` | `verify` (tests), then in parallel: `BaGet` zip artifact, NuGet packages pushed with `--skip-duplicate`, Docker image to Docker Hub | + +| Secret / variable | Used for | +|---|---| +| `NUGET_API_KEY` | Pushing packages to the package source | +| `DOCKER_USERNAME`, `DOCKER_PASSWORD` | Docker Hub login | +| `DOCKER_IMAGE` (variable) | Image name; default `/baget` | + +Pages must use the "GitHub Actions" source for the docs site. + +## 3. Deploy + +| Target | Page | +|---|---| +| Docker (image from `Dockerfile`: `aspnet:10.0`, port 80, `dotnet BaGet.dll`) | [Docker](installation/docker.md) | +| IIS | [IIS proxy](installation/iis-proxy.md) | +| Azure, AWS, Google Cloud, Alibaba Cloud | [Azure](installation/azure.md), [AWS](installation/aws.md), [Google Cloud](installation/gcp.md), [Aliyun](installation/aliyun.md) | +| Several nodes | [High availability](high-availability.md) | + +Configuration is layered: `appsettings.json`, `appsettings.Overrides.json` (written by the Settings page; path `SettingsOverridesPath`), environment variables (`Section__Key`), command line. Keep `SettingsOverridesPath` and log files on a persistent volume. Full reference: [Configuration](configuration.md). + +## 4. Run + +- Listens on `Kestrel:Endpoints:Http:Url` (`http://localhost:6060` by default; override with `Kestrel__Endpoints__Http__Url`). `--urls` has no effect. +- Pending migrations apply at startup (`RunMigrationsAtStartup`). +- Behind a proxy, TLS ends at the proxy; the path base is honoured and forwarded headers only from trusted proxies (loopback by default; list yours in `Proxy:*`, see [Configuration](configuration.md#reverse-proxies-and-forwarded-headers)). +- The key ring lives in `DataProtection-Keys` beside the overrides file: keep it on the persistent volume. +- Restrict served host names, and refuse private upstream addresses for remote repositories: [Configuration](configuration.md). + +## 5. Monitor + +| Signal | How | +|---|---| +| Liveness | `GET /health/live` (200 while the process answers) | +| Readiness | `GET /health/ready` (200 or 503 by database and storage; Redis only reported); point the load balancer here | +| Logs | Serilog: console, `logs/baget-.log` (daily, 14 kept), Windows event log (Warning+); levels live on the Settings page. No query strings or headers are logged | +| Traces, metrics, logs | OpenTelemetry export to an OTLP endpoint (`Telemetry:*`), live on the Settings page, with a status table and a connection test: [Telemetry](configuration.md#telemetry) | +| Cluster | `/admin/cluster`: nodes, leases, gate, health | +| Background jobs | `/admin/operations`, `/admin/retention`, `/admin/replication` | + +## 6. Operate + +| Task | How | +|---|---| +| Read-only during maintenance | In-memory gate; writes answer `503` + `Retry-After: 60`, reads work: [Configuration](configuration.md#read-only-maintenance-gate) | +| Move to another database | Settings page, "Copy all data": verified copy, gate closed until restart: [Moving to another database](configuration.md#moving-to-another-database) | +| Clean up old versions | [Retention](retention.md), with dry run and holds | +| Mirror to another server | [Replication](replication.md) | +| Scan for vulnerabilities | [Vulnerability scanning](vulnerability-scanning.md) | +| Automate administration | [Administration REST API](admin-api.md) with an `admin:api` key | +| Account recovery | `dotnet BaGet.dll account reset-password `, `account promote|demote|approve ` | + +## 7. Back up and upgrade + +- Back up the database, the package store (file system folder or bucket), `appsettings.Overrides.json` and, in a cluster, the certificate in `Ha:KeyCertificatePath`. +- Upgrade: back up, deploy the new build or image, restart; migrations apply at startup. In a cluster, roll nodes one at a time behind `/health/ready`. +- A database copy is refused while `Ha:Enabled` is on (see [High availability](high-availability.md)). +- **Upgrade note (several OpenID Connect providers).** `Accounts:OpenIdConnectProviders:` adds named providers beside the single `Accounts:OpenIdConnect` block, which keeps working unchanged as provider `oidc` (callback `/signin-oidc`, linked logins untouched, no migration). Register `/signin-oidc-` as the redirect URI at each new provider. `/api/ui/session/external/oidc` became `/api/ui/session/external/{provider}`; `GET /api/ui/session/providers` lists the providers anonymously (the sign-in screen model also gains `externalProviders`) (`hasExternalProvider` / `externalProviderName` stay), the sign-in form posts `provider`, and a re-authentication uses a provider linked to the account. Public constructors and methods keep their old signatures as overloads. A provider with an administrator claim controls the administrator flag of the users who sign in through it ([configuration](configuration.md#several-providers)). +- **Upgrade note (Identity tables renamed).** Migration `RenameAspNetTables` renames `AspNetUsers`, `AspNetRoles`, `AspNetUserRoles`, `AspNetUserClaims`, `AspNetUserLogins`, `AspNetUserTokens` and `AspNetRoleClaims` to `Users`, `Roles`, `UserRoles`, `UserClaims`, `UserLogins`, `UserTokens` and `RoleClaims` (keys, indexes and foreign keys follow). Back up first; external SQL, reports or views that name the old tables must be updated, and during a rolling upgrade of a cluster old nodes cannot run against the renamed tables. On SQLite the foreign keys are rebuilt outside a transaction (EF warns at startup): an interrupted migration needs the backup. +- **Upgrade note (page models removed).** The `[Obsolete]` Razor Page models of `BaGet.Identity` and `BaGet.Web.V3` (`LoginModel`, `UsersModel`, `IndexModel`, `AccountPageModel`, ...), `RepositoryPageFilter` and `RepositoryPageRouteConvention` no longer exist: code of a host that referenced them must move to the controllers, workflows and `RepositoryActionFilter`. The forwarding views at the old `Pages/...` paths (`Pages/Shared/_Layout.cshtml`, `Pages/Admin/_ConfirmPassword.cshtml`, ...) are gone too: a host view must name the partial (``) or use `~/Views/Shared/...`. URLs, forms and `?handler=` values are unchanged (page names stopped resolving later, see the next note). +- **Upgrade note (`/api/ui` controllers renamed; breaking for code that references them).** Every controller named `…UiApiController` is now `…ApiController` (`AccountUiApiController` → `AccountApiController`, `SessionUiApiController` → `SessionApiController`, …), and so are the bases: `UiApiControllerBase` → `ApiControllerBase`, `AccountUiApiControllerBase` → `AccountApiControllerBase`, `AdminUiApiControllerBase` → `AdminApiControllerBase`, `AccessUiApiControllerBase` → `AccessApiControllerBase` (not to be confused with `AdminApiController` / `AccessApiController`, the `/api/v1` bases). Routes, request and response bodies are unchanged; the OpenAPI `ui` document's operation tags follow the names (`AccountUiApi` → `AccountApi`). Recompile code that derives from or names these types; nothing is forwarded. +- **Upgrade note (screens named by controller and action; breaking).** `LegacyPageAttribute` is gone: a screen is identified by its controller and the action that answers a plain GET (`ScreenRef`, listed in `ScreenCatalog`; `ScreenEndpoints` tells screen actions from other endpoints). `Url.Page`, `asp-page` and `RedirectToPage` with a BaGet page name (`/Admin/Users`, `/Package`, ...) no longer resolve: a host that linked to a BaGet screen uses `Url.Action`/`asp-controller` + `asp-action`/`RedirectToAction` (`AdminUsers`/`Index`; `repo` is still added for repository pages) and for a handler `asp-route-handler`. Signatures changed: `ScreenNext.Screen` and `ScreenLink.Screen` are a `ScreenRef`, `IScreenLinks.AbsoluteLink(ScreenRef, values)`, `[UiApi(typeof(XController), nameof(XController.Index))]`, `[ApiOperation(summary, typeof(XController), nameof(XController.Index))]` (`UiPage` became `UiController`/`UiAction`/`UiScreen`), `FormatLink` is built with `FormatLink.ToScreen(id, label, controller, action)` or `FormatLink.ToPath(id, label, path)` (its constructor is private; `Page` is gone), `RepositoryEditViewModel.BrowseScreen`, `AccountControllerBase.AbsoluteLink` (was `PageLink`), `NavLinkTagHelper` reads `asp-controller`/`asp-action`. In the `/api/ui` JSON, `next.screen` is `{ "controller", "action" }` instead of a page name, and the OpenAPI extension `x-baget-ui-page` is `x-baget-ui-screen` (`Controller/Action`). URLs, forms and `?handler=` values are unchanged. +- **Upgrade note (assemblies split, UI API).** The screens' logic moved out of `BaGet.Identity` and `BaGet.Web.V3` into two new packages, `Extension.BaGet.Identity.Application` and `Extension.BaGet.Web.Application` (use cases, DTOs, the account services such as `ApiKeyService` and `PackageOwnershipService`, snippets, `ReadmeMarkdown`); `RequestPrincipalResolver` moved into `BaGet.Identity`. Every public type keeps its name and namespace and the old assembly forwards it (`[TypeForwardedTo]`), so a host that recompiles needs no change; deploy the new assemblies beside the old (`Extension.BaGet` brings them transitively). The internal `*Workflow` classes are gone. Every screen now has a JSON twin under `/api/ui` ([UI API](ui-api.md)) documented at `/scalar`; URLs, forms and `?handler=` values are unchanged and nothing needs configuring. +- **Upgrade note (namespaces follow folders).** In `BaGet.Catalog`, `BaGet.Identity`, `BaGet.Identity.Application`, `BaGet.Validation`, `BaGet.Web.Application` and `BaGet.Web.V3` every type sits in the namespace `RootNamespace + folder` (e.g. `BaGet.Web.V3.Routing.Routes`, `BaGet.Identity.Application.Models.Account.LoginViewModel`), one type per file, nested types made top-level (`PackagesModel.OwnedPackage` is `OwnedPackage`); the `[TypeForwardedTo]` entries of the old namespaces are gone. A host that referenced these types recompiles with new `using` lines; URLs, forms and settings are unchanged. +- **Upgrade note (web APIs split from the screens; breaking).** New packages `Extension.BaGet.Api.Base`, `Extension.BaGet.Identity.FrontEnd` and `Extension.BaGet.Web.FrontEnd`. `BaGet.Identity.Api` and `BaGet.Web.V3` now hold APIs only (`/api/ui` twins, `/api/v1`, protocols) and no longer reference `BaGet.Frontend.Base`; the view controllers (`Controllers/FrontEnd`) and all views moved to the two FrontEnd packages (namespaces unchanged), the layout and shared partials, `NavLinkTagHelper`, `RepositoryUrlHelper(Factory)` and `UiActionMap` to `BaGet.Frontend.Base` (namespaces `BaGet.Frontend.Routing` / `BaGet.Frontend.TagHelpers`), the twin bases, `[UiApi]`, `[RepositoryPage]`, `ScreenEndpoints` and `RequestPrincipalResolver` to `BaGet.Api.Base`. The shared MVC types were renamed from `BaGet.Identity.*` to `BaGet.Frontend.*` in the same release (`BaGet.Identity.Controllers.Base`, `.Mvc.*`, `.Security` become `BaGet.Frontend.Controllers.Base`, `.Mvc.*`, `.Security`); recompile against the new names, nothing is forwarded. A host that serves the web UI must reference `Extension.BaGet.Web.FrontEnd` and call `services.AddBaGetFrontEnd()` after `AddBaGetWebApplication` (it registers the screens as application parts); without the call it serves the APIs only (no screens, no Razor Pages, and a `/api/ui` answer that links to a screen cannot build that link). `[UiApi]` and `[ApiOperation]` take the screen as strings (`[UiApi("AdminUsers", "Index")]`, controller without the `Controller` suffix) instead of `typeof(XController), nameof(XController.Index)`; `UiApiAttribute.Controller` and `ApiOperationAttribute.UiController` are strings. The protocol controllers derive `ControllerBase` instead of `Controller`. `UiControllerBase` implements the new marker `IScreenController`, which `ScreenEndpoints` tests. +- **Upgrade note (`/api/ui` accepts interactive sessions; behaviour change).** For single-page applications `/api/ui` now also accepts a person's interactive session: a **session token** from `POST /api/ui/session` (any origin; `bgs.` tokens, only `/api/ui` accepts them) and, same-origin, the **cookie together with a valid `X-XSRF-TOKEN` header** from `GET /api/ui/antiforgery` (the bare cookie is still ignored; the endpoint exists again). The account self-service and package ownership twins, which answered `403` to everybody over HTTP, now answer an interactive session normally and keep answering `403` to API keys and anonymous callers; the administration twins also admit an administrator's session (non-administrators get `403`); the global `ApiKey` is still refused there. New settings: `Accounts:SessionTokenLifetime`, `Accounts:SessionRefreshLifetime`, `Accounts:SessionMaxLifetime`, `Cors:AllowedOrigins` (an explicit list gives those origins credentialed access to `/api/ui` only; with no list the sign-in endpoints of `/api/ui` (`session*`, `antiforgery`, `account/*`) are same-origin only, so a separate-origin SPA must list its origin), `Frontend:SpaPath`, `Frontend:SpaBasePath`, `Frontend:Mvc`, `Frontend:SpaLinks`, `Frontend:SpaUrl` ([configuration](configuration.md#single-page-applications)). A host that calls `AddBaGetAccounts` gets the antiforgery header name `X-XSRF-TOKEN` configured (the HTML forms are unaffected). Changing a password or two-factor settings ends the account's other token sessions. A host that serves the screens itself and wants none of this changes nothing. +- **Upgrade note (`/api/ui` is keys only; superseded by the note above).** `/api/ui` no longer accepts the browser cookie or HTTP Basic (use `Authorization: Bearer ` or `X-NuGet-ApiKey`, as for `/api/v1`); `GET /api/ui/antiforgery` and the antiforgery requirement are gone; account self-service and package ownership twins answer `403` over HTTP (use the web screens); the global `ApiKey` is refused on the administration twins (use an administrator's `admin:api` key). The web screens are unchanged. +- **Upgrade note (forwarded headers, key ring, form limit, exit codes; read before upgrading behind a proxy or in a container).** + - **Forwarded headers are trusted from loopback only.** `X-Forwarded-For`/`-Proto` used to be believed from any sender. A proxy that is not on the same machine must now be listed in `Proxy:TrustedProxies` / `Proxy:TrustedNetworks` (for example the Docker bridge network `172.17.0.0/16`, or your ingress or load balancer addresses); otherwise the client address is the proxy's and an `https` front end is seen as `http` (advertised URLs, `Secure` cookies). `Proxy:TrustAnyProxy=true` restores the old behaviour; use it only when clients cannot reach BaGet except through the proxy. See [Configuration](configuration.md#reverse-proxies-and-forwarded-headers). + - **The key ring is persisted by every single node**, in `DataProtection-Keys` beside the overrides file (`DataProtection:KeyPath`). Keys kept so far in the user profile (`~/.aspnet/DataProtection-Keys`, `%LOCALAPPDATA%\ASP.NET\DataProtection-Keys`) are not read: after the upgrade stored remote-repository passwords and replication peer keys that were protected with them cannot be decrypted (re-enter them), and everyone is signed out once. To keep them, copy that folder to the new `KeyPath` before the first start. Put the folder on the persistent volume and make it writable (startup stops otherwise); on Windows the keys are DPAPI-encrypted, elsewhere plain XML, so restrict the folder's permissions. See [Data protection keys](configuration.md#data-protection-keys). + - **Forms accept 1 MiB** (multipart); the push and upload endpoints keep the old ceiling. + - **`baget` returns an exit code**: `1` for an invalid configuration or a refused command (it was always `0` for the first). +- **Upgrade note (ownership foreign keys).** The migration `AddOwnershipForeignKeys` adds foreign keys from repository, project, user and replication-configuration references to their rows. Before it does, it **deletes the rows that already pointed at nothing** (for example packages or API keys of a repository or user that no longer exists, and everything under them) and clears references to missing projects; such rows were invisible to the application. Back up first if you want to inspect them. From then on the database refuses an orphan, and deleting a repository, project or user is done by the application, which removes the dependents first. + - **Rolling upgrade (cluster):** until every node runs the new build, do not delete an image, a project or a repository: the old code relies on cascades and cleanup the foreign keys now forbid (the delete fails with a constraint error, nothing is lost). + - **Large databases:** the cleanup and the foreign-key validation scan whole tables. Migrations run with the provider's command timeout (30 s by default on SQL Server, PostgreSQL and MySQL); raise it in the connection string (`Command Timeout=600` for SQL Server and PostgreSQL, `Default Command Timeout=600` for MySQL) for the upgrade start, or apply the migrations with `dotnet ef database update` from a shell with such a connection string. + - **MySQL DDL is not transactional:** if the migration fails half way, the foreign keys already added stay. Fix the cause, then drop the `FK_*_Repositories_RepositoryKey`, `FK_*_Projects_ProjectKey`, `FK_*_AspNetUsers_UserId`, `FK_ReplicationRuns_*`, `FK_ReplicationItems_*` and `FK_OciTags_OciRepositories_ImageKey` constraints that exist and start BaGet again (or restore the backup); the cleanup is repeatable. SQL Server, PostgreSQL and SQLite roll the whole migration back. + - A database whose `default` repository row is missing (migrated by an early build of `AddRepositories` and never started) gets the row created first; rows of repository 1 are never treated as orphans. + +## 8. High availability checklist + +Shared SQL Server, PostgreSQL or MySQL; shared object storage (not the file system); Redis; `Ha:Enabled=true` with `Ha:ConnectionString`; the same `Ha:KeyPrefix` on every node; `Ha:KeyCertificatePath` set so data protection keys are encrypted. A node that breaks a rule does not start ([High availability](high-availability.md)). diff --git a/docs/docker-registry.md b/docs/docker-registry.md new file mode 100644 index 000000000..4f8e499e9 --- /dev/null +++ b/docs/docker-registry.md @@ -0,0 +1,172 @@ +# Docker registry + +A local **Docker** repository is an OCI registry (Distribution Spec v1.1): `docker login`, `push`, `pull`, multi-platform indexes, +referrers (signatures, SBOMs), tag listing, deletes. A **remote** Docker repository caches Docker Hub (or any registry), a **virtual** one merges repositories; see [Remote Docker repositories](#remote-docker-repositories) and [Virtual Docker repositories](#virtual-docker-repositories). Blobs nothing uses are removed by the [garbage collection](#garbage-collection). + +## Create and use + +| Step | How | +|---|---| +| Create | Administrators: `/admin/repositories` > *Docker* form (name, *Anonymous read*). Needs a store that streams: `Storage:Type` FileSystem, AwsS3, AzureBlobStorage, GoogleCloud or AliyunOss ([streaming storage](formats.md#streaming-storage-b2)); refused otherwise, and on Azure Table / Azure Search (default repository only) | +| Image name | `{host}/{repository}/{image}[:{tag}]`: the BaGet repository is the **first path segment**, the rest is the image (`team/app`, any depth). `docker push localhost:6060/libs/team/app:1.0` pushes image `team/app` into repository `libs`. The registry is at the server root (`/v2/`), not under `/r/{name}/` | +| Login | `docker login host` with your user name and an **API key** as the password (create one on *API keys*). The API key never leaves the login: the registry hands Docker a short-lived token | +| Plain http | Docker only talks http to `localhost` and to registries listed in `daemon.json` `insecure-registries`; the browse page shows the entry for this host | +| Push / pull | `docker tag` + `docker push`, `docker pull`, `docker buildx build --platform linux/amd64,linux/arm64 --push` (snippets on the browse page) | + +## Access + +pull = Read, push = Deploy, delete = Delete on the image: + +| Action | Needs | Notes | +|---|---|---| +| `pull` | **Read** on the repository and the image | anonymous pulls work where *Anonymous read* is on (Docker takes an anonymous token) | +| `push` | **Deploy** | `docker push` also checks which layers exist, so the user needs Read too | +| `delete` | **Delete** | manifests, tags, blobs | + +The access model sees the image name (`team/app`) as the package id, so include/exclude patterns (`team/*`) work. A key still needs its +own scope: `package:push` or `package:pushversion` to push, `package:unlist` to delete; its package glob must match the image. There is no +ownership: whoever holds the action may use it. Deploy is never granted on a remote or virtual repository. + +### Token flow (`docker login`) + +| Request | Answer | +|---|---| +| `GET /v2/` | `200 {}` for a caller the registry knows (token or API key); `401` + `WWW-Authenticate: Bearer realm="https://host/v2/token",service="BaGet"` for an anonymous one. Every response carries `Docker-Distribution-API-Version: registry/2.0` | +| `GET /v2/token?service=BaGet&scope=repository:{repo}/{image}:pull,push` | `{"token","access_token","expires_in","issued_at"}`. Basic credentials are optional: an API key as the password (a user name is checked against the key's owner); wrong ones are `401`. The token grants, per requested image of an existing Docker repository, the requested actions **the caller holds** (possibly none) | +| a registry route without a covering token | `401` + `Bearer … scope="repository:{repo}/{image}:pull,push"`, plus `error="insufficient_scope"` (a token that does not cover it) or `error="invalid_token"` (expired, tampered with). The same answer for a repository that does not exist and one the caller may not see | +| a registry route with an API key (Basic or Bearer) | judged directly, without a token (scripts, `curl`, the conformance suite). A key that may not read is `404`; one that may read but lacks the action is `403` | + +Tokens are signed and encrypted with ASP.NET Core data protection, hold only the user name (for the log), the image scopes and the expiry, +never an API key, and last `Oci:TokenLifetime` (5 minutes). A revoked permission applies when the tokens issued before it expire. + +## Protocol + +| Request | Answer | +|---|---| +| `HEAD`/`GET /v2/{repo}/{image}/blobs/{digest}` | the blob, `Docker-Content-Digest`, `Accept-Ranges`; `Range` (`206`, `416`). Served only through an image that holds it | +| `POST …/blobs/uploads/` | `202` + `Location` (upload session), `Docker-Upload-UUID`, `Range: 0-0` | +| `POST …/blobs/uploads/?digest=` | monolithic upload (`201`) | +| `POST …/blobs/uploads/?mount={digest}&from={repo}/{image}` | `201` when the source image of the same repository holds the blob and the caller may pull it (through a virtual repository: in its deploy repository, so a registry token needs the pull grant for that repository, not only for the virtual name); otherwise a normal `202` session | +| `PATCH …/blobs/uploads/{ref}` | append a chunk (`202`); `Content-Range` start must equal the upload length, else `416` with the real `Range` | +| `PUT …/blobs/uploads/{ref}?digest=` | optional last chunk, SHA-256 verified while streaming, `201`. A wrong digest is `400 DIGEST_INVALID` and ends the session | +| `GET`/`DELETE …/blobs/uploads/{ref}` | `204` with the current `Range`; `204` cancel | +| `PUT …/manifests/{tag or digest}` | `201`; the `Content-Type` must be an OCI or Docker v2 manifest/index type; every config, layer or child manifest must already be in the image (`400 MANIFEST_BLOB_UNKNOWN`), except foreign (non-distributable) layers, i.e. a `foreign`/`nondistributable` media type with `urls`, which are neither required nor stored nor counted; the digest in the URL must match; max `Oci:MaxManifestBytes` (4 MiB, `413`); `OCI-Subject` header when there is a subject | +| `HEAD`/`GET …/manifests/{tag or digest}` | the bytes exactly as pushed, `Docker-Content-Digest` | +| `DELETE …/manifests/{digest}` | removes the manifest and its tags (`202`); `…/manifests/{tag}` removes the tag only | +| `DELETE …/blobs/{digest}` | removes the blob from the image (`202`); `405 UNSUPPORTED` while a manifest of the image uses it | +| `GET …/tags/list?n=&last=` | sorted tags, `Link: rel="next"` when `n` leaves more | +| `GET …/referrers/{digest}?artifactType=` | an OCI index of the manifests whose `subject` is the digest; `OCI-Filters-Applied` | + +Errors are the specification's JSON (`{"errors":[{"code","message","detail"}]}`). A path that is not a registry endpoint is `404`, an +undefined method `405`, an invalid name `400 NAME_INVALID`. Repository names match case-insensitively; image names and digests are lower case, +tags are case-sensitive. Only `sha256` digests are stored. Writes are `403` in read-only mode and `503` while a database copy has the maintenance gate closed. + +## Remote Docker repositories + +A Docker repository of kind remote is a **pull-through cache** of an upstream registry (Docker Hub `https://registry-1.docker.io`, GHCR `https://ghcr.io`, Quay, Harbor, Artifactory, another BaGet, a `registry:2`). Create it on `/admin/repositories` > *New remote repository* (format Docker): upstream address, optional credentials, the cache settings of [remote repositories](remote-repositories.md). `docker pull host/hub/library/nginx:1.27` (BaGet repository `hub`) is answered from the cache, fetched from the upstream on a miss. + +| Part | Behaviour | +|---|---| +| Names | The image is the name after the repository, as for a local one (`hub/team/app` is `team/app` upstream). At **Docker Hub** (`registry-1.docker.io`, `index.docker.io`, `docker.io`) a name without a slash is an official image and is asked for as `library/{name}`: `docker pull host/hub/nginx` fetches `library/nginx` | +| Authentication | As `docker login` does: the first request goes without credentials; a `401` with `WWW-Authenticate: Bearer realm="…",service="…",scope="…"` sends BaGet to that **realm** (Docker Hub: `auth.docker.io`) for a token, with the configured user name and password as Basic (anonymously when none: Docker Hub hands out anonymous pull tokens, with its rate limit). The token is kept per scope until it expires and sent as the bearer credential. A registry that asks for `Basic` itself gets the pair at its own host; a password with **no user name** is sent as a ready-made bearer token to the registry. Credentials go to the registry's origin and to the realm only: a **redirect** (Docker Hub sends layers to a CDN) is followed without any credential, never from https to http. A realm on http under an https registry is refused | +| Manifests | A tag is asked of the upstream and cached for the **metadata period**; a digest never changes, so a stored one is never asked again. After the period an unchanged tag is verified with a `HEAD` (which Docker Hub does not count as a pull) and the manifest is not downloaded again. The document must be a supported manifest or index whose digest matches the one asked for (and `Docker-Content-Digest`); with *Store locally* it is kept with its tag (a moved tag moves here, the old manifest stays by digest) | +| Layers | A layer an image holds is served from storage. Otherwise it is **streamed from the upstream while it is written to storage** (a pull is not kept waiting for a multi-gigabyte layer) and kept once its SHA-256 matches the digest: a layer that does not is not kept and the download ends in error. A layer another image of the repository already stores is linked to the image once the upstream confirms (`HEAD`) that the image has it, so a base layer is stored and downloaded once. Range requests, a layer already being downloaded by another request and a read-only server pass through unkept. Concurrency and storage failures never fail a pull | +| Tags | `tags/list` is the upstream's tags (all pages) plus the stored ones, paged here (`n`, `last`) | +| Not found / down | A `404` (or a `401`/`403` after the token service gave a token: Docker Hub answers a missing or private image so) is `404` and is remembered for the **negative period**. A registry that cannot be reached, refuses the credentials at its token service or sends something unusable is `502` (`UNAVAILABLE`), never remembered as "not found"; what was cached before is still served | +| Offline | The upstream is never contacted: stored manifests and layers only | +| Pushes and deletes | `403 DENIED` for anyone who may pull (`docker push` fails with *denied*); the token service never grants `push`/`delete` on a remote repository | +| Referrers, pages, search | Cover what is stored | + +*Test connection* does what a client does: `GET /v2/` anonymously, then through the token service with the typed credentials, so a wrong password shows there (it saves nothing and uses a client of its own). *Purge cache* deletes every cached image; *Purge package* takes an image name and optionally one tag or digest. The cache table shows the cached manifests, images and the bytes of their layers. Layers no cached manifest uses are removed by the [garbage collection](#garbage-collection). Docker Hub's anonymous rate limit applies to what BaGet pulls (`GET` of manifests), not to cache hits. + +## Virtual Docker repositories + +A virtual Docker repository presents several Docker repositories (local or remote, of the same format; another virtual one is flattened in place) as one registry, in the order of its members. Create it on `/admin/repositories` > *New virtual repository* (format Docker), then add members, order them and choose the **deploy repository** (a local member) on `/admin/repositories/{name}`; *Where would an image come from?* takes an image name and a tag or digest and asks each member (*stored here*, *not stored yet; its upstream has it*, *not found*, ...) without fetching or storing anything. Clients use it like any repository: `docker pull host/{virtual}/{image}`. + +| Request | Result | +|---|---| +| Manifest by tag or digest | The first member, in order, that has it; a remote member fetches and keeps it. A tag in several members is the first member's | +| Layer, `HEAD` of a layer | The first member that holds it (a remote member in front streams it from its upstream and keeps it; one whose upstream lacks it passes) | +| Tag list | The union of the members' tags, paged here | +| Referrers, browse page, search | Merged across the members (the first member's entry wins an image) | +| Push, upload session, mount, manifest `PUT`, delete | **Moved to the deploy repository** before authorization: the caller needs the action *there*, and the upload URLs the registry hands out stay in the virtual repository. Without a deploy repository: `403 DENIED` | + +Only the members the caller may pull the image from are asked (a member the caller cannot read is skipped, never revealed), each in its own scope so its storage, upstream and rules apply as when it is read directly; a member that fails (its upstream is down) is logged and skipped, so the next one answers. **Tokens:** `/v2/token` for a scope on a virtual repository grants `pull` on it, `push`/`delete` as the deploy repository grants them, and `pull` on each member the caller may pull the image from (the token names them, a registry token having no user to ask later). A manage page is not offered (404): use the member's. + +## Garbage collection + +*Remove unused layers* (Manage) works on one image. The **garbage collection** works on a whole Docker repository, local or remote, and is what keeps a registry from filling up with blobs nobody can reach. Start it on `/admin/operations` (administrators): **Docker garbage collection: dry run** reports and removes nothing, **Docker garbage collection** removes; both are background jobs like the other operations (one run at a time per repository, status kept in memory, audited, refused with `503` while the server is read-only, except the dry run). Before deleting, a run re-checks its plan against the current rows in a serializable transaction: a layer a manifest started using (or a blob another image linked) while the run was going is kept, and the report counts only what was removed. A [retention policy](retention.md) can run it on a schedule after deleting old tags and untagged manifests (*Collect garbage*); the service is `IOciGarbageCollector`. + +What it marks, in this order: + +| Mark | Meaning | Removed | +|---|---|---| +| Expired upload sessions | idle longer than `Oci:UploadExpiry` | the session row and what it received in storage | +| Unreferenced layers | an image holds a layer none of its manifests uses and it is older than `Oci:PruneGrace`, **unless the image has an upload session still open** (a push sends its layers first and the manifest last, however long they take) | the image's link to the layer | +| Blobs nobody holds | no image holds the blob once those links are gone (reference count 0), or a blob row nobody ever linked, older than `Oci:PruneGrace` | the blob row and its file | +| Orphan files | a file under the repository's `docker/blobs/` that no blob row names (a push that died between storing the file and recording it); only where the store can list files; skipped (the report says so) when a blob of this process was being stored during the listing, and rows are re-read after it, so a push finishing during the run is safe. **Nodes sharing one store are not coordinated**: run it while no other node is receiving pushes | the file | + +The report (shown on the Operations page after the run) says how many of each, the bytes freed and the first items; a layer two images hold is removed only when no image holds it, and a manifest, its config and its layers are never touched. A dry run reports exactly what the real run would remove at that moment. A virtual repository has no blobs of its own (the operation is not offered for it); the repository's other formats are not affected. + +## Pages + +| Page | Address (under `/r/{name}/`) | Who | +|---|---|---| +| Browse | `/docker-images?q=` | whoever may read the repository; lists only images the visitor may read; login, pull, push, buildx and daemon snippets | +| Image | `/docker-images/{image}` | readers of the image: tags, manifests (type, platform, layers, size). `?digest=` shows one manifest: config and layers with sizes, an index's platforms with links to each manifest, annotations, the referrers (signatures, SBOMs; `&artifactType=` narrows them like the API filter), the document | +| Manage | `/docker-manage/{image}` | signed-in users with **Delete** on the image: delete a tag, a manifest (with its tags), remove unused layers (older than `Oci:PruneGrace`; like the garbage collector, not while the image has an open upload session), delete the whole image; each asks the password | + +Docker pages are 404 in other formats' repositories and theirs are 404 in a Docker one. In a remote repository the browse and image pages list the cached images, show only the pull commands, and *Manage* is 404. There is no upload page: images are pushed with the CLI (and the NuGet upload page does not offer Docker repositories). + +## Storage and data + +Blobs are stored once per repository, by digest: `docker/blobs/sha256/{ab}/{digest}` under the repository's prefix, shared by every image of the +repository. Manifests are rows (their bytes are the digest). Tables, migration `AddOciTables` on all four providers: + +| Table | Holds | +|---|---| +| `OciRepositories` (repository-scoped) | the images (`team/app`), unique per repository | +| `OciManifests` | digest, media type, artifact type, subject digest, size, the JSON as pushed; unique per image | +| `OciTags` | tag (case-sensitive) to manifest, unique per image; deleted with the manifest | +| `OciBlobs` (repository-scoped) | digest, size, `RefCount` (images holding it); the file goes when it reaches 0 | +| `OciBlobLinks` | which image holds which blob, and how many of its manifests use it | +| `OciUploads` | open upload sessions (reference, storage upload id); idle ones expire after `Oci:UploadExpiry` when the next upload starts | + +A blob is served under an image only through its link, so restricting `team/secret` cannot be bypassed by asking another image for its digest. +Deleting a repository needs it empty of images (a remote one: purge its cache first). + +## Configuration + +| Setting | Default | Meaning | +|---|---|---| +| `Oci:TokenLifetime` | `00:05:00` | validity of a token from `/v2/token` (at least 10 s). Live | +| `Oci:Service` | `BaGet` | the `service` of the challenge, checked at the token endpoint. Live | +| `Oci:MaxManifestBytes` | `4194304` | largest manifest or index. Live | +| `Oci:UploadExpiry` | `1.00:00:00` | idle time after which an upload session is discarded (when the next upload starts, and by the garbage collection). Live | +| `Oci:PruneGrace` | `01:00:00` | a layer no manifest uses is kept this long before *Remove unused layers* or the garbage collection may remove it. Live | + +Kestrel has no request body limit; behind IIS a single `PATCH` is capped (`IISServerOptions.MaxRequestBodySize`, `maxAllowedContentLength`): Docker +pushes a layer in one `PATCH`, so raise both ([streaming storage](formats.md#streaming-storage-b2)). Reverse proxies need `client_max_body_size 0` and +must pass `Authorization` and the `Host` header (the token URL is built from it). + +## Tests + +`OciNamesTests` (Core: names, paths, scopes, manifest reader), `OciUpstreamTests` (Core: remote settings, token challenge, Docker Hub names), +`OciRegistryTests` (HTTP protocol, token flow, access), `DockerPagesTests`, `RemoteOciRepositoryTests` (an in-memory registry with the token flow, a CDN +redirect, private images, corrupt layers and a registry that is down), `VirtualOciRepositoryTests`, `OciGarbageCollectorTests`, +`AdminDockerRemoteVirtualTests` (`BaGet.Tests`), and `DockerRemoteVirtualCliTests` and `DockerCliTests` (`BaGet.Clients.Tests`). +`DockerRemoteVirtualCliTests` pulls through remote repositories whose upstream is a second real BaGet (a private repository that wants the +`docker login` token flow with an API key, and a public one) and the reference `registry:2` image (started by Testcontainers; the test skips +when it cannot be), and through a virtual repository that pushes to its deploy repository; the daemon is told the registries are insecure. +`DockerCliTests`: the real Docker 27 in a privileged `docker:27-dind` logs in, pushes and pulls +multi-layer and 96 MB images, a multi-platform index, public and private repositories, and the `opencontainers/distribution-spec` v1.1.0 +conformance suite (push, pull, content discovery, content management) runs against the same server. They skip without a Docker daemon that +allows privileged containers; the images are built `FROM scratch`, so they need no internet (the conformance image comes from `ghcr.io`). + +## Vulnerability scanning + +Images are scanned by Trivy when `Scanning:TrivyPath` and `Scanning:TrivyRegistryHost` are set; without them images are marked +unscanned in the UI and nothing is blocked. A policy can refuse a manifest pull (`403 DENIED`, tag or digest; layers are +content-addressed and stay fetchable by digest), and a push that reaches the *block deploy* threshold is scanned right after the +push and removed again (`403 DENIED`; a tag the push created or moved, also onto a manifest the image already held, goes back to where it pointed). Trivy's own pull is never refused by *block download* / *block unscanned* (the caller named by `Scanning:TrivyRegistryUser`, or, with no user configured, any pull of the image while its scan runs). See [vulnerability scanning](vulnerability-scanning.md). Tests: `ScanningDockerTests` (a fake +Trivy), `TrivyRunnerTests` (a script standing in for the executable). diff --git a/docs/formats.md b/docs/formats.md new file mode 100644 index 000000000..1dd6c7314 --- /dev/null +++ b/docs/formats.md @@ -0,0 +1,137 @@ +# Package formats + +A repository has a **format**. NuGet, npm (see [npm registry](npm-registry.md)), Maven (local, remote and virtual repositories, see [Maven repositories](maven-repositories.md)) and Docker (local, remote and virtual repositories, see [Docker registry](docker-registry.md)) have a protocol today. `/admin/formats` (administrators) lists what this server can host. + +| Format | Served under | Feed address | Repository kinds | Storage folders | Status | +|---|---|---|---|---|---| +| NuGet | the repository base (`/v3/…`, `/api/v2`, symbols) | `v3/index.json` | local, remote, virtual | `packages` `symbols` `catalog` `validation` `staging` | done | +| npm | `npm/` | `npm/` | local, remote, virtual | `npm` | done ([details](npm-registry.md)) | +| Maven | `maven/` | `maven/` | local, remote, virtual | `maven` | done ([details](maven-repositories.md)) | +| Docker | `/v2/{repo}/{image}/…` (server root) | `v2/{repo}/` | local, remote, virtual | `docker` | done ([details](docker-registry.md)) | + +The *repository base* is `/` for `default` and `/r/{name}/` for the others, so an npm repository `web` is at `/r/web/npm/`. A +route belongs to one format: asking a NuGet route of an npm repository (or an npm route of `default`, which is NuGet) is `404`. +**Docker is the exception** (D2): the OCI Distribution Spec fixes the registry at `/v2/`, so a Docker repository is addressed as `/v2/{repo}/…` +(the BaGet repository is the first path segment of the image name) and its routes carry `RepositoryRouteMetadata.ResolvesRepositoryItself`: the +registry's own filter picks and authorizes the repository, answering in the registry's error format. A `FeedPath` containing `{repo}` is +relative to the server root instead of the repository base. + +## Module contract (`IFormatModule`, `BaGet.Core/Formats`) + +A module only **describes** its format. Register it with `TryAddEnumerable(ServiceDescriptor.Singleton())`; +`FormatRegistry` refuses two modules for one format, a shared route prefix, a shared storage folder, or a claim on `repos`. + +| Member | Used for | +|---|---| +| `Format`, `DisplayName` | identity | +| `RoutePrefix`, `FeedPath` | where its routes start; the address clients are given (admin pages) | +| `CreatableKinds` | what `IRepositoryService.CreateAsync` accepts (every shipped format: local, remote) | +| `SupportsVirtual` | whether virtual repositories of the format exist (`IVirtualRepositoryAdministration.CreateAsync(..., format)`, created with their members; the format's reads must merge and its writes move to the deploy repository) | +| `StorageFolders` | folders it owns below `RepositoryStorage.Prefix` | +| `CreateFields`, `CreateSettings` | extra inputs of the create form; turned into `Repository.Settings` (`ArgumentException` = message shown) | +| `RepositoryLinks` | links on the Repositories page (NuGet: Browse, Upload, V2 feed, Vulnerabilities, and Catalog/Signatures where offered; npm: Browse, Upload, Registry; Maven: Browse, Upload, Repository; Docker: Browse) | +| `CountArtifactsAsync`, `GetUsageAsync`, `StagePurgeAsync` | package counts; what blocks deleting a repository; rows removed with it | + +What a format does per request is a scoped service beside the module, found with `provider.GetFormatService(format)` +(null = not offered): + +| Service | Phase | NuGet | +|---|---|---| +| `IFormatIndexer` (deploy) | npm P3 | `NuGetFormatIndexer` over `IPackageIndexingService`; npm has none (publishing needs the caller, so it is `INpmRegistry.PublishAsync`) | +| `IFormatSearchProvider` | npm P3 | `NuGetFormatSearchProvider` over `ISearchService`; `NpmFormatSearchProvider` over `INpmRegistry.SearchAsync` | +| `IFormatRetentionHooks` | P6 | `NuGetRetentionHooks`; npm, Maven and Docker have theirs (`NpmRetentionHooks`, `MavenRetentionHooks`, `DockerRetentionHooks`); used by the [retention engine](retention.md) | +| `IFormatScanner` | P7 | `NuGetFormatScanner` (package and dependency ranges), `NpmFormatScanner`, `MavenFormatScanner` (POM), `DockerFormatScanner` (image manifests, `ScanEngine.Image`): see [vulnerability scanning](vulnerability-scanning.md) | + +Routes go through `BaGetEndpointBuilder.MapRoute(..., format: module.Format)` with a pattern starting `"{RoutePrefix}/…"`; it +registers the default and `r/{repo}/` variants and tags the endpoint (`RepositoryRouteMetadata.Format`). Unmarked endpoints are +NuGet's. **Repository pages** (controller actions marked `[RepositoryPage]`) are served under `/r/{repo}/` for every repository and decide per page: `[RepositoryPage(Format = …)]` +names the format of a page (NuGet unless set; the npm pages `/NpmPackages`, `/NpmPackage`, `/NpmUpload`, `/Packages/NpmManage`, the Maven pages `/MavenArtifacts`, `/MavenArtifact`, `/MavenUpload`, `/Packages/MavenManage`, the Docker pages `/DockerImages`, `/DockerImage`, `/Packages/DockerManage`; `/Packages/Scan` serves every format via `AnyFormat = true`), +and `RepositoryActionFilter` answers 404 for a page of another format, except that the NuGet front page of a repository of another format +redirects to the module's `browse` link. The upload picker, header switcher, My packages, API-key repository +limits and the access-model listings now cover every format (the `Format == NuGet` filters are gone). A virtual repository +is of one format and so are its members; a remote repository speaks the format's own upstream protocol (`RemoteProtocol`: +NuGet `V3`/`V2`, `Npm`, `Maven`, `Docker`), set from the format. Azure Table still serves `default` only. + +## Data model (B1) + +npm tables exist (migration `AddNpmTables` on SQLite, SQL Server, PostgreSQL, MySQL; no pending model change on any): + +| Table | Columns | Keys | +|---|---|---| +| `NpmPackages` (repository-scoped) | `Name` (lower case, scope kept, 214), `Created`, `Modified` | unique `(RepositoryKey, Name)` | +| `NpmVersions` | `PackageKey`, `Version` (256), `Integrity` (sha512 SRI), `Shasum` (sha1 hex), `TarballSize`, `Manifest` (JSON, unbounded), `Deprecated`, `Published` | unique `(PackageKey, Version)`; cascade from package | +| `NpmDistTags` | `PackageKey`, `Tag` (128), `Version` | unique `(PackageKey, Tag)`; cascade; no FK to the version | + +The packument is built from the manifests, so the registry answers what was published (without the tarball address, built per request). +Tarballs live in storage, not in rows. The npm registry needed no further schema change: its migration is `AddNpmTables`. +Package owners are the common `PackageOwner` rows (repository-scoped, keyed by the lower-case npm name). + +Maven (built, migration `AddMavenTables`): `MavenArtifacts` (repo, `GroupId`, `ArtifactId`), `MavenVersions` (version, snapshot flag), `MavenFiles` (name, classifier, extension, size, sha1/sha256/md5/sha512, timestamp+build for snapshot builds); `maven-metadata.xml` is generated from the rows, never stored; GAV stays a string (index length on MySQL). + +Docker / OCI (built, migration `AddOciTables`; details in [Docker registry](docker-registry.md#storage-and-data)): `OciRepositories` (image per repository), `OciManifests` (digest, media type, artifact type, `subject` digest for referrers, the JSON as pushed), `OciTags` (case-sensitive, deleted with the manifest), `OciBlobs` (digest unique per repository, size, `RefCount`), `OciBlobLinks` (which image holds which blob; a blob is served only through its link) and `OciUploads` (open sessions). Blobs are files named by digest, stored once per repository; digests are `sha256:` + 64 hex (71, columns 140). + +## Client authentication (B3) + +| Client | Flow | Verified | +|---|---|---| +| npm | `//host/:_authToken=T` in `.npmrc`; every request after carries `Authorization: Bearer T`. Nothing is sent unprompted without a token; a `401` is final (`E401`, no retry). `npm whoami` is `GET /-/whoami`. `npm login` tries `POST /-/v1/login` (web login); on `404` it falls back to `PUT /-/user/org.couchdb.user:NAME` with `{_id,name,password,type:"user",roles,date}` and expects `{ok,id,rev,token}`; the token is then stored as `_authToken`. The registry therefore needs **bearer tokens** (access tokens) and the CouchDB user call | real npm 10.9.9, `NpmClientFlowTests` | +| Docker | `GET /v2/` answers `401` + `WWW-Authenticate: Bearer realm="…/token",service="…"`; `docker login` then sends `GET {realm}?account=U&client_id=docker&offline_token=true&service=S` with **Basic** (user and password or token), takes `{token,expires_in}` and retries `/v2/` with `Bearer`; pull and push ask `{realm}?scope=repository:NAME:pull,push&service=S` first. Plain HTTP only for `localhost` or an insecure registry. **Built (P5):** `GET /v2/token` validates the Basic credentials (an API key is the password) and answers a signed, short-lived, scope-limited token that never contains the key | real Docker 27 in `docker:27-dind` (`DockerCliTests`: login, push, pull, wrong key refused, private repository) | +| Maven | HTTP Basic from `settings.xml` (`` matching the repository id; user, password or token). Maven sends credentials **after a `401`** with `WWW-Authenticate: Basic`; deploy (`PUT`) also challenges first. `401` with a Basic challenge is enough | verified with the real `mvn` 3.9 (`MavenCliTests`): deploy and resolve both send the `settings.xml` credentials after the challenge; Maven 3.8.1+ also blocks plain-http repositories | + +## Client test rigs (B6) + +`tests/BaGet.Clients.Tests`: `ClientContainers.NodeAsync()` starts `node:22-alpine` once (idle, `sleep infinity`) and runs scripts in +it with an empty `$HOME`. `HostRegistry` is a real Kestrel server on `0.0.0.0` that records requests; the container reaches it as +`host.docker.internal:{port}` (an extra host `host-gateway`, so Linux works too). `WebApplicationFactory` has no socket, so the CLI tests host the real application on such a server for the CLI tests. The tests skip without a Docker daemon (as `BaGet.Database.Tests`). + +`docker:dind`: **used by `DockerCliTests`** (`DockerDaemon`): `docker:27-dind` with `--privileged`, `DOCKER_TLS_CERTDIR=` and +`--insecure-registry=` reaches `docker info` in ~25 s; the `docker` CLI runs inside the same container against the unix socket, +each script with its own `DOCKER_CONFIG`. Images are built `FROM scratch` (no internet). A CI runner must allow privileged +containers; the tests skip when it does not. Maven: `ClientContainers.MavenAsync()` (`maven:3.9-eclipse-temurin-21`) needs no privilege and, like npm, runs `mvn` in a fresh `$HOME`; the plugins come from Maven Central. + +## Streaming storage (B2) + +`IStreamingStorageService : IStorageService` (`BaGet.Core/Storage`) is the capability a format with huge blobs (Docker layers, +many GB) needs; `PutAsync` takes a whole stream; S3, GCS and Aliyun spool it to a temporary file (not memory) before uploading, and S3/GCS/Aliyun/Azure `GetAsync` of a missing object throws `FileNotFoundException`, like the file store. Nothing is added to `IStorageService`, so +existing providers and tests are unaffected. + +| Call | Meaning | +|---|---| +| `BeginUploadAsync(contentType)` | opaque, URL-safe upload id | +| `AppendAsync(id, offset, chunk)` | adds bytes at the length the store holds; another offset throws `StorageUploadOffsetException` carrying the real length (OCI `416` + `Range`). Returns the new length | +| `GetUploadLengthAsync(id)` | where to resume; null = no such upload | +| `CommitAsync(id, path, sha256?)` | makes the content visible at `path` (known only now, a digest path) and removes the upload. `Success`, `AlreadyExists` (identical content) or `Conflict`; a wrong digest throws `StorageDigestMismatchException` and stores nothing | +| `AbortAsync(id)` | discards; unknown ids ignored | +| `GetInfoAsync(path)` / `GetRangeAsync(path, offset, length?)` | `HEAD` and `GET` with `Range`; stream, never a whole blob | + +- **Memory:** one part/block buffer per request (8 MiB Azure and GCS, 16 MiB S3 and Aliyun), never the blob. SHA-256 is computed while the bytes stream + (`UploadDigestTracker`); a node that lost the running hash (restart, another node took the chunk) recomputes it from the stored + content at commit, still streaming. The caller owns an upload's lifetime (sessions expire; abort). +- **Reads:** S3, Aliyun and GCS serve a range as bounded 64 MiB requests (`WindowedReadStream`), each re-requested from the exact byte + if its connection drops, so a many-GB `GET` is never one connection that must survive; Azure's read stream already works in windows. +- **Refusal:** `IFormatModule.RequiresStreamingStorage` (default false; the Docker module sets it) makes `RepositoryService.CreateAsync` throw + `NotSupportedException` (`StreamingStorage.Require`) for a local or remote repository of that format when the configured store is not + an `IStreamingStorageService`; virtual repositories hold no blobs and are exempt. Every shipped provider streams, so today this guards custom stores. + +| Provider | Mechanism | Verified against | +|---|---|---| +| FileSystem, Null | file grown under `.uploads/`, moved into place on commit | in-process | +| AwsS3 | multipart into `.uploads/`, bytes short of a part kept in a `.tail` object, copied to the final key by ranged multipart copy completed with `If-None-Match: *` | S3Mock (Testcontainers) | +| AzureBlobStorage | staged blocks of a temp blob (`.uploads/`), committed then copied server side if-not-exists | Azurite | +| GoogleCloud | resumable session over HTTP (8 MiB chunks, a multiple of 256 KiB), tail object, copy with `ifGenerationMatch=0` | `oittaa/gcp-storage-emulator` | +| AliyunOss | as S3 (multipart + tail + ranged copy) | **no emulator exists**: code review and the shared contract only; commit of the same key is not atomic (the SDK sends no `x-oss-forbid-overwrite`) | + +Measured (5 GiB blob in 256 MiB chunks, growth of the test process's private memory; B2 of the plan): FileSystem 6 MiB, Azure/Azurite 55 MiB, +S3/S3Mock 68 MiB; GCS 1 GiB 11 MiB (the emulator keeps blobs in RAM, a 5 GiB run did not finish); Aliyun not measurable. Azure +block ids are ordered by their index, not their base64 text (the 5 GiB run caught a scrambled blob). + +Emulator limits (not service limits): the GCS emulator ignores `DELETE` on a session and `ifGenerationMatch` on a copy, so those +contract assertions are switched off for it (`CancelledSessionsAreGone`, `ConditionalCopyIsEnforced`); MinIO was planned for S3 but no longer +publishes images. Tests: `tests/BaGet.Storage.Tests` (one shared contract run against every provider; skips without Docker). The +large-blob test streams 96 MiB by default and 5 GB with `BAGET_STORAGE_LARGE_BYTES=5368709120`, measuring the process's private memory. + +**Body limits for chunked uploads.** The host sets Kestrel's `MaxRequestBodySize` to unlimited (`Program.cs`; the plan's "~2 GB" was +`FormOptions.MultipartBodyLengthLimit`, which only form posts see, not a raw `PATCH`). Under IIS the limits are per request, so a +client that sends a layer in one `PATCH` hits them: `IISServerOptions.MaxRequestBodySize` (BaGet default 250 MB) and `web.config` +`requestLimits maxAllowedContentLength` (30 MB default, 4 GB ceiling). Raise both, or put the registry behind a proxy with no body +limit; a client that chunks (`Content-Range`) stays under them. See [Configuration](configuration.md#iis-server-options). diff --git a/docs/high-availability.md b/docs/high-availability.md new file mode 100644 index 000000000..66b647abc --- /dev/null +++ b/docs/high-availability.md @@ -0,0 +1,101 @@ +# High availability + +Several BaGet nodes behind a load balancer, sharing one database, one object store and one Redis. **Off by default**: a +single node needs no Redis and behaves exactly as before. + +## Requirements + +| Need | Why | Refused at startup | +|---|---|---| +| A shared database: SQL Server, PostgreSQL or MySQL | every node reads and writes the same rows; the data protection keys live there | SQLite (a file on one machine), Azure Table | +| Shared storage: S3, Azure Blob, Google Cloud, Aliyun OSS | every node serves the same files | the file system (`Storage:Type` `Filesystem`) | +| Redis (any 6+), reachable from every node | leases, the read-only gate, rate limits | `Ha:ConnectionString` empty | +| A balancer that probes `/health/ready` | a node that cannot reach its database or storage leaves rotation (Redis is reported only) | - | + +A node that breaks a rule logs it at critical level and does not start (`HaStartupGuard`, and `ValidateStartupOptions` before the host starts). + +## Settings (`Ha:*`, all need a restart) + +| Key | Default | Meaning | +|---|---|---| +| `Ha:Enabled` | `false` | Cluster mode | +| `Ha:Backend` | `Redis` | The only backend | +| `Ha:ConnectionString` | empty | Redis connection string (`host:6379,password=...,ssl=true`); sensitive, never shown or logged | +| `Ha:NodeName` | machine name + random suffix | Name on the Cluster page and in lease holders | +| `Ha:KeyPrefix` | `baget` | Prefix of every Redis key, so clusters can share a Redis | +| `Ha:LeaseDuration` | `00:00:30` | A lease or gate of a node that stopped answering frees after this; holders renew every third of it (min 3 s) | +| `Ha:SyncInterval` | `00:00:02` | Heartbeat and pick-up of what other nodes changed (min 100 ms) | +| `Ha:KeyCertificatePath` | empty | PFX (with private key, the same on every node) that encrypts the data protection keys stored in the database. **Set it**: without it the keys sit as plain XML next to the secrets they protect (remote passwords, replication peer keys) and the node logs a warning at start | +| `Ha:KeyCertificatePassword` | empty | Password of that PFX; sensitive | + +They are on **Server settings > Ha** (connection string masked). Give every node the same database, storage, `Ha:KeyPrefix` +and Redis. `Ha:NodeName` may differ or be left empty. + +## What is shared + +Every singleton or static holding state (B4), by where it lives in a cluster: + +| State | Class | In a cluster | +|---|---|---| +| Read-only gate | `MaintenanceGate` | **Shared.** `Close` is published to Redis (key `gate`, renewed by the closing node, freed if it dies); every node refuses writes. Only the closing node reopens it. `CloseUntilRestart` stays on its node | +| Database copy progress | `DatabaseCopyService` | **A copy is refused while `Ha:Enabled`** (the Settings page shows why): the other nodes cannot be confirmed read-only before it reads, and after it succeeds they would reopen and write to the old database. To move a cluster: stop the other nodes, turn `Ha:Enabled` off, copy, restart, re-enable. Progress is still shared so a node shows a copy it did not start | +| Contact-owners limit, password-reset limits | `ContactRateLimiter`, `PasswordResetRateLimiter` | **Shared** (Redis keys with expiry; the client cap is a fixed window) | +| Data protection keys (cookies, antiforgery, protected remote and replication credentials) | key ring | **Shared** in table `DataProtectionKeys`, one application name. Credentials protected before HA was enabled used the old key ring: enter them again. Encrypt the ring with `Ha:KeyCertificatePath`. A key is written through a context the read-only gate does not block, so sign-in keeps working while the cluster is read-only. A key created while a (non-cluster) database copy runs may be missing from the copy: sessions and protected credentials made with it fail after the restart, enter them again | +| Access model | `AccessModelCache`, `AccessModelVersion` | **Per-node cache, shared invalidation.** A committed change bumps a Redis counter; the others reload within `Ha:SyncInterval` (30 s at the latest) | +| Job leases | `IJobLease` | **Shared** (`ClusterJobLease`); see below | +| Scans in progress | `ScanInFlight` | **Shared marker** per image (so the scanner's pull is recognised on whichever node receives it) | +| Settings overrides file | `SettingsOverridesStore` | **Per node** (`appsettings.Overrides.json`). Keep one file for all nodes (a shared volume, `SettingsOverridesPath`) or configure by environment; all settings that matter here need a restart anyway | +| Remembered upstream answers, counters, pooled clients | `RemoteRepositoryState` | **Per node** (TTL based). A purge on one node clears that node; others expire theirs by TTL | +| Remote downloads in progress | `KeyedLocks`, `RemoteOciRegistry.Caching` | **Per node.** Two nodes may fetch the same file; the second store is a no-op | +| Job status and last reports | `AdminJobService`, `RetentionJobs`, `ReplicationJobs` | **Per node** (memory); the run itself is leased. The page shows the status of the node you reached | +| Scan queue, policy and advisory caches | `ScanQueue`, `ScanPolicyCache`, `OsvState` | **Per node** | +| Download times | `ArtifactUsageRecorder` | **Per node**, flushed to the database in batches | +| Validation queue | `InMemoryValidationQueue` | **Per node**; one validator per submission (lease); every minute a cluster node offers all pending submissions again, so a node that died mid-validation is not waited for | +| Docker blob commit fence | `OciBlobCommits` | **Per node**: the garbage collector's "files without a row" step is **skipped in a cluster** (its report says so) because it cannot see another node's commit | +| E-mail queue | `BackgroundEmailQueue` | **Per node** (mail queued on a node that stops is lost, as on a single node) | +| Telemetry status and exporters | `TelemetryStatus` | **Per node**: each node exports its own signals; set `Telemetry:ServiceName` per node if you want them apart | +| Format registry, framework tables, factories | stateless | identical on every node | + +## Jobs run once + +The lease is a Redis key only one node can create, holding `node|token|since`; it expires after `Ha:LeaseDuration` unless the +holder renews it (every third). A node that cannot reach Redis **skips** the job instead of running it twice. + +| Job | Lease | +|---|---| +| Retention schedule pass (all due policies) | `retention:schedule` | +| A retention run, scheduled or from the page | `retention:policy:{key}` (a dry run takes none) | +| Replication run, resume, orphan sweep | `replication:{config key}` | +| Admin operation (catalog rebuild, import downloads, Docker GC, vulnerability scan) | `operation:{name}:{repository}` | +| Scheduled vulnerability rescan | `scan:sweep` | +| Abandoned-upload sweep | `staging:sweep` | +| Validation of one submission | `validation:{submission id}` | +| A catalog commit (a commit waits up to 30 s for it, so timestamps stay in order across nodes; with the store unreachable it commits without it, warning) | `catalog:{repository key}` | +| Docker garbage collection schedule | runs inside a retention policy (`CollectGarbage`), so under its lease | + +## Health + +| Endpoint | Answer | +|---|---| +| `GET /health/live` | `200 Healthy` while the process answers | +| `GET /health/ready` | `200` or `503` with `{"status", "checks": {"database", "storage", "cluster"}}`; `503` only when `database` or `storage` fails. `cluster` (the Redis ping) appears only with HA and is **reported, never a cause of `503`** (a node keeps serving without Redis); checked at most every 5 s | + +The storage check writes and deletes a one-byte object under `health/`. The body never carries a message or a connection +string. Readiness ignores the read-only gate: a node refusing writes still serves reads. + +## Cluster page + +**Admin > Cluster** (`/admin/cluster`): the nodes with a heartbeat in the last seconds (version, start, readiness, read-only), the leases held +and by whom, whether the cluster is read-only and why, and this node's health checks (`Check again` re-runs them). + +## Redis down + +Nodes keep serving. Leases are refused (jobs wait), the gate and access model stop propagating (the access model still reloads +every 30 s) and the rate limiters of a node fail their page with an error until Redis returns. `/health/ready` stays `200` (a Redis +outage would otherwise take every node out of rotation at once); `cluster` shows `Unhealthy` in its body and on the Cluster page. + +## Tests + +`ClusterTests` (`BaGet.Tests`) run two real nodes in one process on one SQLite file, one package folder and an in-memory store +(`ClusterHarness`; `HaBackendRules.AllowLocalBackends` lifts the startup refusal for the test only). `BaGet.Ha.Tests` runs the +store contract and the same two nodes against a real Redis in Testcontainers (skips without Docker). diff --git a/docs/howto.md b/docs/howto.md new file mode 100644 index 000000000..5c887b883 --- /dev/null +++ b/docs/howto.md @@ -0,0 +1,105 @@ +# How-to + +Short recipes for common tasks. `host` is your server (default `http://localhost:6060`); `{name}` is a repository name. Details are in the linked pages. + +## Publish and restore + +| Goal | Steps | +|---|---| +| Push a NuGet package | Create a key on `/account/apikeys`, then `dotnet nuget push -s http://host/v3/index.json -k pkg.nupkg` | +| Push symbols | Same command with a `.snupkg`; symbol location `http://host/api/download/symbols` | +| Use the server as a source | Add `http://host/v3/index.json` to `NuGet.config` or Visual Studio | +| Push from the browser | `/upload`: stage, preview the metadata, confirm | +| Use V2 clients | Source `http://host/api/v2` (`Feeds:EnableV2`, on by default) | + +## Create a second repository + +1. Sign in as an administrator, open `/admin/repositories`. +2. Create a local repository, pick its format (NuGet, npm, Maven, Docker) and a name. +3. Its feed is `http://host/r/{name}/v3/index.json` (Docker: `host/v2/{name}/{image}`). + +See [Repositories](repositories.md). + +## Make a feed private + +1. Open `/admin/repositories/{name}` and switch off *Anonymous read* (or edit the permission targets). +2. Give each reader a user API key. +3. Add the source with credentials: + `dotnet nuget add source http://host/r/{name}/v3/index.json -n {name} -u -p --store-password-in-clear-text --allow-insecure-connections` (the last flag only for plain `http`). + +See [Access control](access-control.md). + +## Cache nuget.org (or another upstream) + +1. `/admin/repositories`: create a [remote repository](remote-repositories.md) with the upstream URL (add credentials if needed). +2. Point clients at the new repository's feed. Packages are stored on first download; offline mode and purge are on its edit page. +3. To combine local and cached packages under one URL, create a [virtual repository](virtual-repositories.md) with both as members and pick the deploy repository for uploads. + +## Use npm + +``` +npm config set registry http://host/r/{name}/npm/ +npm login +npm publish +``` + +Or a scope only: `@acme:registry=http://host/r/{name}/npm/` in `.npmrc`; auth via `//host/r/{name}/npm/:_authToken=`. See [npm registry](npm-registry.md). + +## Use Maven + +Create a Maven repository, put its API key in `settings.xml` and the repository in the POM; the package page generates both snippets. `mvn deploy` publishes. See [Maven repositories](maven-repositories.md). + +## Use Docker + +``` +docker login host # user name + API key as password +docker push host/{name}/myimage:1.0 +docker pull host/{name}/myimage:1.0 +``` + +Plain `http` works only for `localhost` or hosts in `insecure-registries`. See [Docker registry](docker-registry.md). + +## Clean up old versions + +1. `/admin/retention`: new policy for a repository or project (keep the newest N, older than days, unused, cache size, untagged Docker manifests). +2. Run a dry run, read the plan, then save and run (the password is asked). +3. Protect versions with a hold; set a schedule for automatic runs. + +See [Retention](retention.md). + +## Scan for vulnerabilities + +Set `Scanning:*` (off by default), then choose a policy per repository or project: warn, or refuse downloads and deploys. Findings show on package pages. See [Vulnerability scanning](vulnerability-scanning.md). + +## Import existing packages + +[From nuget.org](import/nugetorg.md), [from NuGet.Server](import/nugetserver.md), [from a local feed](import/local-feeds.md). Download counts: `dotnet BaGet.dll import downloads`. + +## Regain admin access + +| Case | Command | +|---|---| +| Forgot the password | `dotnet BaGet.dll account reset-password [--email
]` | +| Need an administrator | `dotnet BaGet.dll account promote ` | + +Both need `Accounts:Enabled`. + +## Change a setting without editing files + +`/admin/settings` (administrators): changes apply live unless marked restart-required, and are saved to `appsettings.Overrides.json`. See [Configuration](configuration.md#settings-page). + +## Move to another database + +Settings page: change `Database:Type` / `Database:ConnectionString`, keep *Copy all data* ticked, save. The server is read-only during the copy and stays so until you restart it. See [Moving to another database](configuration.md#moving-to-another-database). + +## Script administration + +Create an administrator key with scope `admin:api` and call `/api/v1` (OpenAPI at `/api/v1/openapi.json`, catalog at `/admin/api`). See [Administration REST API](admin-api.md). + +## Run several nodes + +Needs a shared database (not SQLite), shared object storage, Redis and `Ha:Enabled=true`; probe `/health/ready`. See [High availability](high-availability.md). + +## See traces + +Run Jaeger and set `Telemetry__Otlp__Endpoint=http://jaeger:4317`; see the Docker page's Jaeger example: [Docker](installation/docker.md#tracing-with-jaeger). diff --git a/docs/import/local-feeds.md b/docs/import/local-feeds.md index a9668d159..5f9f129ca 100644 --- a/docs/import/local-feeds.md +++ b/docs/import/local-feeds.md @@ -3,7 +3,7 @@ [Local feeds](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) let you use a folder as a NuGet package source. !!! info - Please refer to the [BaGet vs local feeds](../vs/local-feeds.md) page for reasons to upgrade to BaGet. + Please refer to the [BaGet Extension vs local feeds](../vs/local-feeds.md) page for reasons to upgrade to BaGet Extension. ## Steps @@ -11,15 +11,17 @@ Make sure that you've installed [nuget.exe](https://www.nuget.org/downloads). In ```ps1 $source = "C:\path\to\local\feed" -$destination = "http://localhost:5000/v3/index.json" +$destination = "http://localhost:6060/v3/index.json" ``` -If you've [configured BaGet to require an API Key](https://loic-sharma.github.io/BaGet/configuration/#requiring-an-api-key), set it using [the `setapikey` command](https://docs.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-setapikey): +If BaGet Extension requires an API key (a global `ApiKey`, or [accounts](../configuration.md#accounts-package-owners-and-api-keys), on by default), set it using [the `setapikey` command](https://docs.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-setapikey): ```ps1 & nuget.exe setapikey "MY-API-KEY" -Source $destination ``` +With accounts on, use a user API key from `/account/apikeys`; the account must own each package, or its ID must be new. + Now run the following PowerShell script: ```ps1 diff --git a/docs/import/nugetorg.md b/docs/import/nugetorg.md index c140e2b8d..20be97abb 100644 --- a/docs/import/nugetorg.md +++ b/docs/import/nugetorg.md @@ -1,30 +1,28 @@ # Import nuget.org packages -!!! warning - This page is a work in progress! - ## Mirroring -You can configure BaGet to mirror nuget.org. For example, say you install BaGet, enable mirroring, and try to install the package -[`Newtonsoft.Json`](https://www.nuget.org/packages/Newtonsoft.Json/). BaGet doesn't have this package yet, so it will +You can configure BaGet Extension to mirror nuget.org. For example, say you install BaGet Extension, enable mirroring, and try to install the package +[`Newtonsoft.Json`](https://www.nuget.org/packages/Newtonsoft.Json/). BaGet Extension doesn't have this package yet, so it will automatically index this package from nuget.org. This is also known as "read-through caching". -For more information, please see [Enable read-through caching](../configuration#enable-read-through-caching). +For more information, please see [Enable read-through caching](../configuration.md#enable-read-through-caching). `Mirror:Legacy` reads a NuGet v2 source and `Mirror:PackageDownloadTimeoutSeconds` (default 600) is the timeout of every HTTP request to the upstream. ## Importing package downloads from nuget.org -You can import package downloads from nuget.org: +You can import nuget.org's download counts for the packages BaGet Extension already has: 1. Navigate to `.\BaGet\src\BaGet` 2. Run: ``` -dotnet run -- import-downloads +dotnet run -p:GeneratePackageOnBuild=false -- import downloads ``` +Or, from a release: `dotnet BaGet.dll import downloads`. + +It runs against the configured `Database`, overwrites the stored download count of every package version nuget.org lists, and needs a relational database (not Azure Table). + ## Importing all nuget.org packages -* TODO Check-in code -* Explain scaling -* Rebuild indexes at end -* Importing downloads from nuget.org +Not supported as a command. Use read-through mirroring (above), which indexes packages on demand. diff --git a/docs/import/nugetserver.md b/docs/import/nugetserver.md index a9b38ca55..6acce98d7 100644 --- a/docs/import/nugetserver.md +++ b/docs/import/nugetserver.md @@ -1,9 +1,9 @@ # Import NuGet.Server packages -[NuGet.Server](https://github.com/NuGet/NuGet.Server) is a lightweight standalone NuGet server. It is strongly recommended that you upgrade to BaGet if you use NuGet.Server. Feel free to open a [GitHub issue](https://github.com/loic-sharma/BaGet/issues) if you need help migrating. +[NuGet.Server](https://github.com/NuGet/NuGet.Server) is a standalone A NuGet, Maven, NVM, Docker and symbol. It is strongly recommended that you upgrade to BaGet Extension if you use NuGet.Server. Feel free to open a [GitHub issue](https://github.com/loic-sharma/BaGet/issues) if you need help migrating. !!! info - Please refer to the [BaGet vs NuGet.Server](../vs/nugetserver.md) page for reasons to upgrade to BaGet. + Please refer to the [BaGet Extension vs NuGet.Server](../vs/nugetserver.md) page for reasons to upgrade to BaGet Extension. ## Steps @@ -11,15 +11,17 @@ Make sure that you've installed [nuget.exe](https://www.nuget.org/downloads). In ```ps1 $source = "" -$destination = "" +$destination = "" ``` -If you've [configured BaGet to require an API Key](https://loic-sharma.github.io/BaGet/configuration/#requiring-an-api-key), set it using [the `setapikey` command](https://docs.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-setapikey): +If BaGet Extension requires an API key (a global `ApiKey`, or [accounts](../configuration.md#accounts-package-owners-and-api-keys), on by default), set it using [the `setapikey` command](https://docs.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-setapikey): ```ps1 & nuget.exe setapikey "MY-API-KEY" -Source $destination ``` +With accounts on, use a user API key from `/account/apikeys`; the account must own each package, or its ID must be new. + Now run the following PowerShell script: ```ps1 diff --git a/docs/index.md b/docs/index.md index fb491b19b..3382880d8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,14 +1,16 @@ -# BaGet +# BaGet Extension -BaGet (pronounced "baguette") is a lightweight NuGet and symbol server. It is [open source](https://github.com/loic-sharma/BaGet), cross-platform, and cloud ready! +BaGet Extension is A NuGet, Maven, NVM, Docker and symbol server. It is [open source](https://github.com/pieroviano/BaGet) (a fork of [loic-sharma/BaGet](https://github.com/loic-sharma/BaGet)), cross-platform, and cloud ready!

- +

-## Run BaGet +New here? Read the [installation manual](installation-manual.md) and the [user manual](user-manual.md); operators: the [DevOps manual](devops-manual.md); common tasks: [how-to](howto.md). -You can run BaGet on your preferred platform: +## Run BaGet Extension + +You can run BaGet Extension on your preferred platform: * [On your computer](installation/local.md) * [Docker](installation/docker.md) @@ -16,7 +18,71 @@ You can run BaGet on your preferred platform: * [AWS](installation/aws.md) * [Google Cloud](installation/gcp.md) * [Alibaba Cloud (Aliyun)](installation/aliyun.md) +* [Windows, behind an IIS proxy](installation/iis-proxy.md) + +A fresh install has one account, the [default administrator](configuration.md#default-administrator) `Admin` / `Admin1234!`: sign in and change its password at once. + +## Repositories + +One server can hold several [repositories](repositories.md), each with its own feed at `/r/{name}/v3/index.json`; `default` stays at `/`. Repositories have a [format](formats.md): NuGet, and [npm registries](npm-registry.md) (`npm publish` / `install`, dist-tags, deprecate, unpublish, `npm login`), [Maven repositories](maven-repositories.md) (`mvn deploy`, snapshots, checksums, release/snapshot policy) and a [Docker registry](docker-registry.md) (`docker login` / `push` / `pull`, multi-platform images, referrers). A [remote repository](remote-repositories.md) caches another NuGet feed, npm registry, Maven repository or Docker registry such as registry.npmjs.org or Docker Hub (credentials, cache periods, offline mode, purge); a [virtual repository](virtual-repositories.md) puts several of them behind one URL (first match wins, merged search and packuments, uploads to a chosen member). [Retention policies](retention.md) delete old versions on a schedule (keep the newest N, by age, unused, remote cache size, untagged Docker manifests) with a dry run and legal holds. [Replication](replication.md) copies a local repository to or from a repository of another BaGet server (push or pull, on deploy and on a schedule, resumable, any format). [High availability](high-availability.md) runs several nodes behind a load balancer on one database, object store and Redis (jobs run once, the read-only gate and rate limits are shared, `/health/live` and `/health/ready`). The [Settings page](configuration.md) edits configuration live, and OpenTelemetry export (traces, metrics, logs) needs an OTLP endpoint. + +## Access control + +Who may read and write what is set by [groups, permission targets and project roles](access-control.md): private feeds, +Basic-auth client setup, upgrade defaults and the admin pages. + +## Vulnerability scanning + +Packages, npm and Maven artifacts are checked against [OSV.dev](https://osv.dev) (online or an offline copy) and Docker images by +Trivy; findings appear on every package page and in an administrator dashboard, feed NuGet's vulnerability resource, and a +per-repository or per-project policy can warn or refuse downloads and deploys with `403` and the reason: +[vulnerability scanning](vulnerability-scanning.md). + +## Administration REST API + +`/api/v1` does everything the administrator pages do (repositories, access model, users, operations, retention, scanning, replication) for +scripts, with an administrator's API key and OpenAPI 3: [administration REST API](admin-api.md); try every endpoint in the browser: [testing the APIs with Scalar](scalar.md). Every web screen also has a JSON twin for custom frontends: [UI API](ui-api.md); build your own in React or Angular: [custom frontend](custom-frontend.md). + +## What BaGet Extension serves + +BaGet Extension speaks the NuGet V3 protocol, with a V2 feed for older clients (on by default), and serves +symbols; npm, Maven and Docker are served per repository (above). Accounts with package owners and per-user API keys are on by default; a validation +pipeline with repository signing is opt-in. Both are set in its [configuration](configuration.md). +By default it listens on `http://localhost:6060` (`Kestrel:Endpoints`; `--urls` has no effect). The [server API](advanced/api.md) lists +every resource and page, [UI coverage](ui-coverage.md) maps every capability to its page, and [BaGet Extension vs nuget.org](vs/nugetorg.md) compares the two. + +## Import packages + +* [From nuget.org](import/nugetorg.md) +* [From NuGet.Server](import/nugetserver.md) +* [From a local feed](import/local-feeds.md) + +## Compare BaGet Extension + +* [nuget.org](vs/nugetorg.md) +* [Artifactory](vs/artifactory.md) +* [Azure Artifacts](vs/azure-artifacts.md) +* [LiGet](vs/liget.md) +* [Local feeds](vs/local-feeds.md) +* [MyGet](vs/myget.md) +* [Nexus](vs/nexus.md) +* [NuGet.Server](vs/nugetserver.md) +* [TeamCity](vs/teamcity.md) + +## Advanced + +* [Architecture](advanced/architecture.md) +* [Server API](advanced/api.md) +* [Debugging BaGet Extension](advanced/debugging.md) + +## BaGet Extension SDK + +You can also use the [`BaGet.Protocol`](https://www.nuget.org/packages/BaGet.Protocol) package to interact with a NuGet server. For more information, please refer to the [BaGet Extension SDK](advanced/sdk.md) guide. + +To browse these pages without a site, see [reading this folder](https://github.com/pieroviano/BaGet/tree/main/docs). -## BaGet SDK +## Credits -You can also use the [`BaGet.Protocol`](https://www.nuget.org/packages/BaGet.Protocol) package to interact with a NuGet server. For more information, please refer to the [BaGet SDK](advanced/sdk.md) guide. +BaGet Extension is based on [BaGet](https://github.com/loic-sharma/BaGet) (pronounced "baguette") by Loic Sharma, +released under the MIT licence. See [LICENSE](https://github.com/pieroviano/BaGet/blob/main/LICENSE) and +[Acknowledgments](https://github.com/pieroviano/BaGet/blob/main/Acknowledgments.md). diff --git a/docs/installation-manual.md b/docs/installation-manual.md new file mode 100644 index 000000000..f5f30105d --- /dev/null +++ b/docs/installation-manual.md @@ -0,0 +1,98 @@ +# Installation manual + +Step-by-step installation of BaGet Extension. Per-platform details are in the linked pages. + +## 1. Choose a platform + +| Platform | Page | +|---|---| +| Your computer (Windows, Linux, macOS) | [On your computer](installation/local.md) | +| Docker | [Docker](installation/docker.md) | +| Windows, IIS | [IIS proxy](installation/iis-proxy.md) | +| Azure | [Azure](installation/azure.md) | +| AWS | [AWS](installation/aws.md) | +| Google Cloud | [Google Cloud](installation/gcp.md) | +| Alibaba Cloud | [Aliyun](installation/aliyun.md) | + +## 2. Requirements + +| Item | Needed for | +|---|---| +| [.NET 10 ASP.NET Core Runtime](https://dotnet.microsoft.com/download/dotnet/10.0) (or SDK) | Running on your computer | +| [.NET 10 Hosting Bundle](https://dotnet.microsoft.com/download/dotnet/10.0) | IIS | +| Docker | Docker install | +| A database (SQLite is built in) | SQL Server, PostgreSQL or MySQL are optional | +| Redis | Only [high availability](high-availability.md) | + +## 3. Install on your computer + +1. Get the host: download the `BaGet` workflow artifact of a release run, or publish it: + `dotnet publish src/BaGet -c Release -o artifacts -p:GeneratePackageOnBuild=false`, then extract. +2. Start it: `dotnet BaGet.dll`. +3. Browse `http://localhost:6060/`. + +- The port comes from `Kestrel:Endpoints:Http:Url` in `appsettings.json`; `--urls` and `ASPNETCORE_URLS` have no effect. Override with the environment variable `Kestrel__Endpoints__Http__Url`. +- Migrations run at startup (`RunMigrationsAtStartup`, on by default). +- On a server with no users, startup creates the administrator `Admin` / `Admin1234!`. Change the password at once ([Default administrator](configuration.md#default-administrator)). + +## 4. Install with Docker + +1. Create `baget.env` and a `baget-data` folder (sample env file: [Docker](installation/docker.md#configure-baget-extension)). Minimum: + +``` +ApiKey= +Kestrel__Endpoints__Http__Url=http://+:80 +Storage__Type=FileSystem +Storage__Path=/var/baget/packages +Database__Type=Sqlite +Database__ConnectionString=Data Source=/var/baget/baget.db +Search__Type=Database +SettingsOverridesPath=/var/baget/appsettings.Overrides.json +``` + +2. Build the image from the repository root: `docker build -t baget .` (or pull the one the release workflow publishes). +3. Run it: + +``` +docker run --rm --name nuget-server -p 6060:80 --env-file baget.env -v "$(pwd)/baget-data:/var/baget" baget:latest +``` + +Keep `SettingsOverridesPath` and the log path inside the mounted volume, or a recreated container loses them. The data protection key ring (`DataProtection-Keys`) is created beside the overrides file, so with the setting above it is in the volume too; without it a recreated container makes stored remote passwords unreadable and signs everyone out ([Data protection keys](configuration.md#data-protection-keys)). If the container is reached through a proxy or published port, the client address is the Docker gateway: list the proxy in `Proxy:TrustedProxies` / `Proxy:TrustedNetworks`. + +## 5. Install on IIS + +1. Install the .NET 10 Hosting Bundle, restart IIS. +2. Publish the host (`dotnet publish` generates `web.config`) and copy it to the site folder. +3. Create an application pool: no managed code, integrated pipeline. +4. Create a site on that pool with your host name and port (the Kestrel endpoint is not used in-process). +5. Grant the pool identity write access to the folder (required: startup stops if the key folder cannot be written; [IIS proxy](installation/iis-proxy.md)): the data protection key ring is written to `DataProtection-Keys` beside the overrides file (set `DataProtection:KeyPath` for another folder), so a pool without a loaded user profile no longer loses its keys. + +## 6. Choose a database, storage and search + +Set these in `appsettings.json`, environment variables or (after install) the Settings page. Full list: [Configuration](configuration.md). + +| Subsystem | Setting | Values | +|---|---|---| +| Database | `Database:Type`, `Database:ConnectionString` | `Sqlite` (default), `SqlServer`, `PostgreSql`, `MySql`, `AzureTable` | +| Storage | `Storage:Type` | `FileSystem` (default), `AzureBlobStorage`, `AwsS3`, `GoogleCloud`, `AliyunOss`, `Null` | +| Search | `Search:Type` | `Database` (default), `AzureSearch`, `Null` | + +Cloud setup: [Azure](installation/azure.md), [AWS](installation/aws.md), [Google Cloud](installation/gcp.md), [Aliyun](installation/aliyun.md). +Docker registry repositories need a storage that can stream (not `Null`): [Package formats](formats.md#streaming-storage-b2). + +## 7. First steps after installing + +| Step | How | +|---|---| +| Change the `Admin` password | Sign in, then the profile page | +| Set `ApiKey` or create user keys | Global `ApiKey` setting, or `/account/apikeys` | +| Publish a package | `dotnet nuget push -s http://localhost:6060/v3/index.json -k pkg.nupkg` | +| Add the feed to clients | Source `http://localhost:6060/v3/index.json`; symbols `http://localhost:6060/api/download/symbols` | +| Behind a reverse proxy / HTTPS | Terminate TLS at the proxy; the path base is honoured, forwarded headers only from trusted proxies (loopback by default: list yours in `Proxy:TrustedProxies` / `Proxy:TrustedNetworks`, see [Configuration](configuration.md#reverse-proxies-and-forwarded-headers)) | +| Import existing packages | [nuget.org](import/nugetorg.md), [NuGet.Server](import/nugetserver.md), [local feeds](import/local-feeds.md) | + +Next: the [user manual](user-manual.md). + +## 8. Upgrade + +Replace the files (or image) and restart; pending migrations apply at startup. Back up the database and the package store first. diff --git a/docs/installation/aliyun.md b/docs/installation/aliyun.md index d2e6780ee..5c7117d03 100644 --- a/docs/installation/aliyun.md +++ b/docs/installation/aliyun.md @@ -2,9 +2,9 @@ You can store packages to [Alibaba(Aliyun) OSS](https://www.alibabacloud.com/product/oss). -## Configure BaGet +## Configure BaGet Extension -You can modify BaGet's configurations by editing the `appsettings.json` file. For the full list of configurations, please refer to [BaGet's configuration](../configuration.md) guide. +You can modify BaGet Extension's configurations by editing the `appsettings.json` file. For the full list of configurations, please refer to [BaGet Extension's configuration](../configuration.md) guide. ### Aliyun OSS Storage diff --git a/docs/installation/aws.md b/docs/installation/aws.md index 0505d2ade..3e6dbf836 100644 --- a/docs/installation/aws.md +++ b/docs/installation/aws.md @@ -1,13 +1,10 @@ -# Run BaGet on AWS +# Run BaGet Extension on AWS -!!! warning - This page is a work in progress! - -Use Amazon Web Services to scale BaGet. You can store metadata on [Amazon RDS](https://aws.amazon.com/rds/postgresql/) and upload packages to [Amazon S3](https://aws.amazon.com/s3/). +Use Amazon Web Services to scale BaGet Extension. You can store metadata on [Amazon RDS](https://aws.amazon.com/rds/postgresql/) and upload packages to [Amazon S3](https://aws.amazon.com/s3/). -## Configure BaGet +## Configure BaGet Extension -You can modify BaGet's configurations by editing the `appsettings.json` file. For the full list of configurations, please refer to [BaGet's configuration](../configuration.md) guide. +You can modify BaGet Extension's configurations by editing the `appsettings.json` file. For the full list of configurations, please refer to [BaGet Extension's configuration](../configuration.md) guide. ### Amazon S3 @@ -29,6 +26,14 @@ Update the `appsettings.json` file: } ``` +`Region` and `Bucket` are required; set `AccessKey` and `SecretKey` together, or leave both empty to use the default AWS credential chain. Optional keys: + +| Key | Meaning | +| --- | --- | +| `Prefix` | Key prefix for objects in the bucket | +| `UseInstanceProfile` | Use the default AWS credential chain (environment, profile, then EC2 instance profile), ignoring `AccessKey`/`SecretKey` and `AssumeRoleArn` | +| `AssumeRoleArn` | Role to assume, using the default credential chain as the caller; `AccessKey`/`SecretKey` are ignored | + ### Amazon RDS To use PostgreSQL, update the `appsettings.json` file: @@ -66,23 +71,23 @@ To use MySQL, update the `appsettings.json` file: Publish your first package with: ``` -dotnet nuget push -s http://localhost:5000/v3/index.json package.1.0.0.nupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k package.1.0.0.nupkg ``` Publish your first [symbol package](https://docs.microsoft.com/en-us/nuget/create-packages/symbol-packages-snupkg) with: ``` -dotnet nuget push -s http://localhost:5000/v3/index.json symbol.package.1.0.0.snupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k symbol.package.1.0.0.snupkg ``` !!! warning - You should secure your server by requiring an API Key to publish packages. For more information, please refer to the [Require an API Key](../configuration.md#require-an-api-key) guide. + With [accounts](../configuration.md#accounts-package-owners-and-api-keys) on (the default) and an empty `ApiKey`, a push without a key is refused with `401`. Pass either a user API key (created on `/account/apikeys`) or a non-empty global `ApiKey`, with `-k `. See also [Require an API key](../configuration.md#require-an-api-key). ## Restore packages You can restore packages by using the following package source: -`http://localhost:5000/v3/index.json` +`http://localhost:6060/v3/index.json` Some helpful guides: @@ -93,6 +98,6 @@ Some helpful guides: You can load symbols by using the following symbol location: -`http://localhost:5000/api/download/symbols` +`http://localhost:6060/api/download/symbols` For Visual Studio, please refer to the [Configure Debugging](https://docs.microsoft.com/en-us/visualstudio/debugger/specify-symbol-dot-pdb-and-source-files-in-the-visual-studio-debugger?view=vs-2017#configure-symbol-locations-and-loading-options) guide. diff --git a/docs/installation/azure.md b/docs/installation/azure.md index 0898fc95e..ee2de7266 100644 --- a/docs/installation/azure.md +++ b/docs/installation/azure.md @@ -1,19 +1,15 @@ -# Run BaGet on Azure +# Run BaGet Extension on Azure -!!! warning - This page is a work in progress! - -Use Azure to scale BaGet. You can store metadata on [Azure SQL Database](https://azure.microsoft.com/en-us/services/sql-database/), upload packages to [Azure Blob Storage](https://azure.microsoft.com/en-us/services/storage/blobs/), and provide powerful search using [Azure Search](https://azure.microsoft.com/en-us/services/search/). +Use Azure to scale BaGet Extension. You can store metadata on [Azure SQL Database](https://azure.microsoft.com/en-us/services/sql-database/), upload packages to [Azure Blob Storage](https://azure.microsoft.com/en-us/services/storage/blobs/), and provide powerful search using [Azure Search](https://azure.microsoft.com/en-us/services/search/). ## TODO * App Service -* Table Storage * High availability setup -## Configure BaGet +## Configure BaGet Extension -You can modify BaGet's configurations by editing the `appsettings.json` file. For the full list of configurations, please refer to [BaGet's configuration](../configuration.md) guide. +You can modify BaGet Extension's configurations by editing the `appsettings.json` file. For the full list of configurations, please refer to [BaGet Extension's configuration](../configuration.md) guide. ### Azure SQL database @@ -69,8 +65,24 @@ Alternatively, you can use a full Azure Storage connection string: } ``` +Package downloads are redirected to the blob through a shared access signature, valid for 10 +minutes by default. To change it, set `DownloadUriExpiry` in the `Storage` section, as a time span +such as `"00:30:00"`. + +### Azure Table Storage + +Set `"Database": { "Type": "AzureTable", "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...;EndpointSuffix=core.windows.net" }` to store package metadata in Table Storage. It only +stores packages: accounts, the catalog, validation, statistics, abuse reports, deprecation and +vulnerabilities need Azure SQL Database or another relational database. With it, `Search:Type` `Database` +is served by the table provider. + ### Azure Search +The index needs a `normalizedId` field: searchable, filterable, analyzed with BaGet Extension's exact match +analyzer (`PackageDocument` declares it). Autocomplete and version listing use it. Documents +indexed before the field existed keep working through a fallback, and gain the field the next +time a version of their package is pushed. + Update the `appsettings.json` file: ```json @@ -78,7 +90,7 @@ Update the `appsettings.json` file: ... "Search": { - "Type": "Azure", + "Type": "AzureSearch", "AccountName": "my-account", "ApiKey": "ABCD1234" }, @@ -92,23 +104,23 @@ Update the `appsettings.json` file: Publish your first package with: ``` -dotnet nuget push -s http://localhost:5000/v3/index.json package.1.0.0.nupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k package.1.0.0.nupkg ``` Publish your first [symbol package](https://docs.microsoft.com/en-us/nuget/create-packages/symbol-packages-snupkg) with: ``` -dotnet nuget push -s http://localhost:5000/v3/index.json symbol.package.1.0.0.snupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k symbol.package.1.0.0.snupkg ``` !!! warning - You should secure your server by requiring an API Key to publish packages. For more information, please refer to the [Require an API Key](../configuration.md#require-an-api-key) guide. + With [accounts](../configuration.md#accounts-package-owners-and-api-keys) on (the default) and an empty `ApiKey`, a push without a key is refused with `401`. Pass either a user API key (created on `/account/apikeys`) or a non-empty global `ApiKey`, with `-k `. See also [Require an API key](../configuration.md#require-an-api-key). ## Restore packages You can restore packages by using the following package source: -`http://localhost:5000/v3/index.json` +`http://localhost:6060/v3/index.json` Some helpful guides: @@ -119,6 +131,6 @@ Some helpful guides: You can load symbols by using the following symbol location: -`http://localhost:5000/api/download/symbols` +`http://localhost:6060/api/download/symbols` For Visual Studio, please refer to the [Configure Debugging](https://docs.microsoft.com/en-us/visualstudio/debugger/specify-symbol-dot-pdb-and-source-files-in-the-visual-studio-debugger?view=vs-2017#configure-symbol-locations-and-loading-options) guide. diff --git a/docs/installation/docker.md b/docs/installation/docker.md index 8c80f9b9b..bca2e3211 100644 --- a/docs/installation/docker.md +++ b/docs/installation/docker.md @@ -1,41 +1,54 @@ -# Run BaGet on Docker +# Run BaGet Extension on Docker -## Configure BaGet +## Configure BaGet Extension -Create a file named `baget.env` to store BaGet's configurations: +Create a file named `baget.env` to store BaGet Extension's configurations: ``` -# The following config is the API Key used to publish packages. -# You should change this to a secret value to secure your server. +# The global API Key used to publish packages. NUGET-SERVER-API-KEY is only an example: change it +# to a secret value. With accounts on, users can also push with their own keys (/account/apikeys). ApiKey=NUGET-SERVER-API-KEY +# Listen on every interface inside the container; appsettings.json binds to localhost:6060. +Kestrel__Endpoints__Http__Url=http://+:80 + Storage__Type=FileSystem Storage__Path=/var/baget/packages Database__Type=Sqlite Database__ConnectionString=Data Source=/var/baget/baget.db Search__Type=Database + +# Where the server's Settings page saves the settings it changes. Keep it in the mounted volume, +# otherwise a recreated container loses them. +SettingsOverridesPath=/var/baget/appsettings.Overrides.json + +# Logs go to the console (docker logs) and to a rolling file; the default, /app/logs, is lost with the +# container, so keep the files in the volume. +Serilog__WriteTo__File__Args__path=/var/baget/logs/baget-.log ``` -For a full list of configurations, please refer to [BaGet's configuration](../configuration.md) guide. +For a full list of configurations, please refer to [BaGet Extension's configuration](../configuration.md) guide. !!! info - The `baget.env` file stores [BaGet's configuration](configuration) as environment + The `baget.env` file stores [BaGet Extension's configuration](../configuration.md) as environment variables. To learn how these configurations work, please refer to - [ASP.NET Core's configuration documentation](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration#configuration-by-environment). + [ASP.NET Core's configuration documentation](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0&tabs=basicconfiguration#configuration-by-environment). -## Run BaGet +## Run BaGet Extension -1. Create a folder named `baget-data` in the same directory as the `baget.env` file. This will be used by BaGet to persist its state. -2. Pull BaGet's latest [docker image](https://hub.docker.com/r/loicsharma/baget): +1. Create a folder named `baget-data` in the same directory as the `baget.env` file. This will be used by BaGet Extension to persist its state. +2. Get BaGet Extension's docker image: pull the image this fork's release workflow publishes (the `DOCKER_IMAGE` repository variable, else `/baget`), or build it from the repository root: ``` -docker pull loicsharma/baget +docker build -t baget . ``` -You can now run BaGet: +The build context is the repository root: the image needs `Directory.Build.props` and `SignKey.snk` (strong naming) next to `src/`. `.dockerignore` keeps out everything else, including the local data of a developer run (`src/BaGet/appsettings.Overrides.json`, `baget.db`, `packages/`...). + +You can now run BaGet Extension: ``` -docker run --rm --name nuget-server -p 5555:80 --env-file baget.env -v "$(pwd)/baget-data:/var/baget" loicsharma/baget:latest +docker run --rm --name nuget-server -p 6060:80 --env-file baget.env -v "$(pwd)/baget-data:/var/baget" baget:latest # or :latest for the pulled image ``` ## Publish packages @@ -43,27 +56,58 @@ docker run --rm --name nuget-server -p 5555:80 --env-file baget.env -v "$(pwd)/b Publish your first package with: ``` -dotnet nuget push -s http://localhost:5555/v3/index.json -k NUGET-SERVER-API-KEY package.1.0.0.nupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k NUGET-SERVER-API-KEY package.1.0.0.nupkg ``` Publish your first [symbol package](https://docs.microsoft.com/en-us/nuget/create-packages/symbol-packages-snupkg) with: ``` -dotnet nuget push -s http://localhost:5555/v3/index.json -k NUGET-SERVER-API-KEY symbol.package.1.0.0.snupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k NUGET-SERVER-API-KEY symbol.package.1.0.0.snupkg ``` !!! warning - The default API Key to publish packages is `NUGET-SERVER-API-KEY`. You should change this to a secret value to secure your server. See [Configure BaGet](#configure-baget). + `NUGET-SERVER-API-KEY` is only the example value in `baget.env`: change it to a secret value. With an empty `ApiKey` and [accounts](../configuration.md#accounts-package-owners-and-api-keys) on, a push needs a user API key from `/account/apikeys`. See [Configure BaGet Extension](#configure-baget-extension). + +!!! info + On a server with no users, the first start creates the administrator `Admin` / `Admin1234!` (`Accounts:CreateDefaultAdministrator`); change that password at once. See [Default administrator](../configuration.md#default-administrator). + +## Tracing with Jaeger + +To see each request, push and database call as a trace, run [Jaeger](https://www.jaegertracing.io) next to BaGet Extension and +point it at Jaeger's OTLP port (see [Telemetry](../configuration.md#telemetry)): + +```yaml +services: + baget: + image: + ports: + - "6060:80" + environment: + - Telemetry__Enabled=true + - Telemetry__Otlp__Endpoint=http://jaeger:4317 + depends_on: + - jaeger + + jaeger: + image: jaegertracing/all-in-one:latest + ports: + - "16686:16686" # UI: http://localhost:16686 + environment: + - COLLECTOR_OTLP_ENABLED=true +``` + +Jaeger takes traces only: for metrics and logs set `Telemetry__Metrics__Endpoint` / `Telemetry__Logs__Endpoint` to an +OpenTelemetry Collector instead. The same keys can be changed live on the Settings page. ## Browse packages -You can browse packages by opening the URL [`http://localhost:5555/`](http://localhost:5555/) in your browser. +You can browse packages by opening the URL [`http://localhost:6060/`](http://localhost:6060/) in your browser. ## Restore packages You can restore packages by using the following package source: -`http://localhost:5555/v3/index.json` +`http://localhost:6060/v3/index.json` Some helpful guides: @@ -74,6 +118,6 @@ Some helpful guides: You can load symbols by using the following symbol location: -`http://localhost:5555/api/download/symbols` +`http://localhost:6060/api/download/symbols` For Visual Studio, please refer to the [Configure Debugging](https://docs.microsoft.com/en-us/visualstudio/debugger/specify-symbol-dot-pdb-and-source-files-in-the-visual-studio-debugger?view=vs-2017#configure-symbol-locations-and-loading-options) guide. diff --git a/docs/installation/gcp.md b/docs/installation/gcp.md index 3fc12fcdf..1a3c99a6c 100644 --- a/docs/installation/gcp.md +++ b/docs/installation/gcp.md @@ -1,10 +1,7 @@ -# Run BaGet on Google Cloud Platform - -!!! warning - This page is a work in progress! +# Run BaGet Extension on Google Cloud Platform We're open source and accept contributions! -[Fork us on GitHub](https://github.com/loic-sharma/BaGet). +Fork this repository on GitHub. Before you begin, you should decide which [AppEngine region](https://cloud.google.com/appengine/docs/locations) you will use. For best performance, Cloud Storage and Cloud SQL should be located @@ -24,7 +21,7 @@ Follow the instructions in [Using Cloud Storage](https://cloud.google.com/appeng Set up a service account and download credentials. Set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path to the JSON file you downloaded. -Configure BaGet to use Google Cloud Storage by updating the `appsettings.json` file: +Configure BaGet Extension to use Google Cloud Storage by updating the `appsettings.json` file: ```json { @@ -46,7 +43,7 @@ Configure BaGet to use Google Cloud Storage by updating the `appsettings.json` f * Follow [Configuring SSL/TLS](https://cloud.google.com/sql/docs/mysql/configure-ssl-instance#new-client) to create a client certificate. Download the three files it creates. * Convert the PEM to a PFX by running `openssl pkcs12 -inkey client-key.pem -in client-cert.pem -export -out client.pfx` * One way to obtain OpenSSL on Windows is to install [Git Bash](https://gitforwindows.org/). -* Configure BaGet to use Google Cloud SQL by updating the [`appsettings.json`](https://github.com/loic-sharma/BaGet/blob/master/src/BaGet/appsettings.json) file: +* Configure BaGet Extension to use Google Cloud SQL by updating the `appsettings.json` file: ```json { @@ -59,11 +56,11 @@ Configure BaGet to use Google Cloud Storage by updating the `appsettings.json` f } ``` -* Create the tables by running `dotnet ef database update --context MySqlContext --project src\BaGet` +* The tables are created when BaGet Extension starts (`RunMigrationsAtStartup`, on by default). ## Google AppEngine -BaGet can be hosted in Google AppEngine. See [here](https://cloud.google.com/appengine/docs/flexible/dotnet/quickstart) +BaGet Extension can be hosted in Google AppEngine. See [here](https://cloud.google.com/appengine/docs/flexible/dotnet/quickstart) for a tutorial on how to create a new AppEngine project. Create a `app.yaml` file to publish the Docker container built by the Dockerfile in this repo. In the template @@ -72,7 +69,7 @@ below, make the following replacements: * `PROJECT` - your GCP project, as returned by `gcloud config get-value project` * `REGION` -- the GCP region your Google Cloud SQL database is in, e.g., `us-central1` or `us-west2` * `DBINSTANCE` -- the name of your Google Cloud SQL database instance -* `DBNAME` -- the name of the BaGet database on that instance (e.g., `baget` in the instructions above) +* `DBNAME` -- the name of the BaGet Extension database on that instance (e.g., `baget` in the instructions above) * `PASSWORD` -- the password for the database root user * `BUCKETNAME` -- the name of the Google Cloud Storage Bucket configured above @@ -97,7 +94,13 @@ env_variables: Storage__Type: "GoogleCloud" Storage__BucketName: "BUCKETNAME" Search__Type: "Database" - ASPNETCORE_URLS: "http://0.0.0.0:8080" + Kestrel__Endpoints__Http__Url: "http://+:8080" ``` +`Kestrel:Endpoints` in `appsettings.json` takes precedence over `ASPNETCORE_URLS`, so set the Kestrel URL instead. + To publish the application, run `gcloud app deploy`. + +## Publish packages + +With an empty `ApiKey` and [accounts](../configuration.md#accounts-package-owners-and-api-keys) on (the default), a push needs a user API key from `/account/apikeys`; or set `ApiKey` (for example `ApiKey: "..."` in `env_variables`) and pass it with `-k`. See [Require an API key](../configuration.md#require-an-api-key). diff --git a/docs/installation/iis-proxy.md b/docs/installation/iis-proxy.md index 7df4b0019..08df39058 100644 --- a/docs/installation/iis-proxy.md +++ b/docs/installation/iis-proxy.md @@ -1,11 +1,11 @@ # Windows IIS Proxy -With a few extra steps you can run BaGet behind a Windows IIS proxy. This has many benefits, including automatic restarts on reboots. +With a few extra steps you can run BaGet Extension behind a Windows IIS proxy. This has many benefits, including automatic restarts on reboots. ## IIS setup -1. Install the [.NET Core Runtime](https://dotnet.microsoft.com/download) on the web server. -1. Copy the BaGet directory over to your hosting area such as `C:\Inetpub\wwwroot\BaGet` +1. Install the [.NET 10 Hosting Bundle](https://dotnet.microsoft.com/download/dotnet/10.0) on the web server, then restart IIS. Use a published build: `dotnet publish` generates the `web.config`. +1. Copy the BaGet Extension directory over to your hosting area such as `C:\Inetpub\wwwroot\BaGet` 1. Using IIS Manager, create a new Application Pool: - Name = `BaGetAppPool` (can be whatever you want) @@ -16,19 +16,19 @@ With a few extra steps you can run BaGet behind a Windows IIS proxy. This has ma 1. Using IIS Manager, create a new web site: - Choose your site name and physical path - Choose `BaGetAppPool` as the application pool - - In the Binding area, enter the default BaGet port of 5000 + - In the Binding area, enter the host name and port you want to serve. Under IIS in-process hosting the Kestrel endpoint (`localhost:6060`) in `appsettings.json` is not used. -## BaGet folder permissions +## BaGet Extension folder permissions -You **may** need to give special permissions to the top-level BaGet folder so that the app can persist its state. This is necessary as the Application Pools' identity is a virtual account that isn't recognized by the Windows User Management Console. For more information, please refer to ASP.NET Core's documentation: +You **may** need to give special permissions to the top-level BaGet Extension folder so that the app can persist its state. This is necessary as the Application Pools' identity is a virtual account that isn't recognized by the Windows User Management Console. For more information, please refer to ASP.NET Core's documentation: -* [Application Pools](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-2.2#application-pools) -* [Application Pool Identity](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-2.2#application-pool-identity) +* [Application Pools](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-10.0#application-pools) +* [Application Pool Identity](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-10.0#application-pool-identity) ## Alternative storage path !!! info - Virtual Directories do not work with IIS and Kestrel. For more information, please refer to [ASP.NET Core's documentation](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-2.2#virtual-directories). + Virtual Directories do not work with IIS and Kestrel. For more information, please refer to [ASP.NET Core's documentation](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-10.0#virtual-directories). Ensure that the configuration's storage `Path` has the appropriate forward slashes: @@ -41,8 +41,21 @@ Ensure that the configuration's storage `Path` has the appropriate forward slash ... ``` -Note that you will need to adjust folder permissions if the `Path` is created outside of the BaGet top-level directory. See the [BaGet Folder Permissions](#baget-folder-permissions). +Note that you will need to adjust folder permissions if the `Path` is created outside of the BaGet Extension top-level directory. See the [BaGet Extension Folder Permissions](#baget-extension-folder-permissions). +## API key + +With an empty `ApiKey` and [accounts](../configuration.md#accounts-package-owners-and-api-keys) on (the default), a push needs a user API key from `/account/apikeys`; or set `ApiKey` and pass it with `-k`. See [Require an API key](../configuration.md#require-an-api-key). + +## Logging under IIS + +- Logs go to `logs/baget-YYYYMMDD.log` under the site folder; give the application pool identity write access to it (see + [folder permissions](#baget-extension-folder-permissions)) or point `Serilog:WriteTo:File:Args:path` at a writable folder. + A file that cannot be written is reported on stderr (enable `stdoutLogEnabled` in `web.config` to capture it), not silently dropped. +- Warnings and errors, startup failures included, also go to the Windows **Application** event log (source `.NET Runtime`), + without administrator rights. Turn that off with `Serilog:EventLog:Enabled=false`. +- To switch a sink off, set `Serilog:WriteTo:File:Enabled` to `false` (do not rely on an empty environment variable). + See [Logging](../configuration.md#logging). ## IIS server options diff --git a/docs/installation/local.md b/docs/installation/local.md index 430c74f47..cdf7174e3 100644 --- a/docs/installation/local.md +++ b/docs/installation/local.md @@ -1,38 +1,46 @@ -# Run BaGet on your Computer +# Run BaGet Extension on your Computer -## Run BaGet +## Run BaGet Extension -1. Install the [.NET Core SDK](https://www.microsoft.com/net/download) -1. Download and extract [BaGet's latest release](https://github.com/loic-sharma/BaGet/releases) +1. Install the [.NET 10 ASP.NET Core Runtime](https://dotnet.microsoft.com/download/dotnet/10.0) (or the SDK) +1. Get BaGet Extension: download the `BaGet` workflow artifact of a release run of this repository, or publish it with `dotnet publish src/BaGet -c Release -o artifacts -p:GeneratePackageOnBuild=false`, and extract it 1. Start the service with `dotnet BaGet.dll` -1. Browse `http://localhost:5000/` in your browser +1. Browse `http://localhost:6060/` in your browser -## Configure BaGet +!!! info + On a server with no users, the first start creates the administrator `Admin` / `Admin1234!` (`Accounts:CreateDefaultAdministrator`); change that password at once. See [Default administrator](../configuration.md#default-administrator). -You can modify BaGet's configurations by editing the `appsettings.json` file. For the full list of configurations, please refer to [BaGet's configuration](../configuration.md) guide. +!!! info + The port comes from `Kestrel:Endpoints` in `appsettings.json`, which takes precedence over + `--urls`. Change it there, or override it with the `Kestrel__Endpoints__Http__Url` environment variable + (for example `http://localhost:8080`). + +## Configure BaGet Extension + +You can modify BaGet Extension's configurations by editing the `appsettings.json` file. Database migrations run at startup (`RunMigrationsAtStartup`, on by default). For the full list of configurations, please refer to [BaGet Extension's configuration](../configuration.md) guide. ## Publish packages Publish your first package with: ``` -dotnet nuget push -s http://localhost:5000/v3/index.json package.1.0.0.nupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k package.1.0.0.nupkg ``` Publish your first [symbol package](https://docs.microsoft.com/en-us/nuget/create-packages/symbol-packages-snupkg) with: ``` -dotnet nuget push -s http://localhost:5000/v3/index.json symbol.package.1.0.0.snupkg +dotnet nuget push -s http://localhost:6060/v3/index.json -k symbol.package.1.0.0.snupkg ``` !!! warning - You should secure your server by requiring an API Key to publish packages. For more information, please refer to the [Require an API Key](../configuration.md#require-an-api-key) guide. + With [accounts](../configuration.md#accounts-package-owners-and-api-keys) on (the default) and an empty `ApiKey`, a push without a key is refused with `401`. Pass either a user API key (created on `/account/apikeys`) or a non-empty global `ApiKey`, with `-k `. See also [Require an API key](../configuration.md#require-an-api-key). ## Restore packages You can restore packages by using the following package source: -`http://localhost:5000/v3/index.json` +`http://localhost:6060/v3/index.json` Some helpful guides: @@ -43,6 +51,6 @@ Some helpful guides: You can load symbols by using the following symbol location: -`http://localhost:5000/api/download/symbols` +`http://localhost:6060/api/download/symbols` For Visual Studio, please refer to the [Configure Debugging](https://docs.microsoft.com/en-us/visualstudio/debugger/specify-symbol-dot-pdb-and-source-files-in-the-visual-studio-debugger?view=vs-2017#configure-symbol-locations-and-loading-options) guide. diff --git a/docs/maven-repositories.md b/docs/maven-repositories.md new file mode 100644 index 000000000..1e167f8b9 --- /dev/null +++ b/docs/maven-repositories.md @@ -0,0 +1,105 @@ +# Maven repositories + +A local **Maven** repository is a Maven 2 repository: `mvn deploy`, dependency resolution, `maven-metadata.xml`, checksums, SNAPSHOT +builds, a release/snapshot policy. Gradle's `maven-publish` and `maven { url }` use the same protocol. A [remote](#remote-maven-repositories) Maven repository +proxies Maven Central (or any Maven repository) and a [virtual](#virtual-maven-repositories) one merges several. + +## Create and use + +| Step | How | +|---|---| +| Create | Administrators: `/admin/repositories` > *Maven* form (name, versions accepted, redeploy, snapshot builds kept; *Anonymous read*). Refused on Azure Table / Azure Search (default repository only) | +| Address | `https://host/r/{name}/maven/` (shown on the repository list and the browse page). `/maven/` of the root is never served: `default` is NuGet | +| Credentials | HTTP Basic: Maven sends the `settings.xml` `` after a `401` challenge. Password = a user API key (user name = its owner) or the global `ApiKey` (any user name) | +| Deploy | `mvn deploy` with `` (snippets on the browse and upload pages), or `mvn deploy:deploy-file` | +| Resolve | `` entry with the same `` as the ``; `mvn dependency:copy-dependencies`, `dependency:get`, Gradle | + +Maven 3.8.1+ **blocks plain-http repositories** (a built-in mirror `maven-default-http-blocker`): serve BaGet over https, or override that mirror +in `settings.xml`. + +## Protocol + +| Request | Answer | +|---|---| +| `GET`/`HEAD` file | the stored file, `X-Checksum-Sha1/Md5/Sha256` headers | +| `GET` `…/{file}.sha1` `.md5` `.sha256` `.sha512` | computed once on the way in, kept in the file's row | +| `GET` `maven-metadata.xml` (group, artifact, version level) | generated from the rows, never stored; SNAPSHOT versions list the timestamped builds (`timestamp`, `buildNumber`, `snapshotVersions`) | +| `PUT` file | stored; checksum and metadata uploads are acknowledged (they are generated); `201`. A snapshot build is stored under its timestamped name and the build number advances | +| `DELETE` file | one file with its checksums (`204`); not Maven's protocol, but what scripts use | +| Refused | `409` policy refuses the version, or a release file already exists (unless *Redeploy* is on and the caller holds Delete); `400` name outside the layout; `413` over `Maven:MaxFileBytes` (1 GiB); `403` read-only mode | + +A `.pom` deployed to a version is parsed (name, description, URL, licences, packaging, dependencies) for the pages and search; a POM that +does not parse still stores. Layout rules (`MavenNames`): ids use Maven's characters only, so a path never leaves its folder. + +## Policy (per repository, *Edit repository > Maven settings*) + +| Setting | Effect | +|---|---| +| Versions accepted | `Releases` (default), `Snapshots` or `Both`. A stricter policy deletes nothing stored | +| Redeploy releases | off: a release file is immutable (409). On: replaced by a caller who also holds Delete. Simultaneous deploys of one file are serialised per process (the loser gets 409 and the winner's file stays); several nodes on one store are not coordinated | +| Snapshot builds kept | 0 keeps all. N keeps the newest N builds of a snapshot version, deleting older ones on each new deploy; the manage page cleans up on demand | + +## Pages + +| Page | Address (under `/r/{name}/`) | Who | +|---|---|---| +| Browse | `/maven-artifacts?q=` | whoever may read the repository; lists only artifacts the visitor may read (`group:artifact`); `settings.xml` and `pom.xml` snippets | +| Artifact | `/maven-artifacts/{group}/{artifact}/{version?}` | readers of the artifact: versions, files with sizes and checksums, POM view, dependency snippets (Maven, Gradle), `mvn dependency:get` | +| Upload | `/maven-upload` | a signed-in user with Deploy (accounts on), or the API key typed into the form (accounts off): coordinates, packaging, classifier, file | +| Manage | `/maven-manage/{group}/{artifact}` | owners and administrators: owners, delete a file / a version / the artifact (password), snapshot clean-up | + +Maven pages are 404 in a NuGet or npm repository and the other formats' pages are 404 in a Maven one. Access patterns (grants, include/exclude) +see the artifact as `group:artifact`. Writes are refused (503) while a database copy has the maintenance gate closed. + +## Storage and data + +Files: `maven/{group}/{artifact}/{version}/{file}` under the repository's prefix (`repos/{name}/` as for every non-default repository). +Tables `MavenArtifacts`, `MavenVersions`, `MavenFiles` (repository-scoped; migration `AddMavenTables`, all four providers). Owners are the +common `PackageOwner` rows keyed by `group:artifact`. + +## Remote Maven repositories + +A remote Maven repository caches an upstream: Maven Central (`https://repo.maven.apache.org/maven2/`), another BaGet, Artifactory, Nexus. Create it at `/admin/repositories` > *New remote repository* > format *Maven*; the settings (URL, credentials, cache periods, offline, *store locally*, download timeout), *Test connection*, the cache table and both purges are those of [remote repositories](remote-repositories.md#maven-remote-repositories). Point `settings.xml` at it with a `` of `central` (or of `*`, which also sends plugins through it); the browse page shows the snippet. + +| Request | Result | +|---|---| +| File (`GET`) | Stored: served from storage with its checksums (also while the upstream is down). Else downloaded, hashed while written to a temporary file, compared with the checksum the upstream publishes (`.sha1`, else `.sha256`, else `.md5`; a mismatch is neither stored nor served: `502`), stored, served. An `HTML` page answered `200` for a missing file is a `404` | +| `HEAD` | Stored: as for a local repository. Else the upstream is asked for the headers only; nothing is downloaded or kept | +| Checksum of a file not stored yet | The upstream's, remembered like metadata; the file is not downloaded for it | +| `maven-metadata.xml` (artifact, version, group level: plugin prefixes resolve too; a group's plugin list is judged by the repository's Read, not by an artifact named like the group's last folder) and its checksums | The upstream's, cached for the metadata period (`404` for the negative period; an expired one while the upstream is down). Else generated from the versions this repository stored; else `502` (down) or `404` | +| `-SNAPSHOT` | A timestamped build is immutable and kept. The moving name (`lib-1.0-SNAPSHOT.jar`) is always streamed from the upstream and never kept; a stored build answers it only while the upstream cannot. Use a metadata period of `0` to see a new build at once | +| `PUT`, `DELETE` | `403` (`401` without credentials): a remote repository takes no changes. The release/snapshot policy does not apply: whatever the upstream has is served | +| Pages and search | The **stored** artifacts only (browse, artifact page); no owners or *Manage* | +| Private repository | The upstream is not asked (not even to tell a version's metadata from an artifact's) for a caller who may not read the repository | + +Files are ordinary Maven rows and files (`repos/{name}/maven/…`), so counting, search, access, the delete guard and the database copy need nothing new. Metadata and checksum answers are remembered **in memory** per node. + +## Virtual Maven repositories + +A virtual repository of format Maven merges Maven repositories (`/r/{name}/maven/`). Members are read in their own scope (storage, upstream and access rules), only those the caller may read; a member that fails is skipped. + +| Request | Result | +|---|---| +| File and its checksums | The first member that has it, so a file and its checksum always agree | +| Artifact `maven-metadata.xml` | `versions` is the union (Maven's ordering); `latest` and `release` are the first member's own that the merged list contains (**member order**, not the highest version; the highest when no member names one); `lastUpdated` the latest. Its checksums describe the merged document | +| Version `maven-metadata.xml` (snapshot builds) | The first member's that has it (the builds it names are that member's files) | +| Group `maven-metadata.xml` (plugin prefixes) | The union of the members' plugins, a prefix once (first member wins) | +| `PUT`, `DELETE`, upload | **Moved to the deploy repository** before authorization (its rules and the caller's rights there); without one `403` | +| Pages, search | Merged by `group:artifact`; *Manage* is `404` (use the member) | + +The *Where would a package come from?* preview takes `group:artifact` and any Maven version (`5.3.20.RELEASE`). See [virtual repositories](virtual-repositories.md#maven-virtual-repositories). + +## Tests + +`MavenLayoutTests` (Core), `MavenRepositoryTests`, `MavenPagesTests`, `RemoteMavenRepositoryTests`, `VirtualMavenRepositoryTests`, `AdminMavenRemoteVirtualTests` (`BaGet.Tests`, the upstream is the in-memory `FakeMavenUpstream`), and `MavenCliTests` (`BaGet.Clients.Tests`): the real +`mvn` 3.9 in `maven:3.9-eclipse-temurin-21` deploys and resolves releases and snapshots, hits the 409 rules, and signs in to a private +repository with `settings.xml` credentials. They skip without Docker and need the internet (the plugins come from Maven Central). + +`MavenRemoteVirtualCliTests` (`BaGet.Clients.Tests`): the real `mvn` against a remote repository whose upstream is a second real BaGet (releases, timestamped snapshots, upstream gone, `502`, deploy refused), a virtual repository, and, with the internet, the real Maven Central through a `*` mirror (plugins and prefix metadata included). + +## Vulnerability scanning + +With `Scanning:Enabled`, each stored version and the compile and runtime dependencies of its POM that state a literal version are +checked against OSV. A policy can refuse the files of a version (`403`, plain text; `maven-metadata.xml` stays readable) and a +deploy whose artifact or POM dependencies have findings (nothing stored). See [vulnerability scanning](vulnerability-scanning.md). +Tests: `ScanningMavenTests`. diff --git a/docs/npm-registry.md b/docs/npm-registry.md new file mode 100644 index 000000000..12cf281f7 --- /dev/null +++ b/docs/npm-registry.md @@ -0,0 +1,111 @@ +# npm registry + +A local **npm** repository is an npm registry: `npm publish`, `npm install`, dist-tags, deprecate, unpublish, search, `npm login`. +A **remote** npm repository proxies an upstream registry such as registry.npmjs.org ([details](remote-repositories.md#npm-remote-repositories)); a **virtual** one merges several npm repositories ([details](virtual-repositories.md#npm-virtual-repositories)). + +## Create and use + +| Step | How | +|---|---| +| Create | Administrators: `/admin/repositories` > *npm* form (a name; *Anonymous read* chosen there). *New remote repository* / *New virtual repository* with the format *npm* for the other kinds. Refused on Azure Table / Azure Search (default repository only) | +| Registry address | `https://host/r/{name}/npm/` (shown on the repository list and the browse page). `/npm/` of the root is never served: `default` is NuGet | +| Point npm at it | `npm config set registry https://host/r/{name}/npm/`, or only a scope: `@acme:registry=https://host/r/{name}/npm/` in `.npmrc` | +| Sign in | `npm login --registry=…` (user name and password, accounts on) or `//host/r/{name}/npm/:_authToken=` in `.npmrc` (any user API key, or the global `ApiKey`) | +| Publish / install | `npm publish`, `npm install pkg`, `npm install @scope/pkg@tag`, `npm view`, `npm search`, `npm ping`, `npm whoami`, `npm logout` | + +`npm login` calls `POST /-/v1/login` (web login, answered 404 so npm falls back) and then +`PUT /-/user/org.couchdb.user:NAME` with the password. The answer is a token: **an API key of the user, limited to this +repository**, named `npm login (name)`, no expiry; it appears on *Account > API keys* and `npm logout` (or *Revoke*) deletes it. +Refused: wrong password, a locked-out account (429), an unconfirmed email, an account with two-factor authentication (use an +API key from the account page instead). Without accounts (`Accounts:Enabled` off) login answers 501: use the global key as the token. +Login never creates an account. On a **virtual** repository the token is limited to that repository plus its members and deploy repository (so it reads through it and pushes to the deploy repository); logout and login are never moved to the deploy repository. The logout request names the token in its path; the request log and traces show `Redacted` in its place. + +## Pages + +| Page | Address (also under `/r/{name}/`) | Who | +|---|---|---| +| Browse and search | `/npm-packages?q=` | whoever may read the repository; lists only packages the visitor may read | +| Package | `/npm-packages/{name}?version=` (scoped: `/npm-packages/@scope/name`) | readers of the package: readme, versions, dist-tags, dependencies, `npm install` / `yarn` / `pnpm` commands, `.npmrc` lines, tarball link, owners | +| Upload | `/npm-upload` | a signed-in user with Deploy (accounts on), or the API key typed into the form (accounts off) | +| Manage | `/npm-manage/{name}` | owners and administrators: owners, dist-tags, deprecate / remove deprecation, unpublish a version or the package | + +The front page of an npm repository (`/r/{name}/`, the header, the repository switcher) leads to *Browse*. The NuGet pages +(`/packages`, `/upload`, `/statistics`) are 404 there, and npm pages are 404 in a NuGet repository. +*Unpublish* asks for the password again. Writes are refused (503) while a database copy has the maintenance gate closed, and in +read-only mode. + +## Rules + +| Topic | Rule | +|---|---| +| Names | `left-pad` or `@scope/name`, lower case (to publish; reading, and proxying a remote repository, also accept npm's legacy upper case names such as `JSONStream`), at most 214 characters, `a-z 0-9 . _ ~ -`, not starting with `.`, `_` or `-`; `node_modules` and `favicon.ico` reserved. An encoded `@scope%2fname` and `@scope/name` are the same package | +| Versions | semantic versions only (`1.0.0`, `1.0.0-rc.1`, `1.0.0+build`); build metadata does not make a version different, nor does the case of the prerelease label (`1.0.0-Beta` is `1.0.0-beta`) | +| Publish | `PUT /{name}`: the body carries the tarball as base64. It is streamed to a temporary file and decoded to another, never held in memory. Refused (400, nothing stored) when the declared `integrity` (sha512), `shasum` (sha1) or `length` differ from the bytes, when the tarball has no `package.json` or it names another package or version, when the tag is missing or looks like a version. `409` for a published version (publishes of one version are serialized per process, so a loser never replaces the winner's file). The install fields (`dependencies`, `bin`, `os`, `cpu`, `engines`, `scripts`-derived `hasInstallScript`...) are taken from the tarball's own `package.json`, not from the request's manifest. Exception: a `scripts.install` of exactly `node-gyp rebuild` (with `gypfile`) and a `bin` for a tarball that declares only `directories.bin` are kept from the request, as npm adds them when packing. Size limit `Npm:MaxPublishBytes` (413); the document apart from the tarballs (manifest, readme) is held in memory and limited to 64 MiB (413) | +| First version | always gets the `latest` tag, whatever tag it was published with. Later publishes move only the tag they name | +| Ownership | the first publisher of a name owns it (organizations can own); only owners (and administrators) publish versions, tag, deprecate, unpublish. An administrator's push does not take the name over. A name published before accounts has no owner: only the global key and administrators change it | +| Access model | Read for browsing, installing, searching; **Deploy** to publish and to change dist-tags; **Annotate** to deprecate; **Delete** to unpublish after the window. Package patterns of grants apply to the decoded name. API key scopes: `package:push` publishes new names, `package:pushversion` only new versions of owned names, `package:unlist` deprecates and unpublishes after the window | +| Dist-tags | `latest` stays pointed somewhere: removing a version re-points tags with the client's list, `latest` falls back to the highest stable version. A tag cannot be a version | +| Deprecate | `npm deprecate pkg@range "message"` sets the message of each version; an empty message clears it | +| Unpublish | see below | +| Search | `/-/v1/search` and the page match the package **name**; a listing never names a package its caller cannot read | +| Audit | `npm audit` / the audit step of `npm install` get "no advisories" (findings are shown on the package pages and enforced on download/publish, see [vulnerability scanning](vulnerability-scanning.md); the audit endpoints stay empty) | +| Writes need an API key | a Bearer token, Basic password or `X-NuGet-ApiKey`; never the browser session cookie | + +### Unpublish policy + +Same shape as npmjs, with the permission model of this server: + +| Case | Needs | +|---|---| +| A version published less than `Npm:UnpublishWindow` ago (default **72 hours**), or a package whose every version is that young | the owner's **Deploy** and a key with `package:push` (a key limited to `package:pushversion` never deletes: it needs `package:unlist` and Delete like an old version) | +| Anything older | **Delete** on the package, ownership (or administrator) and `package:unlist` | +| `UnpublishWindow` zero or negative | always Delete | + +The tarball is deleted with the version; the number can be published again (npmjs forbids that for ever; here a deleted version +is deleted, as in the NuGet feed). Unpublishing the last version removes the package (its owners are kept, like a NuGet id's). +`npm unpublish pkg@1.0.0` is `PUT /{name}/-rev/{rev}` (the packument without the version) then `DELETE /{name}/-/{file}/-rev/{rev}`; +`npm unpublish pkg --force` is `DELETE /{name}/-rev/{rev}`. The revision is not checked. + +## Routes (below `/r/{name}/npm/`) + +| Route | Does | +|---|---| +| `GET {name}` | packument (`Accept: application/vnd.npm.install-v1+json` gets the install-only form) | +| `GET {name}/-/{file}` | tarball (ETag = integrity) | +| `PUT {name}` | publish (with `_attachments`) or deprecate (a packument without attachments; only `deprecated` can change) | +| `PUT\|DELETE {name}/-rev/{rev}`, `DELETE {name}/-/{file}/-rev/{rev}` | unpublish steps | +| `GET -/package/{name}/dist-tags`, `PUT\|DELETE …/dist-tags/{tag}` | dist-tags (body of PUT: the version as a JSON string) | +| `GET -/v1/search`, `-/ping`, `-/whoami` | search, ping, user name of the token | +| `POST -/v1/login` (404), `PUT -/user/org.couchdb.user:{user}`, `DELETE -/user/token/{token}` | login, logout | +| `POST -/npm/v1/security/advisories/bulk`, `…/audits/quick` | no advisories | + +A scoped name is also accepted as two segments (`@scope/name`) on every route that names a package. Every route is a 404 in a repository that is not npm. Names are case-sensitive on every database (legacy names such as `JSONStream` differ from `jsonstream`). In a private repository a caller without Read gets `404 Not found` from every change route, whether the package exists or not. + +## Configuration + +| Key | Default | Meaning | +|---|---|---| +| `Npm:UnpublishWindow` | `72:00:00` | see above. Live | +| `Npm:MaxPublishBytes` | `536870912` (512 MiB) | largest publish request body (a tarball is about 3/4 of it); `0` = no limit beyond the web server's. Live | + +The web server's own body limit applies as well (the shipped host turns Kestrel's `MaxRequestBodySize` off; IIS has its own caps, see [formats](formats.md#streaming-storage-b2)). + +## Storage and data + +Tarballs: `npm/{name}/-/{file}` below the repository's storage prefix (`repos/{name}/` for repositories other than `default`). +Tables `NpmPackages`, `NpmVersions`, `NpmDistTags` ([formats](formats.md#data-model-b1)); the manifest of each version is kept as +published (without the tarball address, which is built from the request), except the install fields, which come from the tarball's `package.json`, so the packument cannot promise what `npm install` will not run. + +## Tests + +`BaGet.Clients.Tests` runs the real npm 10 in `node:22-alpine` against the real application on a socket (needs Docker; +skipped otherwise): publish, install, scoped names through `%2f`, dist-tag, deprecate, unpublish, search, ping, whoami, audit, +login (npm's own login library; `npm login` needs a terminal), logout, a private repository, a 40 MB tarball with bounded +server allocations. The protocol, access, pages and parser are covered in `BaGet.Tests` (`NpmRegistryTests`, +`NpmAccessTests`, `NpmPagesTests`) and `BaGet.Core.Tests` (`NpmPublishBodyTests`). + +## Vulnerability scanning + +With `Scanning:Enabled`, each stored version and its dependencies that name one exact version are checked against OSV. A +policy of the repository can refuse the tarball download (`403 {"error": reason}`) or the publish (`403`, nothing stored); the +packument stays readable. See [vulnerability scanning](vulnerability-scanning.md). Tests: `ScanningNpmTests`. diff --git a/docs/readme.md b/docs/readme.md deleted file mode 100644 index c962291d9..000000000 --- a/docs/readme.md +++ /dev/null @@ -1,2 +0,0 @@ -Please use the [documentation website](https://loic-sharma.github.io/BaGet/) -for the best browsing experience. \ No newline at end of file diff --git a/docs/remote-repositories.md b/docs/remote-repositories.md new file mode 100644 index 000000000..13840049d --- /dev/null +++ b/docs/remote-repositories.md @@ -0,0 +1,85 @@ +# Remote repositories + +A **remote** repository caches another feed: a NuGet feed (nuget.org, another BaGet, Artifactory, Azure Artifacts, ...) an [npm registry](#npm-remote-repositories) (registry.npmjs.org, Verdaccio, Artifactory, another BaGet, ...) a [Maven repository](#maven-remote-repositories) (Maven Central, Artifactory, Nexus, another BaGet, ...) or a [Docker registry](#docker-remote-repositories) (Docker Hub, GHCR, Quay, ...). A package it does not hold is fetched from the upstream the first time it is requested, stored, and served from there afterwards. Its feed is `/r/{name}/v3/index.json` (npm: `/r/{name}/npm/`, Maven: `/r/{name}/maven/`, Docker: `/v2/{name}/{image}`) like any repository's; clients cannot push to it. + +## Create and edit + +Administrators: `/admin/repositories` > *New remote repository* (pick the **format**: NuGet, npm, Maven or Docker); later `/admin/repositories/{name}` (needs a relational database and accounts, like all [repository pages](repositories.md#admin-pages)). + +| Setting | Default | Meaning | +|---|---|---| +| Upstream URL | required | A V3 `index.json` URL or a V2 feed URL; for npm the registry's base URL (`https://registry.npmjs.org/`); for Maven the repository root (`https://repo.maven.apache.org/maven2/`); for Docker the registry's address (`https://registry-1.docker.io`). Absolute `http`/`https`, no credentials inside | +| Protocol | V3 | NuGet: `V3` or `V2`. npm, Maven and Docker repositories speak their own protocol only: the form does not ask, and saving always keeps it | +| User name / password | none | HTTP Basic, sent to the upstream's own host only, never to hosts a service index or redirect points to. A token goes in the password; an **npm** upstream with a password and no user name gets it as a bearer token (npm's `_authToken`). Stored protected with ASP.NET Core data protection (the host's key ring; back it up with the host), never shown again, never logged. Blank on save or on *Test connection* keeps the stored one while the URL's scheme/host/port and the user name are unchanged (one rule for both) (on the `mirror` repository only the origin counts: `Mirror:*` never sets a user name, so a changed timeout, `Legacy` or URL path keeps it; otherwise it is dropped and a new one must be typed); *Remove the stored password* clears it. A host without data protection refuses to store a password | +| Metadata cache period | 600 s | How long the upstream's version lists and metadata are reused. `0` asks every time. An expired answer is still served when the upstream cannot be reached | +| Negative cache period | 60 s | How long a `404` from the upstream is remembered. A failure to reach the upstream (network, 5xx, 401) is never remembered as "not found" | +| Download timeout | 600 s | Per HTTP request (V3 only; a V2 upstream is contacted by NuGet's own HTTP stack, with its default timeout) | +| Store artifacts locally | on | On: packages are stored (database and files) on first request; they and their local metadata are served while the upstream is down. Off: **pass-through**: metadata and downloads come from the upstream each time and nothing is kept, so search and the package pages stay empty | +| Who may read it (create form; later *Anonymous read*) | default | *Default*: anonymous requests may read it unless a user name or password is set (then signed-in users with Read only), so a credentialed upstream is never served to anyone by accident; *Anyone* / *Only callers the access model allows* override. The edit page warns when a repository with a stored password is anonymously readable. The auto-created `mirror` repository is anonymously readable like `default`, whose fetches it serves; give it credentials and decide again | +| Offline mode | off | The upstream is never contacted: only stored packages and remembered answers are served | + +The cache lives in the repository: cached packages are ordinary package rows of the remote repository (in `repos/{name}/` in storage), isolated from every other repository, and browsable through the repository-aware pages (`/r/{name}/`, `/r/{name}/packages/{id}`, search). + +## What a client sees + +| Request | Result | +|---|---| +| Version list, registration | Upstream's versions merged with the stored ones; cached for the metadata period | +| Package, `.nuspec` download | Stored copy, else fetched, stored (indexed like a push, never validated) and served; pass-through streams it | +| Push, symbol push (`PUT`) | `403`: the access model never grants *Deploy* on a remote repository, not even to administrators; the browser upload page does not list it | +| Delete, unlist, deprecate | Allowed per the access model (evict a cached package) | +| Read | As for any repository: [access control](access-control.md) | +| Unknown package | `404`, remembered for the negative period | + +## Test connection, cache and purge + +On `/admin/repositories/{name}`: + +| Control | Does | +|---|---| +| *Test connection* | Asks the upstream with the values in the form, saved or not (blank password = the stored one, if the URL's origin and user name are unchanged), and saves nothing. V3: the URL must answer a service index (at most 1 MB is read); V2: any success; npm: `{url}/-/ping`, and `{url}` itself where there is no ping (any success); Maven: the repository root; Docker: `GET /v2/` through the token flow. Redirects are followed only within the same origin (at most 5), never to another host. Shows the HTTP status and time; failures say which (refused credentials, HTTP status, unreachable) without URLs or credentials | +| Cache table | Stored package versions and ids; remembered answers; hits, upstream requests, `404`s answered from memory, expired answers served; the upstream's health (last answer, failing since, last error). Counters and remembered answers are per node and reset at restart | +| *Purge cache* | Deletes every stored package (database and files) and drops the remembered answers. Audited | +| *Purge package* | The same for one package id (npm: package name, `@scope/name`; Maven: `group:artifact`, any version text such as `5.3.20.RELEASE`), one version or all of them. Audited | +| *Browse the cached packages* | The repository's browse page (NuGet: front page; npm: `/npm-packages`; Maven: `/maven-artifacts`; Docker: `/docker-images`) | + +Creating a remote repository, saving its upstream, *Test connection* and both purges **ask for your password again** (or a recent sign-in with the external provider, for an account without a password): a test saves nothing but makes the server send a request to a typed URL. The stored password is sent by *Test connection* only while the URL's origin and user name are unchanged (the rule saving applies), so testing another host never hands it to that server. A remote repository with cached packages cannot be deleted until its cache is purged. Creating, editing and purging are refused with `503` while the server is read-only for maintenance (for example during a [database copy](configuration.md)). + +## npm remote repositories + +An npm repository of kind remote proxies an upstream registry: `npm install` against `/r/{name}/npm/` behaves as against the upstream, but every tarball is downloaded through (and kept by) this server. Same settings as above (URL, credentials, metadata and negative periods, offline, *store locally*, timeout, `Remote:BlockPrivateAddresses`), same pages and password rules. + +| Request | Result | +|---|---| +| Packument (`GET /{name}`, scoped `@scope%2fname` or `@scope/name`) | The upstream's document (install-only form when the client asks for it), cached for the metadata period, with **every `dist.tarball` rewritten** to this repository. `404` from the upstream is remembered for the negative period. A version that is not a semantic version is dropped (this server could not serve its tarball name) | +| Upstream down, refusing the credentials or sending something else | An expired remembered answer is served; else what this repository stored (the downloaded versions only, `latest` = the highest of them); else `502 Bad Gateway` with a message without URL or credentials (npm retries it; a `404` would be believed). Never remembered as "not found" | +| Tarball | A stored version is served from storage (also while the upstream is down). Otherwise it is downloaded from the upstream (the packument's own URL when it is on the upstream's origin, else `{url}/{name}/-/{file}`; credentials go to that origin only), hashed while it is written to a temporary file, **checked against the `integrity` / `shasum` the upstream announced** (a mismatch is neither stored nor served: `502`), then stored with its package and version rows and tags and served. Concurrent requests for one version download it once. *Store locally* off: the download is streamed through and nothing is kept | +| Offline mode | The upstream is never contacted: remembered answers and stored versions only; anything else is `404` | +| `npm publish`, dist-tag, deprecate, unpublish | `403` (`401` without credentials): a remote repository takes no changes | +| `npm search` | Searches the **stored** packages only; a registry's catalogue is not searched through a cache | +| `npm audit` | "No advisories", as for every repository (the findings of [vulnerability scanning](vulnerability-scanning.md) are on the package pages, not in the audit endpoint) | + +What is kept (a copy cached earlier under another spelling of the version, by case or build metadata, is replaced by the upstream's spelling on the next request for it): a stored version is an ordinary npm version row (manifest, checksums, deprecation, upstream publish time) and its tarball under `repos/{name}/npm/`; the packument itself is **remembered in memory only**, per node (at most 1000 answers per repository, 128 MB each), so after a restart with the upstream down the packument lists only the stored versions. The cache table counts stored versions and packages. Each tarball fetch emits the `mirror.fetch` span (package, version, result; never a URL or credential), as a NuGet mirror fetch does. A tarball is cached under the upstream's exact version spelling only: a file name with other build metadata is a `404` (it used to cache a second copy that the real URL could not reach). + +## Maven remote repositories + +A Maven repository of kind remote proxies an upstream Maven repository, with the settings above (HTTP Basic credentials, metadata and negative periods, offline, *store locally*; the V3/V2 choice does not exist). *Test connection* asks the repository root: `2xx` is connected; `404` is reported as connected with a note (many repositories list nothing at their root); `401`/`403` is a refusal of the credentials. Behaviour per request (files, checksums verified against the upstream's, metadata, snapshots, offline, `502`) is in [Maven repositories](maven-repositories.md#remote-maven-repositories). The cache table counts stored versions and artifacts; *Purge package* takes `group:artifact` and optionally one version (which also drops the remembered version list). + +## Docker remote repositories + +A Docker repository of kind remote is a pull-through cache of an upstream registry (`docker pull host/{repo}/{image}`), with the settings above (credentials, metadata and negative periods, offline, *store locally*, `Remote:BlockPrivateAddresses`). Credentials follow the registry's token flow (Basic at the token service the registry names, or a bearer token as a password with no user name); a layer is streamed to the client while it is kept; Docker Hub's official images are asked for under `library/`. *Test connection* does the version check through the token flow; *Purge package* takes an image name and optionally a tag or digest; the cache table counts manifests, images and layer bytes. Behaviour per request is in [Docker registry](docker-registry.md#remote-docker-repositories). + +## Upstream addresses (SSRF) + +An upstream URL makes **this server** request whatever the administrator typed: loopback, internal services, link-local addresses such as the cloud metadata endpoint `169.254.169.254`. Only administrators can create or edit remote repositories, and internal feeds are a normal use, so private addresses are **allowed by default**. If your administrators are less trusted than the host, set [`Remote:BlockPrivateAddresses`](configuration.md#remote-repositories-refuse-private-upstreams) to `true`: creating, saving and testing then refuse such upstreams, and every V3 connection re-checks the address it actually connects to (so DNS changes and redirects cannot get around it). Whatever the setting, *Test connection* never follows a redirect to another host and reads at most 1 MB (a Docker registry is probed by its own client, which follows a registry's redirects as a pull does, every connection checked against the setting). + +## The mirror + +`Mirror:Enabled` (see [configuration](configuration.md#enable-read-through-caching)) keeps working unchanged: the default repository fetches from `Mirror:PackageSource`, stores the packages in itself and asks the upstream every time. At startup the **`mirror`** remote repository is created from `Mirror:*` (or its URL, protocol and timeout are brought in line with them) and the default repository fetches **through its settings**, so credentials, an offline switch or cache periods set on `mirror` apply to the default repository too. Its URL, protocol and timeout stay owned by `Mirror:*` (read-only on the page). Packages mirrored into `default` are default packages; `mirror` has its own (initially empty) cache at `/r/mirror/`. If a *local* repository (or one of another format) is already named `mirror`, it is left alone and `Mirror:*` is read directly. + +!!! note + Replace `IRemoteHttpClientFactory` to change how upstreams are contacted (proxy, certificates). Registering your own `HttpClient` no longer affects mirroring. V2 upstreams do not go through the factory: NuGet.Protocol contacts them itself (no proxy/certificate hook, the download timeout does not apply, credentials are given to NuGet's source credential for that host), with NuGet's on-disk HTTP cache switched off so the metadata period and *Purge cache* govern. + +## Not covered yet + +A remote repository can be a member of a [virtual repository](virtual-repositories.md) (an ordered group behind one URL); `default` with the mirror behaves as one, see [`default` and the mirror](virtual-repositories.md#default-and-the-mirror). Azure Table and `Search:Type` = `AzureSearch` serve the default repository only, so remote repositories cannot be created there. npm, Maven and Docker remotes are tested against in-memory upstreams and a second BaGet (and, when the machine is online, registry.npmjs.org or Maven Central); other registries are covered by the protocol rules above only. Retention policies can limit a remote cache (`CacheLimitBytes`, see [retention](retention.md)). diff --git a/docs/replication.md b/docs/replication.md new file mode 100644 index 000000000..ec0ed558a --- /dev/null +++ b/docs/replication.md @@ -0,0 +1,71 @@ +# Replication + +A replication copies a **local repository** to (push) or from (pull) a repository of **another BaGet server**, in the same +format, through that format's own protocol. Everything is in **Admin > Replication** (`/admin/replication`) and +`/api/v1/replication`; administrators only. Needs a relational database (not Azure Table). + +## A replication + +| Setting | Meaning | +|---|---| +| Local repository | a **local** repository (remote caches an upstream, virtual stores nothing) | +| Direction | **push**: this repository is the source; **pull**: the peer's repository is the source | +| Peer address, peer repository | the other server's base address (`https://other.example/`) and its repository (`default` or a name); same format, and for a push it must be local | +| Peer API key | an **administrator's key with the `admin:api` scope** on the peer (the inventory is an admin API call; deploy rights follow from being an administrator); required, even for a pull | +| Enabled | a disabled replication never runs (manual runs refused) | +| On deploy | push only: a few seconds after the last package/version/file/tag stored in the local repository, a run starts | +| Repeat every N minutes | schedule, counted from the later of the last run and the moment it was set | +| Delete propagation | delete at the target what **this replication copied** and the source has since deleted; nothing else is ever deleted | +| Conflict | both sides hold the item with different content: **target wins** (kept, logged) or **source wins** (source's copied over the target's; a push deletes the peer's copy first except for Docker, see below) | + +The key is stored protected (the remote-repository password mechanism) and sent as a bearer token to the peer's address +only; no page, API answer, log or audit entry shows it. Changing the peer's address drops the stored key unless a new one +is typed. `Remote:BlockPrivateAddresses` applies to peer addresses like to upstreams. Changing the repository, direction or +peer clears the record of what was copied. + +## What is copied + +| Format | Item | Protocol used | Conflict detection | +|---|---|---|---| +| NuGet | package version | `PUT api/v2/package` (push), flat container `.nupkg` then the normal submit pipeline (pull) | none: same id (any case) and version = same package | +| npm | version, with the dist-tags that point at it | `PUT {name}` with the tarball streamed from a temp file (push), packument + tarball (pull) | tarball `integrity` | +| Maven | one **file** of a version (jar, pom, ...); metadata and checksums are generated | `PUT`/`GET`/`DELETE` of the file path | SHA-256 | +| Docker | a **tag**: manifest/index, child manifests, missing blobs | `HEAD`/`POST ...?digest=`/`PUT manifests` (push), `GET` (pull) | manifest digest | + +Layers and tarballs are streamed (spooled to temporary files), never held in memory. A blob the receiver holds is not sent. +Referrers and untagged manifests travel only when a copied index names them. + +The peer's API key goes to the peer's own origin only: the connection does not follow redirects by itself, and a `GET`/`HEAD` redirect is followed by BaGet with the key only when the target is the same origin (never from https to http); other redirects fail the item. + +A **pull** is subject to the receiving repository's [scanning policy](vulnerability-scanning.md) like a push: a NuGet package or Docker image that reaches the *block deploy* threshold is not kept (a failed item with the reason in the run's detail). npm and Maven pulls are checked by the same rule. + +With *source wins*, a pull **replaces** the local copy only after the peer's item is fetched and accepted (integrity, scanning policy): a refused or failed replacement keeps what was there (a Docker tag simply moves, and a refused image puts the previous manifest back). A push moves a Docker tag in place (the manifest `PUT`), so nothing is deleted at the peer first. For NuGet, npm and Maven the peer refuses to overwrite a stored version or release file (`409`), so a push deletes the peer's copy first and a peer that then refuses the item (scanning policy) is left without it until the next run. + +## Runs, log, interruption + +A run lists both sides (`GET /api/v1/replication/inventory/{repository}` on the peer), plans (copy what the target lacks, +skip what it holds, apply the conflict rule, propagate deletes; an item the target changed after it was copied, by digest, is deleted only under `SourceWins`, else forgotten), executes and writes a **log entry**: status +(`Running`, `Succeeded`, `Failed`, `Interrupted`), counts (examined, copied, skipped, deleted, conflicts, failed), bytes and the +first failures and conflicts. One item failing is logged and the run goes on; a **peer that cannot be reached** +ends the run as `Failed` (not one failure per item). Stopping a run, stopping the server, or a read-only server ends it as +`Interrupted`; a process that died leaves a `Running` entry that the worker marks `Interrupted` (when no node holds its lease). + +**Resume** is simply another run: it plans from what both sides hold now, so what was copied is skipped and the rest is copied +(the new entry names the one it continues). Each copied item is recorded as it goes, so progress survives any interruption. + +One run per replication at a time (`IJobLease`, name `replication:{key}`; the default holds it in this process only, the +high-availability phase replaces it with a cluster-wide lock). Runs and the worker (every 15 s) are idle while the server +is read-only. + +## Pages and API + +| Page / endpoint | Does | +|---|---| +| `/admin/replication` | list, create (password) | +| `/admin/replication/{id}` | settings (save with password), **Test connection** (password, saves nothing), **Run now** / **Resume** (password), **Stop**, the log, delete (password) | +| `GET/POST /api/v1/replication/configs`, `GET/PUT/DELETE .../{key}` | list, create, show, replace, delete | +| `POST .../configs/{key}/run`, `.../resume`, `.../stop`, `POST .../test` | start, resume, stop, test | +| `GET .../configs/{key}/runs`, `GET .../runs/{key}` | the log | +| `GET .../inventory/{repository}` | what a repository holds (`summary=true`: the count); what a peer calls | + +See [Administration REST API](admin-api.md) for keys and confirmation, and [UI coverage](ui-coverage.md). diff --git a/docs/repositories.md b/docs/repositories.md new file mode 100644 index 000000000..46fcc5829 --- /dev/null +++ b/docs/repositories.md @@ -0,0 +1,52 @@ +# Repositories + +A server holds one or more named repositories. Each has its own packages, owners, catalog and validations. + +| Repository | Feed | +|---|---| +| `default` | `/v3/index.json` (unchanged; every existing install is this one) | +| any other | `/r/{name}/v3/index.json` | + +Local, [remote](remote-repositories.md) (upstream cache) and [virtual](virtual-repositories.md) (ordered group of members) repositories can be created for NuGet, [npm](npm-registry.md), [Maven](maven-repositories.md) and [Docker](docker-registry.md) (the [format layer](formats.md) is how formats plug in). A Docker repository is addressed as `/v2/{name}/{image}` at the server root, not under `/r/{name}/`. + +## Web pages + +The web pages work in every repository: the package list, package, statistics, report-abuse, manage, contact-owners, profile and upload pages are at their usual address for `default` and under `/r/{name}/` for any other (`/r/{name}/packages`, `/r/{name}/upload`, ...). Links on a page stay in the repository being browsed. + +| Where | What | +|---|---| +| Header | A *Repository* menu appears on those pages when more than one repository is readable; it goes to the front page of the chosen one. Hidden with a single repository, and always with Azure Table or `Search:Type` = `AzureSearch` (only `default`) | +| Upload | `/r/{name}/upload` publishes to `{name}`; the page lists the repositories you can publish to and shows the push commands of the one open | +| My packages | The packages you own, grouped by repository | +| `/admin/repositories` | *Browse* and *Upload* links per repository | +| Service index | Each repository advertises its own `PackageDetailsUriTemplate` and `ReportAbuseUriTemplate` | + +## Admin pages + +Administrators manage them at `/admin/repositories` (menu: *Repositories*). Other users and anonymous requests get `404` or the sign-in page. + +| Page | Does | +|---|---| +| `/admin/repositories` | Lists name, format, type, package count and feed address (with a copy button) and the links of its format (npm: *Browse*, *Upload*, *Registry*; Maven: *Browse*, *Upload*, *Repository*; Docker: *Browse* and the `v2/{name}/` registry address); creates a local, a [remote](remote-repositories.md) or a [virtual](virtual-repositories.md) repository (the remote and virtual forms ask for the format: NuGet, [npm](npm-registry.md), [Maven](maven-repositories.md) or [Docker](docker-registry.md)), or a local one of another format | +| `/admin/repositories/{name}` | Shows the feed and who effectively holds each action (see [Access control](access-control.md#admin-pages)); edits *Anonymous read*; for a remote repository also its upstream, *Test connection*, the cache and *Purge* ([details](remote-repositories.md)); for a virtual one its members, deploy repository and *Where would a package come from?* ([details](virtual-repositories.md)); a member lists the virtual repositories it belongs to | +| `/admin/repositories/{name}/delete` | Deletes a repository that holds **no packages** (a remote one: purge its cache first) | + +Other administrator pages work across all repositories: + +| Page | Does | +|---|---| +| `/admin/operations` | Runs *Rebuild the catalog*, *Import download counts*, the Docker garbage collection (dry run and run) and the vulnerability scan for a chosen repository as background jobs; shows each one's last status | +| `/admin/validation` | Pending and quarantined submissions of every repository: retry, release (index anyway, audited), reject (see [configuration](configuration.md#validate-packages-before-serving-them)) | +| `/admin/abuse` | Abuse reports of every repository (unresolved by default, `?all=true` for all): resolve or reopen; links each package to its Manage page in its own repository | + +Rules: + +* Names: 1 to 64 lowercase letters, digits, `-`, `.`, `_`; no leading or trailing `.`, no `..`; not a reserved word (`admin`, `api`, `r`, `v3`, ...). Invalid names are refused with the reason. +* A name is never changed after creation (it is in URLs and storage paths). +* `default` cannot be deleted. +* A repository that a virtual repository lists as a member cannot be deleted until it is removed there. +* A repository that still holds packages, or submissions awaiting validation, cannot be deleted; delete the packages first and wait for the validations. Deleting removes its history rows too (catalog entries, owners, validations, abuse reports, API keys limited to it alone) and every file under `repos/{name}/` in storage (symbols, catalog files, staged uploads), so a repository re-created under the same name starts empty. +* Writes are refused with `503` while the server is read-only for maintenance (for example during a database copy). +* *Anonymous read* is enforced: off, anonymous callers get `401` (feeds) or the sign-in page, and others need a Read grant of their own. See [Access control](access-control.md). +* Creating needs a relational database and a repository-aware search: with Azure Table, or with `Search:Type` = `AzureSearch` (one global index), only `default` exists and other repositories already in the database are not served. +* The `AddRepositories` migration creates the `default` row itself, so it exists even when migrations are applied outside the app. diff --git a/docs/retention.md b/docs/retention.md new file mode 100644 index 000000000..97aedbeda --- /dev/null +++ b/docs/retention.md @@ -0,0 +1,86 @@ +# Retention and cleanup + +Retention policies delete old versions on their own: keep the newest N, delete by age or by lack of downloads, trim a +remote cache, remove untagged Docker manifests and collect their blobs. Everything is in **Admin > Retention** +(`/admin/retention`); administrators only. Needs a relational database (not Azure Table). + +## Policies + +A policy applies to **one repository** or to **every repository of a project** (deleting the repository or the project deletes its policies, audited) (virtual repositories store nothing and +are skipped). A version is deleted when **any enabled rule selects it** and no legal hold covers it. + +| Rule | Selects | Notes | +|---|---|---| +| Keep the newest N | versions of an artifact beyond its N newest (by publish time) | per artifact (package id, npm name, Maven `group:artifact`, Docker image) | +| Older than D days | published more than D days ago | | +| Unused for D days | last download older than D days | publish time (not before the rule started watching, see below) when no download was recorded (see below) | +| Prerelease only | restricts the three rules above to prerelease versions | NuGet pre-release, npm prerelease, Maven `-SNAPSHOT`; Docker tags are never prerelease | +| Cache limit (MiB) | remote repositories: least recently used versions until the cache fits | ignored (with a note) elsewhere | +| Untagged for D days | Docker manifests no tag, index or referrer relationship needs, pushed more than D days ago | counted from the push; children of an index and artifacts attached to a manifest (signatures) are kept | +| Collect garbage | Docker: run the [garbage collection](docker-registry.md) after the rules | frees the layers of deleted manifests | +| Only these artifacts | name globs (`*`, one per line) limiting the policy | empty = all | + +What a "version" is per format: + +| Format | Version | Deleted with | +|---|---|---| +| NuGet | package version | rows and `.nupkg`, as an administrator's hard delete (not the protocol's unlist) | +| npm | published version | row and tarball; dist-tags that pointed at it go, `latest` moves to the highest left; the last version removes the package | +| Maven | `group:artifact` version, with all files (snapshot builds included) | rows and files; the artifact goes with its last version | +| Docker | a **tag** of an image | the tag only; its manifest stays until the untagged rule takes it, its blobs until the garbage collection | + +### Downloads and "unused" + +NuGet counts downloads; the other formats do not, so the server records **when each version was last downloaded** +(NuGet package download, npm tarball, Maven file, Docker manifest pull by tag or digest). Writes are batched in memory and +saved about once a minute (and before a run plans), so a restart can lose the last minute. Downloads before this feature +existed are unknown: such a version counts from its publish time or from when the rule started watching, whichever is later, +so a policy never judges a period it did not watch (a new policy waits N days before it selects a version nobody is recorded +to have downloaded). The watching clock (`UnusedSince`) starts at creation and restarts when the *Unused* days, the repository, +the project or the name patterns are edited; an old policy that gains the rule, or is pointed at other repositories, waits N days too. + +## Dry run, run, schedule + +Open a policy (`/admin/retention/{id}`): + +* **Dry run** lists every version the policy would delete (artifact, version, dates, size, the rule that selected it) + and those kept by a legal hold. It deletes nothing and needs no password. **It is computed by the code a run uses**: the + run deletes exactly that list (a version published, held or deleted in between aside). The Docker garbage collection in a + dry run reports the state before this run's deletions. +* **Run now** (password) deletes the list. Both run in the background; the page shows the report when ready. One run per + policy at a time. A version that cannot be deleted is reported `Failed` and tried again by the next run. +* **Schedule**: "run every N hours" (enabled policies only). The first run is N hours after the schedule was set or the policy + enabled; then N hours after the last run started. Scheduled runs wait while the server is read-only (database copy) and + run once it reopens. +* The result is kept on the policy (last run, one line). The detailed report of the latest run is kept in memory until restart. + +A real run, saving, enabling and deleting a policy are refused with 503 while the server is read-only +([maintenance gate](configuration.md)); a dry run is a read and still works through the service. + +## Legal holds + +**Admin > Retention > Legal holds** (`/admin/retention/holds`). A hold names a repository, an artifact (in the form its +format lists it) and optionally one version (a Docker tag or digest). No version = every version, including ones published +later. Every rule skips a held version, and the report lists it as `Held`. A hold is only checked by retention: someone +who may delete a version still can. Placing a hold needs no password; lifting one does. + +## Audit + +Creating, changing and deleting a policy, placing and lifting a hold, and every run are written to the +[access audit](access-control.md#admin-pages) (`/admin/audit`, actions `retention.*`) and to the admin audit log +(`IAdminAudit`; runs are `retention.run` / `retention.dry-run`; a run the read-only gate interrupts is still audited as `retention.run` with "Interrupted" and what was deleted so far, the scheduler's actor is `scheduler`). + +## Deleting a repository + +Deleting a repository deletes its policies, legal holds and recorded download times. + +## For developers + +| Piece | Where | +|---|---| +| Tables `RetentionPolicies`, `RetentionHolds`, `ArtifactUsages` (migration `AddRetention` x4) | `BaGet.Core/Retention/RetentionEntities.cs` | +| Rules as a pure function | `RetentionEvaluator` | +| Run (plan + delete, per repository scope) | `RetentionEngine`; background runs `RetentionJobs`; schedule `RetentionWorker` | +| Per-format list/delete | `IFormatRetentionHooks`: `NuGetRetentionHooks`, `NpmRetentionHooks`, `MavenRetentionHooks`, `DockerRetentionHooks` | +| Policies and holds (audited) | `IRetentionAdministration` | +| Download times | `ArtifactUsageRecorder` (in memory, flushed in batches) | diff --git a/docs/scalar.md b/docs/scalar.md new file mode 100644 index 000000000..0b87744be --- /dev/null +++ b/docs/scalar.md @@ -0,0 +1,98 @@ +# Testing the APIs with Scalar + +BaGet serves its OpenAPI documents with a [Scalar](https://scalar.com) viewer at **`/scalar`**: browse every endpoint, read its +schema and send real requests from the browser. + +## Who can open it + +Administrators only; everyone else (anonymous included) gets `404`, for the viewer and for the JSON. + +| Caller | Opens `/scalar` and `/openapi/*.json` | +|---|---| +| Signed-in server administrator (browser session) | yes | +| An administrator's API key with the `admin:api` scope, not limited to repositories | yes | +| The server's global `ApiKey` (only when one is configured) | yes | +| Anyone else, or accounts disabled without a global `ApiKey` | no (`404`) | + +The simplest way: sign in as an administrator, then open `https:///scalar` (or follow the link on **Admin > REST API**, `/admin/api`). + +## The three documents + +Pick one with the document selector at the top of the viewer. + +| Document | JSON | What it covers | Authenticate with | +|---|---|---|---| +| `ui` | `/openapi/ui.json` | `/api/ui/...`: the JSON twin of every web screen (what an Angular/React frontend calls) | an API key (`bearer` or `apiKey`) or a session token (`session`); never the bare cookie, never Basic | +| `v1` | `/openapi/v1.json` (alias `/api/v1/openapi.json`) | `/api/v1/...`: the administration REST API ([admin-api.md](admin-api.md)) | an administrator's `admin:api` key (never the session) | +| `protocols` | `/openapi/protocols.json` | NuGet V3/V2, symbols, npm, Maven and Docker (OCI) routes, at `/` and `/r/{repo}/` | anonymous where the repository allows it, else an API key | + +## Getting an API key + +Signed in, open **Account > API keys** (`/account/apikeys`) and create a key. For `/api/v1` choose an administrator account and the +`admin:api` scope, with no repository limit. The key is shown once: copy it. + +## Setting the credentials in Scalar + +Open the **Authentication** box of the viewer (or the *Auth* tab of the request window) and choose one scheme: + +| Scheme | Fill in | Use for | +|---|---|---| +| `bearer` | the key | `/api/v1`, `/api/ui`, most protocol routes | +| `session` | the `accessToken` of `POST /api/ui/session` | `/api/ui` only (a person's session) | +| `basic` | any user name (npm/Maven send the account name), the key as password | `/api/v1` and the protocol routes (what Maven and Docker clients send); **not** `/api/ui` | +| `apiKey` (`X-NuGet-ApiKey` header) | the key | `/api/ui`, NuGet push/delete, also accepted elsewhere | + +A wrong or revoked key is refused with `401`; it never falls back to the session (no document accepts the session cookie). The `ui` document offers `bearer`, `apiKey` and `session`. + +**Shape of the `ui` document** (for generated clients): enums are string schemas listing their names (`ScreenStatus`: `Ok`, `Invalid`, ...), as the API writes them; integers are plain `integer`; every operation that answers a `ScreenResult` describes its `400`, `401`, `403` and `404` answers with the schema of its `200`; an optional route value is two paths (`/api/ui/packages/{id}` and `/api/ui/packages/{id}/{version}`, the value a required path parameter in the second), never a query parameter behind a path that names it. + +## Testing `/api/ui` (screens as JSON) + +Set the `bearer` (or `apiKey`) scheme to a key, as for `/api/v1`, or the `session` scheme to the `accessToken` of `POST /api/ui/session`. The browser cookie is **not** +used here unless a request also carries the antiforgery token of `GET /api/ui/antiforgery` in `X-XSRF-TOKEN`. Without a credential you are anonymous: public screens work (home, package, statistics, report abuse), a +protected one answers `401` with a message saying to send a key; HTTP Basic is refused with `401`. + +- **Administration screens** (`/api/ui/admin/...`) need an administrator's session token or key with the `admin:api` scope and no repository limit, e.g. `GET /api/ui/admin/repositories` returns + the model the **Repositories** screen renders. The server's global `ApiKey` is refused with `403` (it has no owner): use an administrator's key. +- **Account self-service** (sign-in, password, two-factor, API keys, organizations, deletion) and **package ownership** screens (manage, contact owners, validation status, scan) + need an interactive session (a session token): they appear in the document, marked "Interactive session only", and answer `403` "use the web screen" to an API key and to an anonymous caller. +- A key limited to repositories sees other repositories as `404`. + +**Confirmation passwords.** Actions whose screen asks your password (delete, purge, access changes, ...) take it in the request body field +the schema shows (e.g. `password`). A wrong one counts as a failed sign-in and can lock the account. + +**Reading the answer.** Every `/api/ui` response is a screen result: + +| Field | Meaning | +|---|---| +| `status` | `Ok`, `Invalid`, `NotFound`, `Forbidden`, `SignIn`, `Next` | +| `model` | the data the screen renders (present also when `Invalid`, so a form can be shown again) | +| `errors` | field name -> messages (`""` = the whole form) | +| `next` | after a write: where to go (`screen` = `{ controller, action }` such as `AdminUsers` / `Index`, `routeValues`, or a validated `localUrl`; `fragment`) and the flash `message` or `error` | +| `statusCode` | set when the screen itself answers with a specific code | + +HTTP status: `200` (Ok, Next), `400` (Invalid), `401` (SignIn), `403` (Forbidden), `404` (NotFound), `503` while the server is read-only +(maintenance, database copy); some screens answer with their own code (e.g. `409`). + +## Testing `/api/v1` (administration) + +Set the `bearer` scheme to an administrator's `admin:api` key (or the global `ApiKey`, which `/api/v1` still accepts); the session is never accepted here. Operations +marked as needing confirmation also take the key owner's password in the **`X-Confirm-Password`** header (the global key needs none). +Errors are `application/problem+json` with a stable `code`; lists are paged (`page`, `pageSize` up to 200). Details: [admin-api.md](admin-api.md). + +## Testing the package protocols + +Good for reads: service index (`GET /v3/index.json`), search, package metadata, npm packuments, Maven metadata, OCI tags and manifests. +For a private repository authenticate with a key (`basic` with the key as password, or `bearer`). For OCI (`/v2/...`) an anonymous call +returns `401` with a `Bearer realm=.../v2/token` challenge: call `GET /v2/token?scope=repository:/:pull` with Basic +credentials and use the returned token as `bearer`. + +Uploads (a `.nupkg`, an npm tarball, Docker layers) are binary or multi-step and are easier with the real clients (`dotnet nuget push`, +`npm publish`, `mvn deploy`, `docker push`); the document describes their routes and parameters, not their bodies. + +## Tips + +- Test against a copy or a test repository: Scalar sends real requests, deletes included. +- The read-only gate (Settings, database copy) makes every write answer `503` with `Retry-After`. +- The documents never contain keys or secrets; download them (`/openapi/.json`) to generate a client (e.g. `openapi-generator`, + NSwag, `orval` for React/Angular). diff --git a/docs/ui-api.md b/docs/ui-api.md new file mode 100644 index 000000000..bb4308721 --- /dev/null +++ b/docs/ui-api.md @@ -0,0 +1,181 @@ +# UI API (`/api/ui`) + +Every web screen has a JSON twin under `/api/ui/...` that does the work and answers the model the screen renders. A frontend (Angular, React, +a script) can be written against `/api/ui` alone; the HTML screens call the same code in process and only render the answer, so the two +cannot differ. Try it in the browser with [Scalar](scalar.md); the administration API for scripts is [`/api/v1`](admin-api.md). + +## Routes + +| Screen | Twin | +|---|---| +| GET of a screen (`/admin/users`) | `GET /api/ui/admin/users` | +| POST of the screen's own form | `POST` the same path | +| Named handler (`?handler=Approve`) | `POST` (or `GET`) `/api/ui//approve` (kebab case; catch-all routes put the handler first: `/api/ui/npm-manage/{handler}/{*id}`) | +| Repository screen (`/r/{repo}/...`) | `/api/ui/r/{repo}/` | + +Route values keep the screen's names (`{id}`, `{name}`, `{version}`). The complete list is the OpenAPI document `ui` +(`/openapi/ui.json`) and the snapshot `tests/BaGet.Tests/Contracts/ui-api.txt`. Bodies are JSON; a file upload is multipart. + +## Who may call + +Two kinds of caller: **API keys** (scripts, like [`/api/v1`](admin-api.md)) and **a person's interactive session** (a single-page application): a +**session token** from `POST /api/ui/session` for any origin, or, for an application served from BaGet's own origin, the **cookie plus an antiforgery header** +([Sessions](#sessions-for-a-single-page-application)). The bare cookie is never a credential and HTTP Basic is refused. Exception: an open server (accounts off, no `ApiKey`) lets anonymous callers upload, so any page a +visitor opens can post an upload there, as it already can to the protocol routes (CORS allows any origin); configure an `ApiKey` or turn accounts on. + +| Caller | Rule | +|---|---| +| Session token in `Authorization: Bearer bgs.…` | The signed-in user, with the rights of their cookie session (every scope, no repository limit, administrator flag read per call). Re-validated on every use (account exists, not pending, not locked out, security stamp unchanged). An invalid or expired token is `401`. **Only `/api/ui` accepts it**: on a protocol route, `/api/v1` or the registry it is an invalid key | +| Cookie + `X-XSRF-TOKEN` header (any method) | Same as a session token, for a client on BaGet's own origin; the token comes from `GET /api/ui/antiforgery`. The cookie without a valid header is ignored: the request is anonymous | +| API key in `Authorization: Bearer ` or `X-NuGet-ApiKey: ` | Acts as the key's owner within its scopes and repository limit. An invalid key is `401` (never read as anonymous, never falls back to the cookie). A key beside a session is judged as a key | +| HTTP Basic | `401` with a message saying to use Bearer or `X-NuGet-ApiKey` (browsers cache Basic credentials and re-send them cross-site) | +| Anonymous | Public screens (home, package, statistics, legal, report abuse, profiles, browse); a protected screen is `401` | +| Administrator screens | An administrator's interactive session, or an administrator's key with `admin:api` and no repository limit. Anyone else: `401` (no credential), `403` (another user's session or key). The **global `ApiKey` is refused** (`403`: it has no owner). A project administrator's session reaches the screens of their project | +| Account self-service (sign-in/out, registration, password, two-factor, external logins, API keys, organizations, deletion) and package ownership screens (manage, contact owners, validation status, scan) | **Interactive sessions only**: a session token, or the cookie with the antiforgery header. An API key (a leaked CI key must not change the account) and an anonymous caller get `403` "use the web screen". They stay in the OpenAPI document, marked "Interactive session only" | + +Same gates as the HTML screen: accounts on, mail configured, administrator, access model present, repository check (`r/{repo}`: `404` for an +unknown repository, a format mismatch or a repository the caller cannot read), `MaintenanceGate` (`503` + `Retry-After` on writes while read-only) and the +password the screen asks for, sent in the body (an account without a password confirms within five minutes of the external sign-in that created the session token). The HTML screens keep their cookie session and antiforgery token; they call the same code in process. + +## Sessions for a single-page application + +Endpoints under `/api/ui` (JSON bodies, answers are `ScreenResult<...>`; `404` while accounts are off). They are not the twin of a screen (the sign-in page sets a cookie) and carry no +`[UiApi]`. All of them are *session endpoints*: an invalid or expired `Authorization: Bearer bgs....` header is no credential on them (a client that attaches its token to every request can still +refresh or sign in), and a browser request whose `Origin` is not this server's (or, except for the cookie endpoints, a listed one in `Cors:AllowedOrigins`) is refused with `403`. **With no list a page of +another origin cannot script them** (no password spraying or intranet reach from visitors' browsers); a separate-origin SPA must list its origin. Requests without an `Origin` header (scripts) are not affected. "This server's origin" is the request's scheme and host, plus the origin of `Site:PublicUrl` when set; behind a TLS proxy +whose `X-Forwarded-Proto` BaGet does not trust ([`Proxy:*`](configuration.md#reverse-proxies-and-forwarded-headers)) the request looks like `http`, so set `Site:PublicUrl` (or trust the proxy), else a same-origin SPA is refused. + +| Method and route | Body | Answer | +|---|---|---| +| `POST /session` | `{ userName, password }` | `model`: `{ accessToken, expiresAt, refreshToken, refreshExpiresAt, userName }`, or `{ twoFactorRequired: true, twoFactorTicket, twoFactorTicketExpiresAt }` for an account with two-factor. `401` wrong credentials (the same answer for an unknown user), `403` locked out / awaiting approval / email unconfirmed (only to the right password), `400` empty form | +| `POST /session/two-factor` | `{ ticket, code }` | the tokens; `401` for a wrong code or an expired ticket (counted: five failures lock the account, then `403`) | +| `POST /session/recovery-code` | `{ ticket, recoveryCode }` | the tokens; each code works once | +| `POST /session/refresh` | `{ refreshToken }` | a new pair; the old refresh token stays valid until it expires (stateless); the authentication time is kept and the session ends `Accounts:SessionMaxLifetime` after it | +| `POST /session/exchange` | `{ exchangeToken }` | the tokens (or the two-factor ticket) for the 60-second token of an external sign-in; **each token works once** (a used one is remembered until it expires: in the shared store with `Ha:Enabled`, else in memory), a second use is `401` | +| `POST /session/sign-out` | `{ everywhere?, refreshToken? }` | `200`. Revokes nothing by itself (the client forgets its tokens); `everywhere: true` changes the account's security stamp, which ends **every** token and cookie session of the account (send the access token, or the refresh token in the body) | +| `GET /antiforgery` | | `model`: `{ headerName: "X-XSRF-TOKEN", requestToken }` and the antiforgery cookie; the token is bound to the signed-in user (or to the anonymous visitor), so fetch it again after signing in or out | +| `POST /session/cookie` | `{ userName, password }`, then for two-factor `{ ticket, code \| recoveryCode }` | **Same origin only**, and needs the antiforgery token of a signed-out visitor in `X-XSRF-TOKEN` (no login CSRF). The rules of `POST /session`, but the answer holds no tokens: the session cookie is set (fetch the antiforgery token again; the cookie is accepted with it, [Who may call](#who-may-call)) | +| `POST /session/cookie/sign-out` | | Same origin; the cookie session with its antiforgery header ends. `401` for anything else (a token session has no cookie) | +| `GET /session/providers` | | the external sign-in providers to offer before anyone is signed in: `model.providers` = `[{ id, displayName }]` (empty when none; `404` while accounts are off). Anonymous, with the other session endpoints' origin rule | +| `GET /session/external/{provider}?returnUrl=` | | a browser navigation: challenges the OpenID Connect provider `{provider}` (its id: `oidc` for the single `Accounts:OpenIdConnect` block, else a key of `Accounts:OpenIdConnectProviders`; read without case; an unknown id is `404`; `GET /session/providers` lists them). `returnUrl` must lie under `Frontend:SpaBasePath` of this server or be an address of an origin in `Cors:AllowedOrigins` (an empty list does **not** mean any origin here), else `400` | +| `GET /session/external-callback?returnUrl=` | | redirects to `returnUrl#exchange_token=...&exchange_expires_at=...&user_name=...`, or `#notice=...` (account created, not usable yet) or `#error=...`. No cookie is set or kept (a session of the browser is left alone) and no session token is put in a URL: exchange the token at `POST /session/exchange` within a minute and **remove the fragment at once** (`history.replaceState(null, '', location.pathname + location.search)`) so it stays out of the history and `Referer`. **Bind it to the browser**: the exchange token is not tied to whoever receives it, so an attacker could send a victim a link that signs the victim in as the attacker. Put a random `state` in the query of `returnUrl` (`/app/callback?state=...`), remember it in `sessionStorage` before the redirect, and exchange only when the returned `state` matches | + +The anonymous account flows work for a client without a session, from this server's origin (or a listed one), with an API key refused (`403`) and **no cookie ever set** for an HTTP caller: + +| Method and route | Notes | +|---|---| +| `GET` / `POST /account/register` | `404` when registration is closed. Answers `model.session` (the new account's tokens) when it can sign in at once, nothing when a confirmation or approval is pending. Every attempt counts against the client address; the email address is mailed once per ten minutes, charged only when an account was created (a refused attempt costs nothing; a second account for the same address is created but not mailed again: use `resend-confirmation`) | +| `GET /account/confirmemail?userId=&code=[&email=]` | the link of the mail; a made-up link is the same harmless answer (`succeeded: false`) | +| `POST /account/resend-confirmation` | `{ identifier }` (user name or email): mails a new link to an unconfirmed account, once per account per ten minutes and per client; the answer is the same whether or not an account matches | +| `GET` / `POST /account/forgotpassword`, `GET` / `POST /account/resetpassword` | as the screens: the same answer whoever the name belongs to; an unknown user and a bad code are the same refusal | + +Emails link to the screens (`/account/confirmemail`, `/account/resetpassword`). When the screens are off (`Frontend:Mvc=false`) and `Frontend:SpaPath` is set, or `Frontend:SpaLinks=true` +(an application a reverse proxy serves under the base path), or `Frontend:SpaUrl` names an application hosted elsewhere (`{SpaUrl}/confirm-email`...), they link to the application +instead (with the screens off and none of these, the host refuses to start while email is configured: no link may point at a 404): `{PublicUrl}{SpaBasePath}/confirm-email?userId=&code=[&email=]`, `.../reset-password?userId=&code=` and `.../sign-in` (the cookie's login path), with the same query values; the token is never dropped +(the application posts `code` back unchanged). + +**Tokens.** `bgs.` + ASP.NET Core data protection of `{ user id, security stamp, authentication time, expiry }`, one purpose per kind (access, refresh, two-factor ticket, exchange, so one cannot +stand for another); nothing is stored, so a token cannot be revoked one by one. Lifetimes: access `Accounts:SessionTokenLifetime` (15 min), refresh `Accounts:SessionRefreshLifetime` (14 days; a refresh +issues a new one, so an active client stays signed in), but never past `Accounts:SessionMaxLifetime` (30 days) after the sign-in; two-factor ticket 5 minutes, exchange token 60 seconds. Send +`Authorization: Bearer `; renew with `refresh` before `expiresAt`; keep the tokens in memory (or a secure store) and never put them in a URL (only the 60-second exchange token travels +in a fragment). In a cluster every node needs the shared data protection key ring ([high availability](high-availability.md)). + +**Revocation.** Every use re-reads the account: deleted, awaiting approval, or a different security stamp means `401`. A locked-out account (someone guessing its password) keeps the sessions it has, like a +cookie session; only a sign-in is refused. Changing the password, enabling or resetting two-factor, or `sign-out everywhere` change the stamp. When the **current** token session itself caused the change, the +answer carries a renewed pair in the headers `X-Session-Access-Token`, `X-Session-Access-Expires`, `X-Session-Refresh-Token`, `X-Session-Refresh-Expires` (exposed to CORS; only for the caller's own +account): replace the tokens you hold. Every other session of the account ends. + +**Confirmations a stolen token cannot skip.** Over `/api/ui` (token or cookie with the header), the two-factor setup key and QR code are only answered to `GET /account/twofactor` with the password in +`X-Confirm-Password` (without it the screen's model has none, and nothing is generated); turning two-factor on and creating an API key need `password` in the body. The web screens' forms are unchanged. + +**Hosting.** `Cors:AllowedOrigins` and `Frontend:*` are in [configuration](configuration.md#single-page-applications). + +## The answer: `ScreenResult` + +| Field | Meaning | +|---|---| +| `status` | `Ok`, `Invalid`, `NotFound`, `Forbidden`, `SignIn`, `Next` | +| `model` | What the screen renders (also on `Invalid`, so the form can be shown again) | +| `errors` | Field name to messages; `""` = the whole form | +| `next` | After a write: `screen` (`{ "controller": "AdminUsers", "action": "Index" }`), `routeValues`, flash `message` or `error` | +| `statusCode` | Set when the screen itself answers with a code (an upload refused with `403`, a missing package explained with `404`) | + +| `status` | HTTP | +|---|---| +| `Ok`, `Next` | `200` (or `statusCode`) | +| `Invalid` | `400`, body still holds `model` and `errors` | +| `Forbidden` | `403` | +| `SignIn` | `401` with `WWW-Authenticate: Bearer` | +| `NotFound` | `404` (also for "you may not know it exists") | +| read-only gate closed | `503` + `Retry-After` (problem details) | + +JSON is camelCase, enums by name, nulls left out. A response never carries a password, a protected password, a connection string, a +security stamp or an API key value (except the key just created, shown once). + +## Browser-only steps + +No twin: the external provider's challenge and callback (sign-in and re-authentication; a token client uses `/session/external/oidc`), and downloads that are +plain URLs (package files, symbol files, avatars). `UiApiParityTests` fails for any other screen and handler (GET or POST) of a view without a twin. + +## OpenAPI and Scalar + +`/openapi/ui.json` (this API: every twin, plain and `/api/ui/r/{repo}/`; security schemes `bearer` and `apiKey` only), `/openapi/v1.json` and +`/openapi/protocols.json`, viewer at `/scalar`; administrators only (everyone else `404`). See [testing the APIs with Scalar](scalar.md). + +## Architecture + +| Project | Holds | +|---|---| +| `BaGet.Identity.Application`, `BaGet.Web.Application` | Use cases (`UseCase`), the DTOs (the JSON `model`), business services. No MVC or Razor reference (`ApplicationLayeringTests`) | +| `BaGet.Identity.Api`, `BaGet.Web.V3` | The `[UiApi]` twins (`Controllers/UI`) and the other web APIs; no view controller, no view, no reference to a front end (`ApplicationLayeringTests`) | +| `BaGet.Api.Base` | What twins and screens share: the twin bases (`ApiControllerBase` family), `[UiApi]`, `[RepositoryPage]`, `IScreenController`/`ScreenEndpoints`, `UiApiSecurityFilter`, `RequestPrincipalResolver` | +| `BaGet.Identity.FrontEnd`, `BaGet.Web.FrontEnd` | The view controllers (`Controllers/FrontEnd`), which bind the form, call the twin in process (`UiApiInvoker`) and render, and their views; `AddBaGetFrontEnd()` registers them | +| `BaGet.Frontend.Base` | MVC base of the screens: `UiControllerBase` family, `UiApiInvoker`, `RepositoryUrlHelper`, `NavLinkTagHelper`, the layout and shared partials | + +A use case takes explicit inputs (caller, form, cancellation token), returns a `ScreenResult` and sees no `HttpContext`, `ModelState` or +`TempData`. The twin's filters do not run in process, so the view controller bases run the same `ScreenGate` first. +Moved types are not forwarded (`[TypeForwardedTo]`): code compiled against an older BaGet must be recompiled. + +## Not breaking + +URLs, forms, `?handler=` values, redirects and status codes of the HTML screens are unchanged; the snapshots `ui-routes.txt`, +`ui-forms.txt` and `public-api.txt` (a superset check) guard it. Each screen's row in [UI coverage](ui-coverage.md) covers its twin. + +## Adding a screen + +Worked examples: `LegalController` / `LegalApiController` / `LegalUseCase`, `StatisticsController` / `StatisticsApiController` / `StatisticsUseCase`; +test twins for each base at the end of `tests/BaGet.Tests/UiApiAccessTests.cs`. + +| Piece | Where | Rule | +|---|---|---| +| Use case | `BaGet.Web.Application/UseCases` or `BaGet.Identity.Application/UseCases/` | Scoped `UseCase`, one method per GET and handler; inputs explicit (caller `ClaimsPrincipal`, form DTO, `CancellationToken`); returns `ScreenResult`; sees no `HttpContext`, `ModelState`, `TempData`; validates its form itself; a write calls `MaintenanceGate.ThrowIfClosed`; absolute links from `IUrlGenerator`; no secret in a DTO | +| DTO | same project, `Models/` (namespace = folder) | Flat, no EF entities; one type per file | +| Registration | `AddBaGetWebUseCases`, or `AddBaGetAccounts` after its `Enabled` check | `TryAddScoped<UseCase>()` | +| JSON twin | `BaGet.Web.V3/Controllers/UI` or `BaGet.Identity.Api/Controllers/UI` | `ApiController`; never `[ApiController]`, a `UiControllerBase` or `[AutoValidateAntiforgeryToken]`; it may not reference the view controller, so `[UiApi]` names the screen by text | +| View controller | `BaGet.Web.FrontEnd/Controllers/FrontEnd` or `BaGet.Identity.FrontEnd/Controllers/FrontEnd`, view in the same project's `Views//.cshtml` | Binds the form, `Api(api => ...)`, `Render(...)`; holds no use case | + +Twin bases: `ApiControllerBase` (public), `AccountApiControllerBase` (override `RequiresSignIn`/`RequiresEmail`; **interactive sessions only**: 403 over HTTP to a key and to an anonymous caller), +`AdminApiControllerBase` (administrator's session or `admin:api` key), `AccessApiControllerBase` (override `AuthorizeAsync`; writes `503` while read-only; retention, replication and +repository bases build on these). Every twin is visible in the OpenAPI `ui` document (the base sets `[ApiExplorerSettings(IgnoreApi = false)]`) and answers +`ActionResult>` through `Respond(...)`. + +```csharp +[Route("api/ui")] +[RepositoryPage(NotOnVirtual = true)] // same values as the view controller: adds api/ui/r/{repo}/... +public sealed class StatisticsApiController : ApiControllerBase +{ + [HttpGet("stats"), UiApi("Statistics", "Index")] // view controller without the suffix + its default GET action + public async Task>> Get(CancellationToken ct) + => Respond(await _useCase.GetAsync(ct)); +} +``` + +Routes: GET `api/ui/`; default POST the same path; handler `X` = `api/ui//` with `[UiApi("X", "Index", Handler = "X")]` (the view controller without the `Controller` suffix and its default GET action name the screen; `ApiOperation(summary, "X", "Index")` takes the same two strings); route values keep the +view's names. Bodies are `[FromBody]` JSON, uploads `[FromForm]` multipart. Public helpers are `[NonAction]` or non-public. The view action becomes +`=> Render(await Api(api => api.Get(ct)), "Index")` and keeps every attribute and its base (whose `ScreenGate` and +antiforgery already ran: the twin's filters do not run in process). + +Checklist: the parity case (page and twin carry the same, statuses correspond) in `UiApiParityTests`; a case per caller kind in `UiApiAccessTests` +(anonymous, cookie ignored without the antiforgery header, session token, key, `admin:api` key, limited key, global key, Basic); no password or key in a response; regenerate `Contracts/ui-api.txt` with +`BAGET_UPDATE_CONTRACTS=1` (never hand-merge); `ui-routes.txt`, `ui-forms.txt` and `public-api.txt` stay unchanged; a `ScreenCatalog` member and a row with its `Controller/Action` token in [UI coverage](ui-coverage.md) for +a new screen (`ScreenCatalogTests` checks that every catalog entry, `[UiApi]`, `FormatLink` and `ApiOperation` name resolves to a view action: a typo is a failing test, not a compile error). diff --git a/docs/ui-coverage.md b/docs/ui-coverage.md new file mode 100644 index 000000000..265aef0c6 --- /dev/null +++ b/docs/ui-coverage.md @@ -0,0 +1,276 @@ +# UI coverage + +Every operation the server offers (REST, CLI, service) is reachable from the web UI, with the gate of the operation. +This page maps each capability to its page. Pages in repository scope also exist as `/r/{name}/...`. "Admin" = an +administrator signed in (others get 404). "Password" = the administrator's password (or a fresh external sign-in) is +asked again. Every write calls `MaintenanceGate.ThrowIfClosed` (503 while closed) and, on package pages, refuses in +`IsReadOnlyMode`. Tests: `UiCoverageTests` and the page test of each area; `UiCoverageInventoryTests` fails when a controller, screen (`Controller/Action` of a view controller) or CLI command has no row here, and `AdminApiAccessTests` when a REST operation has none. Every screen also has a JSON twin under `/api/ui` ([UI API](ui-api.md)); the twin is covered by its screen's row (no row of its own) and `UiApiParityTests` fails for a screen without one. + +## NuGet protocol (per repository) + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Service index `v3/index.json` | REST | Admin Repositories / RepositoryEdit (feed URL + copy); Upload page (feed URLs) | read | +| Search, autocomplete | REST | Home and `/` search (`Home/Index`; filters, sort, paging); type-ahead on both search boxes | read | +| Package page, versions, dependents, readme, icon, download | REST | `/packages/{id}/{version}` (`Package/Show`), download link | read | +| Registration, flat container, `.nuspec` | REST | machine-only; the package page links the downloads | read | +| Push `.nupkg` | REST (`PUT api/v2/package`) | `/upload` (`Upload/Index`; stage, review, publish) | Push | +| Push `.snupkg` / symbols | REST (`api/v2/symbol`) | `/upload` (symbol package) | Push | +| Symbol download | REST | machine-only (debugger); symbols listed and deleted on Manage | read | +| Unlist / relist / delete | REST (`DELETE`, `POST`) | Manage (`PackageManage/Index`): Unlist, Relist, Delete; permanent delete asks Password | Manage (owner) | +| Deprecation (reasons, message, alternate ID and version range) | REST | Manage: Deprecate / Remove | Manage | +| Vulnerabilities | REST | Manage: add / remove | Manage | +| V2 feed | REST (`api/v2`) | Repositories: "V2 feed" link | read | +| Vulnerability index | REST | Repositories: "Vulnerabilities" link | read | +| Catalog index, pages, leaves | REST | Repositories: "Catalog" link (local repositories) | read | +| Catalog rebuild | CLI `catalog rebuild -r` | Admin Operations | Admin, audited | +| Repository signatures, certificate | REST | Repositories: "Signatures" link (local repositories) | read | +| Validation status of a submission | REST (`v3/package/{id}/{v}/validation`) | `/packages/{id}/validation` (`ValidationStatusPage/Index`), linked from Manage | Push or Manage | +| Import downloads | CLI `import downloads -r` | Admin Operations | Admin, audited | +| Report abuse | page | `/packages/{id}/{v}/report-abuse` (`ReportAbuse/Show`) | read | + +## npm registry (per repository, `npm/`) + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Search `-/v1/search` | REST | `/npm-packages` (`NpmBrowse/Packages`) | read | +| Packument, tarball | REST | `/npm-packages/{name}` (`NpmBrowse/Package`; versions, tags, downloads) | read | +| Publish | REST (`PUT {name}`) | `/npm-upload` (`NpmBrowse/Upload`; file, tag) | Push | +| Dist-tags set / remove | REST | NpmManage (`NpmManage/Index`) | Manage | +| Deprecate / undeprecate a version | REST | NpmManage | Manage | +| Unpublish a version / all | REST (`DELETE`) | NpmManage | Manage + Password | +| Owners | REST | NpmManage | Manage | +| Login / logout (tokens) | REST (`npm login`, `-/user/token`) | Account API keys (create, list, revoke; npm tokens are keys limited to a repository) | signed in | +| Ping, whoami, audit | REST | stateless handshakes; whoami is the signed-in profile, audit answers "none" | none | +| Web login `-/v1/login` | REST | not offered (answers 404, npm falls back to user and password) | - | + +## Maven repository (per repository, `maven/`) + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Read file, checksum, `maven-metadata.xml` | REST (`GET`/`HEAD`) | `/maven-artifacts` (`MavenBrowse/Artifacts`; browse, search), `/maven-artifacts/{group}/{artifact}/{version}` (`MavenBrowse/Artifact`; files with sizes and checksums, POM view, download links) | read | +| Deploy (`mvn deploy`, `PUT`) | REST | `/maven-upload` (`MavenBrowse/Upload`; coordinates, file, optional POM), `settings.xml` and `distributionManagement` snippets on browse and upload | Deploy | +| Delete a file | REST (`DELETE`) | MavenManage (`MavenManage/Index`) | Manage + Password | +| Delete a version / the artifact | service | MavenManage | Manage + Password | +| Snapshot clean-up (keep newest N builds) | service | MavenManage | Manage + Password | +| Owners | service | MavenManage | Manage | +| Policy, redeploy, snapshot builds kept | service | RepositoryEdit: Maven settings (audited) | Admin | +| Remote Maven repository: create (URL, credentials, periods, offline, store locally) | service | Repositories > *New remote repository* (format Maven) | Admin + Password | +| Remote Maven: edit upstream, *Test connection*, cache table, *Purge cache*, *Purge package* (`group:artifact`, version text) | service | RepositoryEdit (`/admin/repositories/{name}`) | Admin + Password | +| Remote Maven: read through (`GET`/`HEAD` of files, checksums, metadata) | REST | `/maven-artifacts` (the stored artifacts), snippets incl. the Central `` | read | +| Virtual Maven repository: create, members, order, deploy repository, *Where would an artifact come from?* | service | Repositories > *New virtual repository* (format Maven); RepositoryEdit members and preview (`group:artifact`, any version) | Admin | +| Dependency / `settings.xml` / `` / Gradle snippets | machine-only config | artifact and browse pages | read | + +## Docker registry (per repository, `/v2/{repo}/`) + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Version check `GET /v2/` | REST | machine-only handshake (the browse page shows the registry address and `docker login`) | none (401 challenge) | +| Token service `GET /v2/token` (`docker login`) | REST | machine-only; Account API keys creates the key used as the password; the browse page shows the login, `curl` and daemon snippets | API key / anonymous | +| Pull: blobs (ranges), manifests, tag list, referrers (`?artifactType=` filter: the *Referrers* form on `?digest=`) | REST | `/docker-images` (`DockerBrowse/Images`; browse, search), `/docker-images/{image}` (`DockerBrowse/Image`; tags, manifests, platforms of an index), `?digest=` (config, layers with sizes, annotations, referrers such as signatures and SBOMs, the document) | Read | +| Push: upload sessions (monolithic, chunked, mount), manifests | REST | machine-only (Docker CLI); the browse and image pages show the push, `buildx` and pull commands | Deploy | +| Delete a tag | REST (`DELETE manifests/{tag}`) | DockerManage (`DockerManage/Index`) | Delete + Password | +| Delete a manifest (with its tags) | REST (`DELETE manifests/{digest}`) | DockerManage | Delete + Password | +| Delete a blob from an image | REST (`DELETE blobs/{digest}`) | covered by *Remove unused layers* (a blob in use is refused) | Delete | +| Remove unused layers | service | DockerManage | Delete + Password | +| Delete the whole image | service | DockerManage | Delete + Password | +| Repository: create, list, anonymous read, delete | service | Repositories (Docker create form, Browse link), RepositoryEdit, RepositoryDelete | Admin | +| Remote Docker repository: create (URL, user name, password or token, periods, offline, store locally) | service | Repositories > *New remote repository* (format Docker) | Admin + Password | +| Remote Docker: edit upstream, *Test connection* (version check through the token flow), cache table (manifests, images, layer bytes), *Purge cache*, *Purge package* (image, optional tag or digest) | service | RepositoryEdit (`/admin/repositories/{name}`) | Admin + Password | +| Remote Docker: pull through (`GET`/`HEAD` of manifests, layers, tags) | REST | `/docker-images` (the cached images, pull commands), `/docker-images/{image}` | read | +| Virtual Docker repository: create, members, order, deploy repository, *Where would an image come from?* (image, tag or digest) | service | Repositories > *New virtual repository* (format Docker); RepositoryEdit members and preview | Admin | +| Virtual Docker: pull from the first member, merged tags, push to the deploy repository | REST | `/docker-images` (the members' images merged), `/docker-images/{image}` | read / Deploy | +| Docker garbage collection of a repository (dry run, run) | service (`IOciGarbageCollector`) | Admin Operations: *Docker garbage collection: dry run* and *Docker garbage collection* per local or remote Docker repository; scheduled by a retention policy (*Collect garbage*) | Admin, audited | + +## Vulnerability scanning + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Findings of a version (NuGet, npm, Maven, Docker image) | service (`IScanService`) | the *Vulnerabilities* section of `/packages/{id}/{version}`, `/npm-packages/{name}`, `/maven-artifacts/...`, `/docker-images/{image}?digest=` | read | +| Scan a version now | service | `/scan-artifact` (`ScanArtifact/Index`; linked from that section) | signed in, Manage on the package | +| Scan a whole repository | service, operation `vulnerability-scan` | Admin Scanning > repository (*Scan the whole repository now*); Admin Operations | Admin, audited | +| Counts by severity, versions with findings, engines in use | service | Admin Scanning, Admin Scanning > repository | Admin | +| Policy of a repository (warn, block download, block deploy, block unscanned) | service (`IScanPolicyService`) | Admin Scanning > repository | Admin + Password, audited | +| Policy of a project | service | Admin Scanning > project (linked from the project) | Admin + Password, audited | +| 403 with the reason on download and deploy | REST (every format's routes) | package pages explain a refusal; the Upload pages show it | read / Deploy | +| NuGet vulnerability resource | REST | Manage lists the scanner's entries read-only | read | +| Scanning options (`Scanning:*`) | `appsettings.Overrides.json` | Admin Settings (`AdminSettings/Index`) | Admin + Password | + +## Repositories (Admin) + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| List, counts, feed URL, links per format | service | Admin Repositories | Admin | +| Filter the list by name fragment, format and kind (`?q=`, `?format=`, `?kind=`; the REST list's parameters, one rule `RepositorySummaryFilter`) | REST `GET /api/v1/repositories` | Admin Repositories: filter form | Admin | +| Create local NuGet / npm / Maven / Docker | service | Repositories create forms | Admin | +| Create remote (URL, credentials, cache periods, offline) | service | Repositories remote form, RepositoryEdit | Admin + Password | +| Create virtual, members, order, upload target | service | Repositories virtual form, RepositoryEdit | Admin | +| Virtual preview, remote connection test | service | RepositoryEdit: Preview, Test | Admin (+ Password for test) | +| Purge remote cache / one package | service | RepositoryEdit | Admin + Password | +| Anonymous read, delete | service | RepositoryEdit, RepositoryDelete | Admin | +| Enable formats | settings | Admin Formats | Admin | + +## Access model (Admin) + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Groups: create, rename, delete, members | `IAccessAdministration` | Groups, GroupDetail | Admin + Password | +| Permission targets: create, edit, delete, grants, restore built-ins | service | Permissions, PermissionDetail | Admin + Password | +| Preview ("who can do what") | service | Permissions / PermissionDetail / ProjectDetail: Preview; Account Access (`AccountPackages/Access`, own access) | Admin | +| Projects: create, members, repositories, delete | service | Projects, ProjectDetail | Admin + Password | +| Audit trail (filter actor, subject, dates) | service | Audit | Admin | + +## Accounts, organizations, owners + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Register, confirm email, sign in (password, 2FA, recovery code, external) | pages | Account pages | anonymous | +| Sign in for a single-page application (password, 2FA ticket + code or recovery code, refresh, exchange, sign out, external provider, cookie sign-in and sign-out, antiforgery token, register / resend confirmation / forgot / reset / confirm without a session) | REST (`/api/ui/session`, `/api/ui/antiforgery`) | the sign-in pages (`Account/Login`, `Account/LoginWith2fa`, `Account/LoginWithRecoveryCode`) | anonymous; same lockout, approval and email rules | +| Forgot / reset password | pages | ForgotPassword, ResetPassword | anonymous | +| Change password / email, delete account | service | Account Settings (`AccountSettings/Settings`) | signed in + Password | +| Sign in with one of several OpenID Connect providers (a button each); link / unlink a provider; re-authenticate with a linked provider | `/api/ui/session/providers`, `/api/ui/session/external/{provider}`, `/api/ui/account/settings/unlink-external` | Login (`Account/Login`), Reauthenticate (`Account/Reauthenticate`), Account Settings > *Sign-in providers* (`AccountSettings/Settings`) | anonymous; link / unlink signed in + Password | +| Two-factor: enable, disable, reset | service | TwoFactor (`AccountSettings/TwoFactor`) | signed in + Password | +| API keys: scopes, glob, expiry, repositories; revoke | service | Account API keys (`AccountSettings/ApiKeysIndex`) | signed in | +| Organizations: create, members | service | Account Organizations (`AccountOrganizations/Organizations`) | signed in | +| Organizations: rename, delete, admin flag | service | Admin Organizations, OrganizationDetail (`AdminOrganizations/Index`, `AdminOrganizations/Detail`) | Admin + Password | +| Package owners add / remove, verified flag | service | Manage (verified: Admin) | Manage | +| Contact owners | service | `/packages/{id}/contact-owners` (`ContactOwners/Index`) | signed in, SMTP | +| Profiles, packages of an owner | pages | `/profiles/{name}` (`Profile/Profile`), Account Packages (`AccountPackages/Packages`); all packages: Admin Packages (`AdminPackages/Index`) | read | +| Approve a self-registered account (`Accounts:RequireApproval`) | CLI `account approve`, service (`AccountApprovalService`) | Admin Users and Admin UserDetail: *Approve* (both show *Awaiting approval*); reject = Delete | Admin + Password, 503 while read-only | +| Users: create, invite, promote (also approves), demote | CLI `account promote\|demote`, service | Admin Users | Admin + Password | +| Reset password, with `--email` | CLI `account reset-password [--email]` | Admin Users: Generate a password (+ optional email) | Admin + Password | +| Send reset link | service | Admin Users | Admin + Password, SMTP | +| Delete user, user's packages and keys | service | DeleteUser, UserDetail, UserPackages (`AdminUsers/DeleteUser`, `AdminUsers/UserPackages`) | Admin + Password | + +## Operations and server + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| Validation queue: retry, release, reject | service | Admin Validation (`AdminOperations/Validation`) | Admin (+ Password) | +| Abuse reports: resolve, reopen | service | Admin Abuse (`AdminOperations/Abuse`); Manage for the owner | Admin / Manage | +| Settings (every options section), restart-required marks | `appsettings.Overrides.json` | Admin Settings | Admin + Password | +| Sign-in providers (`Accounts:OpenIdConnectProviders`): list, add, edit, remove named OpenID Connect providers (secret write-only, administrator / group mapping), restart-required | `SignInProviderSettings`, `/api/ui/admin/settings/save-provider`, `remove-provider` | Admin Settings > Accounts > *Sign-in providers* (`AdminSettings/Index`) | Admin + Password, 503 while read-only | +| Logging: default minimum level (live), Windows event log switch and source (restart) | `Serilog` section | Admin Settings > Serilog | Admin + Password | +| Logging: level per source (`Serilog:MinimumLevel:Override`, live): list with where each is set, set, remove (only what the page saved) | `SettingsService.SetLogLevelOverrideAsync` | Admin Settings > Serilog > *Log levels per source* | Admin + Password, 503 while read-only | +| Database copy (copy all data, status) | service | Admin Settings (database section) | Admin + Password | +| Telemetry settings, status, connection test | service | Admin Settings (telemetry section) | Admin + Password | +| Statistics | service | `/statistics` (`Statistics/Index`) | read | +| Read-only gate banner | MaintenanceGate | every page | - | +| Retention policies: create, change, enable, delete (rules, name patterns, schedule) per repository or project | service (`IRetentionAdministration`) | Admin Retention (`/admin/retention`, `/admin/retention/{id}`) | Admin + Password, audited | +| Retention: dry run (what a run would delete), run now, last report, scheduled runs | service (`RetentionEngine`, `RetentionJobs`, `RetentionWorker`) | Admin Retention > policy: *Dry run* (no password), *Run now* (Password); the schedule field | Admin (+ Password), audited, 503 while read-only (run) | +| Legal holds: place, list, lift (artifact or one version) | service (`IRetentionAdministration`) | Admin Retention > Legal holds (`/admin/retention/holds`) | Admin, lifting asks Password, audited | +| Download times (last download per version, for the *unused* rule) | in memory (`ArtifactUsageRecorder`) | shown as *Last download* in a retention report | Admin | +| Replication configurations: create, change, enable, delete (local repository, push or pull, peer address and repository, peer API key, schedule, on deploy, delete propagation, conflict rule) | service (`IReplicationAdministration`) | Admin Replication (`/admin/replication`, `/admin/replication/{id}`) | Admin + Password, audited | +| Replication: test connection, run now, resume an interrupted or failed run, stop, log of runs (status, counts, first failures and conflicts) | service (`ReplicationEngine`, `ReplicationJobs`, `ReplicationWorker`) | Admin Replication > configuration: *Test connection*, *Run now*, *Resume* (Password), *Stop*, the log table | Admin (+ Password), audited, 503 while read-only | +| Cluster status: nodes with health and read-only state, job leases and their holder, the shared store, this node's health checks (database, storage, shared store) | service (`IClusterStatusService`, `ReadinessService`) | Admin Cluster (`AdminOperations/Cluster`, `/admin/cluster`, *Check again*) | Admin | +| High availability settings (`Ha:*`: enable, Redis connection string, node name, key prefix, lease and sync intervals), restart-required marks | settings | Admin Settings > Ha | Admin + Password | +| Health probes for a load balancer: `/health/live`, `/health/ready` (database, storage, shared store) | REST (anonymous, no detail in the body) | Admin Cluster > *This node's health checks* shows the same checks with their detail | - | +| Replication inventory (what a repository holds, for a peer to compare) | service (`IReplicationInventory`) | Admin Replication > configuration: *the local repository holds N items* | Admin | + +## Administration REST API (`/api/v1`) + +Every operation below has the page that offers the same operation and the same gate: an administrator's API key with the `admin:api` scope (or the global key) in place of the signed-in administrator, and the key owner's password in `X-Confirm-Password` where the page asks for the password. See [Administration REST API](admin-api.md). The list is generated from the controllers; `AdminApiAccessTests` fails when a row is missing or names a page that does not exist. + +| Capability | Reached by | UI | Gate | +|---|---|---|---| +| List access-audit entries, newest first, optionally by actor, subject or time | REST `GET /api/v1/audit` | `AdminAudit/Index` | Admin key | +| List the package formats and the kinds and fields each offers | REST `GET /api/v1/formats` | `AdminOperations/Formats` | Admin key | +| List groups with their member counts | REST `GET /api/v1/groups` | `AdminGroups/Index` | Admin key | +| Create a group | REST `POST /api/v1/groups` | `AdminGroups/Index` | Admin key | +| Delete a group with the grants and project roles that name it | REST `DELETE /api/v1/groups/{name}` | `AdminGroups/Detail` | Admin key + password | +| Show a group with its members and the grants naming it | REST `GET /api/v1/groups/{name}` | `AdminGroups/Detail` | Admin key | +| Rename a group | REST `PATCH /api/v1/groups/{name}` | `AdminGroups/Detail` | Admin key | +| Remove a user from a group | REST `DELETE /api/v1/groups/{name}/members/{user}` | `AdminGroups/Detail` | Admin key + password | +| Add a user to a group | REST `PUT /api/v1/groups/{name}/members/{user}` | `AdminGroups/Detail` | Admin key + password | +| Download the OpenAPI 3 description of this API (also `/openapi/{ui,v1,protocols}.json`, browsed at `/scalar`) | REST `GET /api/v1/openapi.json` | `ApiCatalog/Index` | Admin key or admin cookie | +| List the operations this server offers, the repositories each applies to and their last runs | REST `GET /api/v1/operations` | `AdminOperations/Index` | Admin key | +| Show the last run of an operation on a repository | REST `GET /api/v1/operations/{operation}/repositories/{repository}` | `AdminOperations/Index` | Admin key | +| Start an operation on a repository (one that deletes data asks for the password) | REST `POST /api/v1/operations/{operation}/repositories/{repository}` | `AdminOperations/Index` | Admin key + password | +| List permission targets | REST `GET /api/v1/permission-targets` | `AdminPermissions/Index` | Admin key | +| Create a permission target (add grants afterwards) | REST `POST /api/v1/permission-targets` | `AdminPermissions/Index` | Admin key | +| Preview which repositories (and whether a package) a set of patterns selects; saves nothing | REST `POST /api/v1/permission-targets/preview` | `AdminPermissions/Index` | Admin key | +| Re-create the built-in groups and permission targets that are missing | REST `POST /api/v1/permission-targets/restore-built-ins` | `AdminPermissions/Index` | Admin key + password | +| Delete a permission target and its grants | REST `DELETE /api/v1/permission-targets/{name}` | `AdminPermissions/Detail` | Admin key + password | +| Show a permission target with its grants | REST `GET /api/v1/permission-targets/{name}` | `AdminPermissions/Detail` | Admin key | +| Replace a permission target's repository and package patterns | REST `PUT /api/v1/permission-targets/{name}` | `AdminPermissions/Detail` | Admin key + password | +| Give a user, group or organization actions through a permission target (none removes the grant) | REST `PUT /api/v1/permission-targets/{name}/grants` | `AdminPermissions/Detail` | Admin key + password | +| List projects with their repository and member counts | REST `GET /api/v1/projects` | `AdminProjects/Index` | Admin key | +| Create a project | REST `POST /api/v1/projects` | `AdminProjects/Index` | Admin key | +| Delete a project with its members, targets and retention/scan policies (its repositories stay) | REST `DELETE /api/v1/projects/{name}` | `AdminProjects/Detail` | Admin key + password | +| Show a project with its repositories, members and permission targets | REST `GET /api/v1/projects/{name}` | `AdminProjects/Detail` | Admin key | +| Give a user or group a role in a project | REST `PUT /api/v1/projects/{name}/members` | `AdminProjects/Detail` | Admin key + password | +| Remove a user or group from a project | REST `DELETE /api/v1/projects/{name}/members/{type}/{principal}` | `AdminProjects/Detail` | Admin key + password | +| Take a repository out of a project | REST `DELETE /api/v1/projects/{name}/repositories/{repository}` | `AdminProjects/Detail` | Admin key + password | +| Put a repository in a project (it leaves any project it was in) | REST `PUT /api/v1/projects/{name}/repositories/{repository}` | `AdminProjects/Detail` | Admin key + password | +| List repositories (filter by format, kind or name) | REST `GET /api/v1/repositories` | `AdminRepositories/Index` | Admin key | +| Create a local, remote or virtual repository of any format (remote asks for the password) | REST `POST /api/v1/repositories` | `AdminRepositories/Index` | Admin key + password | +| Delete an empty repository (refused for default, a repository with packages, or a virtual member) | REST `DELETE /api/v1/repositories/{name}` | `AdminRepositories/DeleteRepository` | Admin key | +| Show a repository with its upstream, cache or members | REST `GET /api/v1/repositories/{name}` | `AdminRepositories/Edit` | Admin key | +| Switch a repository's anonymous read (a remote repository asks for the password) | REST `PATCH /api/v1/repositories/{name}` | `AdminRepositories/Edit` | Admin key + password | +| Show who holds which action in a repository, and why | REST `GET /api/v1/repositories/{name}/access` | `AdminRepositories/Edit` | Admin key | +| Change a remote repository's upstream and settings | REST `PUT /api/v1/repositories/{name}/remote` | `AdminRepositories/Edit` | Admin key + password | +| Show what a remote repository stores and remembers | REST `GET /api/v1/repositories/{name}/remote/cache` | `AdminRepositories/Edit` | Admin key | +| Purge a remote repository's cache (deletes what it stored) | REST `POST /api/v1/repositories/{name}/remote/purge` | `AdminRepositories/Edit` | Admin key + password | +| Purge one cached package of a remote repository | REST `POST /api/v1/repositories/{name}/remote/purge-package` | `AdminRepositories/Edit` | Admin key + password | +| Test a remote repository's upstream with unsaved settings (saves nothing) | REST `POST /api/v1/repositories/{name}/remote/test` | `AdminRepositories/Edit` | Admin key + password | +| Replace a virtual repository's members, their order and its deploy repository | REST `PUT /api/v1/repositories/{name}/virtual` | `AdminRepositories/Edit` | Admin key | +| Show where a package version would come from in a virtual repository (fetches and stores nothing) | REST `POST /api/v1/repositories/{name}/virtual/preview` | `AdminRepositories/Edit` | Admin key | +| List legal holds, optionally of one repository | REST `GET /api/v1/retention/holds` | `AdminRetention/Holds` | Admin key | +| Place a legal hold on an artifact (retention never deletes it) | REST `POST /api/v1/retention/holds` | `AdminRetention/Holds` | Admin key | +| Lift a legal hold | REST `DELETE /api/v1/retention/holds/{key}` | `AdminRetention/Holds` | Admin key + password | +| List retention policies with their last run | REST `GET /api/v1/retention/policies` | `AdminRetention/Index` | Admin key | +| Create a retention policy | REST `POST /api/v1/retention/policies` | `AdminRetention/Index` | Admin key + password | +| Delete a retention policy (what it deleted stays deleted) | REST `DELETE /api/v1/retention/policies/{key}` | `AdminRetention/Policy` | Admin key + password | +| Show a retention policy with its last run and report | REST `GET /api/v1/retention/policies/{key}` | `AdminRetention/Policy` | Admin key | +| Replace a retention policy's scope and rules | REST `PUT /api/v1/retention/policies/{key}` | `AdminRetention/Policy` | Admin key + password | +| Start a dry run of a policy: the report of what a run would delete (nothing is deleted) | REST `POST /api/v1/retention/policies/{key}/dry-run` | `AdminRetention/Policy` | Admin key | +| Show the last run (or dry run) of a policy with its report | REST `GET /api/v1/retention/policies/{key}/run` | `AdminRetention/Policy` | Admin key | +| Start a run of a policy: the versions it selects are deleted | REST `POST /api/v1/retention/policies/{key}/run` | `AdminRetention/Policy` | Admin key + password | +| List replications with their last run | REST `GET /api/v1/replication/configs` | `AdminReplication/Index` | Admin key | +| Create a replication | REST `POST /api/v1/replication/configs` | `AdminReplication/Index` | Admin key + password | +| Show a replication | REST `GET /api/v1/replication/configs/{key}` | `AdminReplication/Config` | Admin key | +| Replace a replication's settings | REST `PUT /api/v1/replication/configs/{key}` | `AdminReplication/Config` | Admin key + password | +| Delete a replication with its log (what it copied stays where it is) | REST `DELETE /api/v1/replication/configs/{key}` | `AdminReplication/Config` | Admin key + password | +| Test the connection to a peer with the given settings (nothing is saved; a stored key is used while the address is unchanged) | REST `POST /api/v1/replication/test` | `AdminReplication/Config` | Admin key + password | +| Start a run of a replication | REST `POST /api/v1/replication/configs/{key}/run` | `AdminReplication/Config` | Admin key + password | +| Start a run that continues the last interrupted or failed run of a replication | REST `POST /api/v1/replication/configs/{key}/resume` | `AdminReplication/Config` | Admin key + password | +| Ask the running replication to stop (it ends as interrupted and can be resumed) | REST `POST /api/v1/replication/configs/{key}/stop` | `AdminReplication/Config` | Admin key | +| List the runs of a replication, newest first (status, counts, the first failures and conflicts) | REST `GET /api/v1/replication/configs/{key}/runs` | `AdminReplication/Config` | Admin key | +| Show one run of the replication log | REST `GET /api/v1/replication/runs/{key}` | `AdminReplication/Config` | Admin key | +| List what a repository holds in the form replication compares (what a peer asks; summary=true: only the count) | REST `GET /api/v1/replication/inventory/{repository}` | `AdminReplication/Config` | Admin key | +| Show whether scanning is on and every repository's numbers and policy | REST `GET /api/v1/scanning` | `AdminScanning/Index` | Admin key | +| Show a project's scanning policy | REST `GET /api/v1/scanning/projects/{name}/policy` | `AdminScanning/Project` | Admin key | +| Set a project's scanning policy (all thresholds empty removes it) | REST `PUT /api/v1/scanning/projects/{name}/policy` | `AdminScanning/Project` | Admin key + password | +| Show a repository's scan numbers, its own policy and the last scan | REST `GET /api/v1/scanning/repositories/{name}` | `AdminScanning/Repository` | Admin key | +| Set a repository's scanning policy (all thresholds empty removes it) | REST `PUT /api/v1/scanning/repositories/{name}/policy` | `AdminScanning/Repository` | Admin key + password | +| List the scanned versions with findings of at least a severity, worst first | REST `GET /api/v1/scanning/repositories/{name}/results` | `AdminScanning/Repository` | Admin key | +| Scan every artifact of a repository in the background | REST `POST /api/v1/scanning/repositories/{name}/scan` | `AdminScanning/Repository` | Admin key | +| List users, optionally by a name fragment | REST `GET /api/v1/users` | `AdminUsers/Index` | Admin key | +| Create a user (with a given or a generated password, returned once) | REST `POST /api/v1/users` | `AdminUsers/Index` | Admin key + password | +| Show a user with groups, project roles, organizations and API keys | REST `GET /api/v1/users/{name}` | `AdminUsers/Detail` | Admin key | +| Show what a user may do in each repository, and the grants behind it (for one package id with ?package=) | REST `GET /api/v1/users/{name}/access` | `AdminUsers/Detail` | Admin key | +| Make a user an administrator or take the flag away (never the last administrator) | REST `PUT /api/v1/users/{name}/administrator` | `AdminUsers/Index` | Admin key + password | +| Remove a user from a group | REST `DELETE /api/v1/users/{name}/groups/{group}` | `AdminUsers/Detail` | Admin key + password | +| Add a user to a group | REST `PUT /api/v1/users/{name}/groups/{group}` | `AdminUsers/Detail` | Admin key + password | +| Revoke one of a user's API keys | REST `DELETE /api/v1/users/{name}/keys/{key}` | `AdminUsers/Detail` | Admin key + password | + +## Audit method and gaps closed + +Standing rule: `UiCoverageInventoryTests` (controller, UI action, CLI command each need a row) and `AdminApiAccessTests` (each REST operation names an existing page). The last full audit compared, one by one: every controller route, every `IFormatModule`/administration/service method an operator reaches, every CLI command and option, every registered options type (the Settings catalog is built from `AddBaGetOptions`, so a new section appears by itself), every `?handler=` action, and the query parameters of each REST list and protocol endpoint with the page that serves it. + +| Gap found | Closed by | +|---|---| +| REST repository list filters by format, kind and name; the page listed everything | Admin Repositories filter form (shared `RepositorySummaryFilter`) | +| OCI referrers API filters by `artifactType`; the image page showed all referrers | *Referrers* filter form on the manifest page | + +No other operation lacked a page or a field. Items the UI cannot do are listed below. + +## Not in the UI, on purpose + +| Item | Why | +|---|---| +| `--urls`, host arguments | process start, not a runtime operation | +| Registration, flat container, symbol download, tarball bodies | machine formats; the pages link the downloads | +| Serilog sinks (`WriteTo`, file path, retention) | arrays of package-specific objects, read once at start; edit the file or the environment ([Logging](configuration.md#logging)) | +| `Kestrel` endpoints, `SettingsOverridesPath` | read before the settings file exists (listening address, where the file lives) | +| External login link / unlink | accounts are created by the first external sign-in; there is no link-later operation on the server | diff --git a/docs/user-manual.md b/docs/user-manual.md new file mode 100644 index 000000000..0b6930c7c --- /dev/null +++ b/docs/user-manual.md @@ -0,0 +1,85 @@ +# User manual + +Task-oriented guide to BaGet Extension: install, sign in, publish, consume, administer. Each section links to the page with the details. + +## 1. Install and start + +| Where | Page | +|---|---| +| Your computer | [On your computer](installation/local.md) | +| Docker | [Docker](installation/docker.md) | +| Azure, AWS, Google Cloud, Alibaba Cloud | [Azure](installation/azure.md), [AWS](installation/aws.md), [Google Cloud](installation/gcp.md), [Aliyun](installation/aliyun.md) | +| Windows behind IIS | [IIS proxy](installation/iis-proxy.md) | + +- Default address `http://localhost:6060` (`Kestrel__Endpoints__Http__Url` changes it; `--urls` has no effect). +- The first start applies database migrations. +- With no users, startup creates the administrator `Admin` / `Admin1234!`. Change the password at once ([Default administrator](configuration.md#default-administrator)). + +## 2. Sign in and API keys + +| Task | Where | +|---|---| +| Sign in, register, profile | The sign-in page (registration is `Accounts:AllowRegistration`; with `Accounts:RequireApproval` an administrator must approve new accounts on `/admin/users`) | +| Create an API key (scopes, expiry, repository limit) | `/account/apikeys` | +| Package owners, organizations | [Access control](access-control.md) | + +A push needs an API key (`-k`): a user key, or the global `ApiKey` when one is set. + +## 3. Publish and consume + +Repositories have a format. `default` is at `/`; any other is at `/r/{name}/`. See [Repositories](repositories.md) and [Package formats](formats.md). + +| Format | Publish | Consume | Details | +|---|---|---|---| +| NuGet | `dotnet nuget push -s http://localhost:6060/v3/index.json -k pkg.nupkg` (symbols: `.snupkg`) | Source `http://localhost:6060/v3/index.json`; V2 clients `http://localhost:6060/api/v2` | [Local install](installation/local.md), [Server API](advanced/api.md) | +| npm | `npm publish` | `npm install` with the repository's `.npmrc` lines | [npm registry](npm-registry.md) | +| Maven | `mvn deploy` | `settings.xml` / POM snippets | [Maven repositories](maven-repositories.md) | +| Docker | `docker login`, `docker push` | `docker pull` | [Docker registry](docker-registry.md) | + +Each package page shows the exact install commands for its repository. Browser upload: `/upload` (preview, then confirm). + +## 4. Search, browse, inspect + +- The front page and `/packages` list and search packages; a package page shows versions, dependencies, owners, downloads and vulnerability findings. +- The header switcher moves between repositories (shown when there are two or more). +- Owners manage a package (unlist, deprecate, owners, symbols) on its Manage page; a report goes through Report abuse. + +## 5. Administer + +Administrator pages live under `/admin` (others get `404`). + +| Task | Page | +|---|---| +| Settings, live (saved to `appsettings.Overrides.json`), database copy | `/admin/settings`, [Configuration](configuration.md) | +| Repositories: create local, [remote](remote-repositories.md) and [virtual](virtual-repositories.md) | `/admin/repositories` | +| Users, groups, permission targets, projects, audit | `/admin/users`, `/admin/groups`, `/admin/permissions`, `/admin/projects`, `/admin/audit`; [Access control](access-control.md) | +| Background operations (downloads import, catalog rebuild, Docker GC) | `/admin/operations` | +| Validation and abuse queues | `/admin/validation`, `/admin/abuse` | +| Retention policies and holds | `/admin/retention`; [Retention](retention.md) | +| Vulnerability scanning | `/admin/scanning`; [Vulnerability scanning](vulnerability-scanning.md) | +| Replication to or from another server | `/admin/replication`; [Replication](replication.md) | +| Cluster nodes and health | `/admin/cluster`; [High availability](high-availability.md) | +| Scripting everything above | [Administration REST API](admin-api.md) (`/api/v1`, `admin:api` key) | + +Command line (run in the host folder): + +| Command | Does | +|---|---| +| `import downloads [-r ]` | Imports nuget.org download counts | +| `catalog rebuild [-r ]` | Appends missing catalog entries | +| `account reset-password [--email
]` | Sets a generated password, switches off two-factor | +| `account promote ` / `account demote ` | Grants or removes the administrator flag (promoting also approves a pending account) | +| `account approve ` | Enables an account waiting for approval (`Accounts:RequireApproval`) | + +## 6. Operate + +| Topic | Notes | +|---|---| +| Read-only mode | While a database copy runs, writes answer `503` + `Retry-After`; sign-in still works | +| Health | `GET /health/live`, `GET /health/ready` | +| Logs | Serilog, `logs/baget-.log`; levels on the Settings page | +| Telemetry | OpenTelemetry export to an OTLP endpoint, set on the Settings page | +| Moving packages in | [nuget.org](import/nugetorg.md), [NuGet.Server](import/nugetserver.md), [local feeds](import/local-feeds.md) | +| Troubleshooting | [Debugging](advanced/debugging.md) | + +Every capability and the page that offers it: [UI coverage](ui-coverage.md). diff --git a/docs/virtual-repositories.md b/docs/virtual-repositories.md new file mode 100644 index 000000000..378a4fbb1 --- /dev/null +++ b/docs/virtual-repositories.md @@ -0,0 +1,86 @@ +# Virtual repositories + +A **virtual** repository presents several repositories of one format (local, [remote](remote-repositories.md) or other virtual ones) as one feed at `/r/{name}/v3/index.json` (npm: `/r/{name}/npm/`, see [npm virtual repositories](#npm-virtual-repositories); Maven: `/r/{name}/maven/`; Docker: `/v2/{name}/{image}`). Clients configure one source; the server decides which member answers. It stores nothing itself. + +## Create and edit + +Administrators: `/admin/repositories` > *New virtual repository* (a name and the **format**, NuGet, npm, Maven or Docker; it starts empty), then `/admin/repositories/{name}`. Needs a relational database and accounts, like all [repository pages](repositories.md#admin-pages). Not available with Azure Table or `Search:Type` = `AzureSearch` (only `default` exists there). + +| Control | Does | +|---|---| +| *Anonymous read* (create form, default on) | Whether requests without credentials may read the virtual repository. A member is read only when the caller may read that member, so this never exposes a closed member | +| Members table | Resolution order, top to bottom. *Up* / *Down* reorder, *Remove* drops a member. Saved at once, audited | +| *Add a member* | Any other repository **of the same format** whose own members do not lead back to this one; added at the end | +| Deploy repository | The member that receives uploads: a local member, or a virtual member that itself deploys to a local one. A remote repository cannot be one. *None* = the repository takes no uploads | +| *Where would a package come from?* | Package id (npm: package name) + version: asks each effective member in order and shows what it found (*stored here*, *its upstream has it and it would be fetched*, *not found*, *its upstream could not be asked*, *not asked: an earlier member answers*) and which member answers. Fetches and stores nothing. It uses the rules of a real request: each member's stored copy, then its own upstream (a remote repository's, or the one `default` fetches through while `Mirror:Enabled`); an upstream in offline mode shows *not stored; its upstream is in offline mode*, a remembered 404 counts as not found, and later members' upstreams are not asked once one answers | + +Rules: at most 50 members; a repository is listed once; a member must exist and be of the virtual repository's format (a NuGet virtual repository takes no npm, Maven or Docker member, and so on); **nesting** is allowed, a nested virtual member is expanded in place (each repository counts once, at its first place), and a change that would make a virtual repository contain itself is refused with the reason. A repository that a virtual repository lists cannot be deleted until it is removed there (the delete page says where). Edits are refused with `503` while the server is read-only for maintenance. Members are stored by name in `Repository.Settings` (no schema change). + +## What a client sees + +| Request | Result | +|---|---| +| Download, `.nuspec`, readme, icon of a version | The **first member**, in order, that has that version. A remote member fetches and stores it (in itself) as it does when read directly; a member that fails (its upstream is down) is logged and skipped, so a later member can answer | +| Version list, registration index | The **union** of the members' versions; each version's data comes from the first member that has it. (A package id in a local member and on nuget.org therefore lists the versions of both) | +| Search | Merged, one result per package id: the first member's entry, the versions of all members (highest first, the highest reported) and the summed downloads. Order is total and independent of the page: *relevance* = id (case-insensitive), *downloads* = summed downloads then id; `skip`/`take` never repeat or drop a package. *Last updated* is not offered. Each member is read only as far as the page needs (its first `skip + take + 1` results, 500 per call, at most 10,000, so a first page is one small call per member); a member of at most 2,000 results is read completely. While every member was read completely `totalHits` is the exact number of distinct ids; otherwise it is an estimate (ids seen plus each member's unseen remainder, an upper bound), results deeper than 10,000 per member are cut off, and with *downloads* an id held by several members is summed from the entries inside each member's window, so it can rank slightly low at a window edge | +| Autocomplete, version enumeration, dependents | The same merge (ids by name; versions ascending; dependents by summed downloads, top 20) | +| Symbols | The first member that stores the PDB | +| V2 feed (`/r/{name}/api/v2`) | `FindPackagesById`, `Packages(Id,Version)`, `Packages()` and `Search()` read the members' stored packages the same way (the V2 feed never asks an upstream, here or elsewhere) | +| Vulnerability index | The advisories of the readable members, each once | +| Scanning policy (download refusals) | The first member that has a scan result for the version decides, under that member's policy; a virtual repository has no results or policy of its own | +| Catalog | **Not served** (`404`, and the service index omits `Catalog/3.0.0`): a virtual repository records nothing, and a merged log would have no commit order a client could resume from. Use the members' catalogs | +| Service index | Like any repository's, with every URL inside `/r/{name}/` | +| Web pages | *Packages*, a package's page, *Upload* and *Browse* work; *Statistics*, *Report abuse*, *Manage package* and *Contact owners* answer `404` (a virtual repository has no owners, reports or counters of its own: use the member's page) | + +Every link in an answer (registration, search, V2 entries, content) points into the virtual repository, so clients keep resolving through it. + +## Writes + +A write to a virtual repository **is a write to its deploy repository**: the request is moved there before anything else, so the access model, package ownership, validation and the catalog all apply to that repository. + +| Request | Result | +|---|---| +| Push, symbol push, unlist, relist, deprecation, vulnerabilities (`PUT`/`POST`/`DELETE`), validation status | Handled in the deploy repository; needs **Deploy** (or the action asked) **there**. Deploy on the virtual repository itself is never granted (not even to administrators) and never needed. Without a deploy repository: `403`. An unlist or delete of a package stored in another member finds nothing in the deploy repository | +| Browser upload (`/r/{name}/upload`) | Stores in the deploy repository (the page says which); offered to those who can read the virtual repository and deploy to its deploy repository | + +## Access + +* Reading needs **Read on the virtual repository** (anonymous read, grants and project roles work as for any repository: [access control](access-control.md)). +* A request is answered **only from the members the caller may read** (per package too, by the grants' include/exclude patterns). A private member contributes nothing for a caller without Read on it: no error, no hint; a package only it has is `404`. +* Search and the V2 listing filter by repository, not by package pattern, like everywhere else. +* The *Effective access* table of a virtual repository shows *Deploy* as decided by the deploy repository. + +## npm virtual repositories + +A virtual repository of format npm merges npm repositories (`/r/{name}/npm/`). Members are read in their own scope (their storage, upstream and access rules apply), only those the caller may read, and a member that fails (an upstream that is down) is logged and skipped. + +| Request | Result | +|---|---| +| Packument (full and install-only) | The members' packuments **merged**: `versions` is the union, each version from the **first member** that has it (semantic versions compared without build metadata); `dist-tags` take, per tag, the **first member that has the tag**, so `latest` follows the member order and not the highest version (a tag whose version the merge does not hold is dropped; `latest` falls back to the highest version if no member has it); `time` is the union with the earliest `created` and the latest `modified`; description, readme and the other fields come from the first member that has them. Every tarball address points into the virtual repository | +| Tarball | The first member that has it; a remote member downloads and stores it as it does when read directly | +| Dist-tags (`GET`), `npm view`, package pages | The same merge | +| Search | Merged by package name (the first member's entry), ordered by name; each member is read for the first `skip + take` hits (at most 1000); remote members contribute the packages they stored. `total` is exact while every member was read completely, else an upper bound | +| `npm publish`, dist-tag, deprecate, unpublish | **Moved to the deploy repository** before authorization: it needs the matching action *there*, ownership there, and the unpublish window of `Npm:UnpublishWindow` applies there. Without a deploy repository: `403`. The service (`INpmRegistry`) does the same for callers that are not routes | +| `npm login`, `whoami`, `ping`, `audit` | As for any repository; login is answered by the virtual repository (not moved to the deploy repository) and its token also covers the members and the deploy repository | +| Web pages | *Browse*, a package's page and *Upload* (to the deploy repository) work; *Manage* answers `404` (use the member's page) | + +The *Where would a package come from?* preview asks each npm member: *stored here* (the version's tarball is stored), *not stored yet; its upstream has it* (a remote member, from its remembered or fresh packument), *not found*, *its upstream could not be asked*, *offline*. + +## Maven virtual repositories + +A virtual repository of format Maven merges Maven repositories (`/r/{name}/maven/`): files from the first member that has them, artifact `maven-metadata.xml` merged (versions union; `latest` and `release` follow the member order), writes moved to the deploy repository. Details in [Maven repositories](maven-repositories.md#virtual-maven-repositories). The preview takes `group:artifact` and a Maven version and asks each member (*stored here*, *would be fetched*, *not found*...). + +## Docker virtual repositories + +A virtual repository of format Docker merges Docker repositories (`docker pull host/{name}/{image}`): manifests and layers from the first member that has them, tag lists merged, a push moved to the deploy repository (a `403 DENIED` without one). Only the members the caller may pull from are asked; a registry token names the members it was issued for. Details in [Docker registry](docker-registry.md#virtual-docker-repositories). The preview takes an image name and a tag or digest and asks each member (*stored here*, *would be fetched*, *not found*...) with a `HEAD` and nothing stored. + +## `default` and the mirror + +`default` keeps its URL (`/`). With `Mirror:Enabled`, it behaves as a virtual repository of two members: its own packages, then the `mirror` remote repository (see [the mirror](remote-repositories.md#the-mirror)). What it fetches is stored **in `default`'s own rows**, exactly as before; `mirror` itself stays empty unless it is read at `/r/mirror/`. This is not a stored virtual repository (nothing to migrate, nothing to edit). To compose your own: + +* a virtual repository with `default` as a member reads `default` as it reads itself, mirror fall-through included; +* a virtual repository with `mirror` as a member reads the mirror's own cache (separate from what `default` stored). + +## Not covered + +No per-member path rules (include/exclude patterns), no merged catalog (only NuGet has one), no *last updated* sort, and the V2 feed ignores `$filter`/`$orderby` as everywhere. Per-member resolution state of remote members (memory, health) is per node, as for [remote repositories](remote-repositories.md). diff --git a/docs/vs/artifactory.md b/docs/vs/artifactory.md index f86d78357..084609c78 100644 --- a/docs/vs/artifactory.md +++ b/docs/vs/artifactory.md @@ -1,4 +1,53 @@ # Artifactory -!!! warning - This page is a work in progress! \ No newline at end of file +[JFrog Artifactory](https://jfrog.com/artifactory/) is a commercial, multi-format artifact repository manager; NuGet is one of its package types. + +| Feature | Artifactory | BaGet Extension | +|---|---|---| +| Formats | Multi-format (Maven, npm, Docker, PyPI, NuGet, ...) | NuGet, npm, Maven and Docker repositories (local, remote, virtual); `.nupkg`, `.snupkg`, tarballs, Maven files, OCI images | +| NuGet V3 | Yes: `/api/nuget/v3//index.json`; PackageBaseAddress only on repos with *Enforce Layout* (fixed at creation) | Yes: `/v3/index.json`; registration not paged | +| NuGet V2 | Yes: `/api/nuget/` | Yes: `/api/v2` OData, on by default (`Feeds:EnableV2`); `$filter`/`$orderby`/`$select`/`$expand` ignored | +| Symbols | Local, remote and virtual symbol repos; `.snupkg`; Microsoft PDB v7 and Portable PDB | Yes: `.snupkg` push, download endpoint; Portable PDB only | +| Proxy / upstream cache | Remote repos (nuget.org or another Artifactory); cached on demand | [Remote repositories](../remote-repositories.md): per-repository upstream (NuGet V3 or V2, npm, Maven, Docker), credentials, metadata and negative cache periods, offline mode, pass-through or stored copies, test connection, purge; plus the optional `Mirror:Enabled` mirror for the default repository. Stored copies are permanent until purged; search does not query upstream | +| Virtual / group feeds | Virtual repos combine local and remote behind one URL; push allowed | [Virtual repositories](../virtual-repositories.md): ordered members (local, remote, nested virtual), first match answers, versions and search merged, uploads to a default deploy repository, only readable members used; no merged catalog, no per-member path rules | +| Multiple feeds | Many repositories per instance | Many [repositories](../repositories.md) per instance (`/r/{name}/`), each with its own format and access | +| Private (authenticated) reads | Yes: anonymous access configurable (JFrog recommends off; anonymous removed from default permissions since 7.84.3); *Force Authentication* per repo | Yes: `AnonymousRead` per repository; a private one answers `401` + Basic challenge (`404` without Read) | +| Permissions model | Permission targets (repos + users/groups); Permissions V2 from 7.77.2; project RBAC | [Access control](../access-control.md): private repositories, groups, permission targets, project roles; anonymous read per repository; Basic auth or API key for reads; package ownership on top | +| Accounts / API keys | Users, groups, access tokens; API key as `user:key` in NuGet clients | Accounts (on in shipped config), OpenID Connect, TOTP 2FA, scoped expiring API keys, global `ApiKey` | +| Storage / DB backends | Filestore: file system, S3, Azure Blob, GCS, NFS; DB: PostgreSQL (default since 7.84.7), MySQL, MariaDB, MSSQL, Oracle, Derby (not for production) | File system, Azure Blob, S3, Google Cloud, Aliyun OSS; SQLite, SQL Server, PostgreSQL, MySQL, Azure Table | +| UI | Admin and browse UI | Search, details, upload, stats, package management, account pages | +| Deployment | JFrog-hosted SaaS or self-managed | Self-hosted .NET 10 (Windows/Linux/macOS), Docker, IIS | +| HA / scale-out | Self-managed HA listed under Enterprise X; SaaS Enterprise X 99.9% uptime | [High availability](../high-availability.md): several nodes on one database, object store and Redis (not on SQLite, the file system store or Azure Table) | +| Licence / cost | Commercial, see below | MIT, free; you pay only infrastructure | + +Artifactory editions and pricing (pricing page): + +| Plan | SaaS | Self-managed | +|---|---|---| +| Pro (SaaS) / Pro X (self-managed) | SaaS "Pro" $150/mo ($50 promo, monthly only); 25 GB base consumption, per-GB overage | Self-managed "Pro X" $27,000/yr, 1 server | +| Enterprise X | from $950/mo; 125 GB base | from $51,000/yr, 3 servers; HA | +| Enterprise + | custom | custom | + +- SaaS is priced by storage and transfer consumption; self-managed by server count and project count, minimum one-year term. +- Free offerings per JFrog: Artifactory OSS (Java only), Community Edition for C/C++ (Conan and generic only), cloud trial. No free edition with NuGet was found. + +## When to choose which + +- Artifactory: more formats (PyPI, Conan, ...), vendor-backed HA and support, JFrog Xray, a mature ecosystem. +- BaGet Extension: NuGet, npm, Maven and Docker with local, remote and virtual repositories, access control, retention, [vulnerability scanning](../vulnerability-scanning.md) (OSV, Trivy), [replication](../replication.md) and HA, with no licence cost and a simple self-hosted deployment. +- Artifactory: when you need a format BaGet Extension lacks or a vendor SLA. +- BaGet Extension: when NuGet, npm, Maven and Docker cover the need and a free, MIT-licensed server is wanted. + +## Sources + +Checked 2026-10. + +- +- +- +- +- +- +- +- +- BaGet Extension side: this fork's code and docs. diff --git a/docs/vs/azure-artifacts.md b/docs/vs/azure-artifacts.md index c7ef3b97d..4eb7845a2 100644 --- a/docs/vs/azure-artifacts.md +++ b/docs/vs/azure-artifacts.md @@ -1,4 +1,40 @@ # Azure Artifacts -!!! warning - This page is a work in progress! \ No newline at end of file +[Azure Artifacts](https://learn.microsoft.com/en-us/azure/devops/artifacts/start-using-azure-artifacts) is the package management service of Azure DevOps (cloud service and Azure DevOps Server). + +| Feature | Azure Artifacts | BaGet Extension | +|---|---|---| +| Package formats | NuGet, npm, Maven (incl. Gradle), Python, Cargo, Universal Packages | NuGet, npm, Maven and Docker repositories (local, remote, virtual); `.nupkg`, `.snupkg`, tarballs, Maven files, OCI images | +| NuGet protocol | V3 feed URL (`.../nuget/v3/index.json`); legacy V2 (`.../nuget/v2`, PAT; Azure DevOps Services only, "only when you can't move to a newer client") | V3 service index, plus V2 OData feed `/api/v2` (on by default, `Feeds:EnableV2`) | +| Symbols | Symbol server, published by the `PublishSymbols@2` pipeline task; retention follows the producing build; `.snupkg` not supported | Symbol server in the same feed: push `.snupkg`, download by key; portable PDBs only | +| Upstream / proxy | Upstream sources (nuget.org, npmjs, ...); packages saved to the feed when a Collaborator+ installs them; custom upstreams only for npm; cannot publish a version that exists upstream | [Remote repositories](../remote-repositories.md) (NuGet, npm, Maven, Docker upstreams) and the optional `Mirror:Enabled` mirror; indexed copy kept; search does not query upstream | +| Multiple feeds / views | Many feeds (org or project scoped); views `@local`, `@prerelease`, `@release`, read-only; promotion only, no demotion | Many [repositories](../repositories.md); [virtual repositories](../virtual-repositories.md) merge several; no views | +| Private reads | Private feeds need Feed Reader or higher; public feeds only in public projects (public projects convert to private from 2027) | Yes: `AnonymousRead` per repository; a private one needs Basic auth or an API key | +| Permissions | Roles Reader, Collaborator, Contributor, Owner per feed; view visibility settable | [Access control](../access-control.md): private repositories, groups, permission targets, project roles; anonymous read per repository; Basic auth or API key for reads; accounts, organizations, per-package owners | +| Accounts / API keys | Azure DevOps identities, personal access tokens | Local accounts, OIDC, TOTP 2FA, scoped expiring API keys, global `ApiKey` | +| Retention | Policy: max versions per package and days since last download; deletions kept 30 days in Recycle Bin; versions immutable (number never reusable) | [Retention policies](../retention.md): keep newest N, age, unused, cache size, untagged Docker manifests, dry run, holds; delete = `Unlist` (default) or `HardDelete` | +| UI | Web UI in Azure DevOps | Web UI: search, details, upload, stats, manage | +| Hosting | Azure DevOps Services (SaaS) or Azure DevOps Server (on-prem; Universal Packages not in Server 2020/2022; Cargo not in Server 2020) | Self-hosted .NET 10 (Windows/Linux/macOS, Docker, IIS) | +| HA | Managed by Microsoft (SaaS); on-prem HA not verified | [High availability](../high-availability.md): several nodes on one database, object store and Redis (not on SQLite, the file system store or Azure Table) | +| Licence / cost | 2 GiB free per organization, then tiered from $2/GiB down to $0.25/GiB; publishing blocked above the limit until billing is set up | MIT, free; infrastructure cost only | +| Maintenance | Microsoft product; docs updated 2026 | Fork of loic-sharma/BaGet, community maintained | + +## When to choose which + +- Azure Artifacts: already on Azure DevOps, or you need Python/Cargo/Universal Packages, views or Microsoft-managed hosting. +- BaGet Extension: NuGet, npm, Maven and Docker, self-hosted, no per-GiB billing, V2 and V3 on one server, per-repository read permissions. + +## Sources + +Checked 2026-10. + +- https://learn.microsoft.com/en-us/azure/devops/artifacts/start-using-azure-artifacts +- https://learn.microsoft.com/en-us/azure/devops/artifacts/concepts/feeds +- https://learn.microsoft.com/en-us/azure/devops/artifacts/concepts/views +- https://learn.microsoft.com/en-us/azure/devops/artifacts/concepts/upstream-sources +- https://learn.microsoft.com/en-us/azure/devops/artifacts/feeds/feed-permissions +- https://learn.microsoft.com/en-us/azure/devops/artifacts/how-to/delete-and-recover-packages +- https://learn.microsoft.com/en-us/azure/devops/pipelines/artifacts/symbols +- https://learn.microsoft.com/en-us/azure/devops/artifacts/nuget/nuget-exe +- https://learn.microsoft.com/en-us/nuget/create-packages/symbol-packages-snupkg +- https://azure.microsoft.com/en-us/pricing/details/devops/azure-devops-services/ diff --git a/docs/vs/liget.md b/docs/vs/liget.md index 899fc27da..2fa9aa24d 100644 --- a/docs/vs/liget.md +++ b/docs/vs/liget.md @@ -1,16 +1,38 @@ # LiGet -!!! warning - This page is a work in progress! - -[LiGet](https://github.com/ai-traders/liget) is a NuGet server created with a linux-first approach. - -* LiGet - * Strong support for Paket - * Only supports NuGet's v2 APIs (missing verified packages, signed packages, etc...) - * Stores all packages' metadata using a single JSON file -* BaGet - * Supports NuGet's v3 APIs - * Stores packages' metadata in a database - * Capable of ingesting all packages on nuget.org - * Can run on Azure \ No newline at end of file +[LiGet](https://github.com/ai-traders/liget) is a Linux-first, Docker-oriented NuGet server. Since 1.0 it is +itself a fork of upstream BaGet (per its README). It is **dormant**: not archived, but the last release is +1.0.3 (2019-04-29) and the last commit is 2021-01-06. + +# BaGet Extension vs LiGet + +| Feature | LiGet | BaGet Extension | +| --- | --- | --- | +| Maintenance | Dormant (last commit 2021-01) | Maintained fork | +| Runtime | Kestrel on .NET Core 2.0 (README) | .NET 10 | +| Protocols | V3 for private packages and V3 search; limited V2 (`FindPackagesById()`, `Packages()`, `PUT /api/v2`; no V2 search/filter) | V3, plus V2 OData at `/api/v2` (`searchTerm`, `id`, `$skip`/`$top`) | +| Paket | Tested with Paket; older Paket versions unsupported | Not specifically tested; not confirmed | +| Metadata | SQLite via EF (only listed DB) | SQLite, SQL Server, PostgreSQL, MySQL, Azure Table | +| Package storage | `simple2` file backend only | FileSystem, Azure Blob, S3, GCS, Aliyun OSS | +| Push auth | One API key (SHA256 hash in `LIGET_API_KEY_HASH`) | Global key, or accounts with scoped keys (on by default) | +| Accounts / owners | Not mentioned | Users, organizations, owners, OpenID Connect, 2FA | +| Upstream | Read-through cache of nuget.org packages on a separate endpoint (`/api/cache/v3/index.json`); no search for cached packages | Read-through into the same feed, merged version lists; search sees local/pulled packages only | +| Symbols | Not mentioned | Yes, portable PDBs only | +| Web UI | Not confirmed | Search, details, upload, manage, stats | +| Validation / signing | Not mentioned | Opt-in | +| Deployment | Docker image (`tomzo/liget`) | Docker, IIS, any host with .NET 10 | +| Licence | MIT | MIT | + +## When to choose which + +* Any new deployment: BaGet Extension (current runtime, active development). +* Existing LiGet with Paket workflows you cannot change: keep it, test Paket against BaGet Extension first. +* Need accounts, ownership, symbols, validation or non-SQLite databases: BaGet Extension. + +## Sources + +Checked 2026-10. + +* (README, MIT) +* (1.0.3, 2019-04-29) +* (describes LiGet as "an open-source implementation of NuGet V2 server"; the README says V3 plus limited V2) diff --git a/docs/vs/local-feeds.md b/docs/vs/local-feeds.md index 2cd716e0a..8eb2d2a7f 100644 --- a/docs/vs/local-feeds.md +++ b/docs/vs/local-feeds.md @@ -1,16 +1,37 @@ # Local Feeds -!!! warning - This page is a work in progress! +[Local feeds](https://learn.microsoft.com/en-us/nuget/hosting-packages/local-feeds), or "folder feeds", use a +folder or network share (e.g. `\\myserver\packages`) as a NuGet source. Add the path with the Package +Manager UI or `nuget sources`. -[Local feeds](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds), also known as "folder feeds", let you -use a folder as a NuGet package source. You can access these packages using a network share. +* Hierarchical layout (NuGet 3.3+): `//..nupkg`, created by `nuget add` (one package) or `nuget init` (a folder of packages). +* Older flat layout (single folder) works but is slower. -# BaGet vs local feeds +# BaGet Extension vs local feeds -Local feeds are very simple and are lack features like: +| Feature | Local feed | BaGet Extension | +| --- | --- | --- | +| Server needed | No (file access only) | Yes (HTTP service) | +| Protocol | File system, no HTTP API | V3, plus V2 at `/api/v2` | +| Search | Client-side: NuGet scans the folder (ID, tags, description); slow on large feeds | Server-side V3 search; Database provider matches package ID only | +| Web UI | No | Search, details, upload, manage, stats | +| Push auth | File-system permissions only | Global key, or accounts with scoped keys | +| Owners / accounts | No | Yes | +| Symbols | Not confirmed | Yes, portable PDBs only | +| Mirroring nuget.org | No | Optional read-through ([remote repositories](../remote-repositories.md)) | +| Storage | Folder or share | Folder, Azure Blob, S3, GCS, Aliyun OSS | +| Remote / internet access | Network share only | HTTP(S) | +| Setup / cost | Minimal | Run a .NET 10 service and a database | -1. Search functionality -1. A user interface to browse your packages -1. Authentication for package uploads -1. Cloud storage for large feeds +## When to choose which + +* One developer, a small team on one LAN, or an offline fallback: a local feed. +* Remote teams, CI over HTTP, authentication, search or symbols: BaGet Extension. +* Moving an existing folder feed into BaGet Extension: see [importing local feeds](../import/local-feeds.md). + +## Sources + +Checked 2026-10. + +* +* diff --git a/docs/vs/myget.md b/docs/vs/myget.md index 0950ba486..6ef0fdcf9 100644 --- a/docs/vs/myget.md +++ b/docs/vs/myget.md @@ -1,4 +1,38 @@ # MyGet -!!! warning - This page is a work in progress! \ No newline at end of file +[MyGet](https://www.myget.org) is a hosted package management service for NuGet and other formats. + +| Feature | MyGet | BaGet Extension | +|---|---|---| +| Package formats | NuGet, symbols, npm, Bower, Maven, PHP Composer, VSIX, Python, RubyGems | NuGet, npm, Maven, Docker | +| NuGet protocol | V3 (`/F//api/v3/index.json`), V2 (`/api/v2`), V1 | V3, plus V2 OData `/api/v2` (on by default) | +| Symbols | Symbol server per feed (`/F//symbols`) | Symbol server in the feed; portable PDBs only | +| Upstream / proxy | Proxy (metadata only) or mirror (copy on first request); mirrored packages count toward quota; update-check interval configurable (the Professional plan's 30-min interval was documented, but that plan is no longer sold) | [Remote repositories](../remote-repositories.md) (copy kept) and an optional `Mirror:Enabled` mirror; search does not query upstream | +| Multiple feeds | Private feeds per plan (1 / 5 / unlimited); public feeds on all plans | Many [repositories](../repositories.md) per instance, no plan limit | +| Private reads | Private feeds require basic auth or an API-key URL | Yes: private repositories, Basic auth or API key ([access control](../access-control.md)) | +| Permissions | Contributors per plan (1 / 5 / 10+); identity providers (Azure AD, ADFS, Okta) supported | Accounts, organizations, groups, permission targets, project roles, per-package owners | +| Accounts / API keys | MyGet accounts, access tokens, 2FA | Local accounts, OIDC, TOTP 2FA, scoped expiring API keys | +| Retention | Package retention feature exists (details not verified); custom retention available | [Retention policies](../retention.md); `Unlist` or `HardDelete` | +| UI | Web UI | Web UI | +| Hosting | SaaS; Enterprise on dedicated Azure infrastructure | Self-hosted .NET 10 | +| HA | Provider-managed | [High availability](../high-availability.md): several nodes on one database, object store and Redis (not on SQLite, the file system store or Azure Table) | +| Licence / cost | Developer $15/mo (500 MB), Team $40/mo (2 GB), Enterprise from $1,395/yr (4 GB); max package size 500 MB / 1 GB | MIT, free | +| Maintenance | Owned by Idera (via Assembla, 2018); operating (2026-09); docs' last release note 2020.1 | Community fork | + +## When to choose which + +- MyGet: hosted feed with no server to run, several formats, build services, license and vulnerability governance (Team and up). +- BaGet Extension: NuGet, npm, Maven and Docker, self-hosted, no plan limits on feeds, storage or contributors. +- Private reads: both have them. + +## Sources + +Checked 2026-10. + +- https://www.myget.org/pricing +- https://www.myget.org +- https://docs.myget.org/docs/reference/feed-endpoints +- https://docs.myget.org/docs/reference/upstream-sources +- https://www.ideracorp.com/pressreleases/acquires-assembla + +Unconfirmed: long-term roadmap; retention details; the docs still mention a "Professional" plan that the pricing page no longer lists. diff --git a/docs/vs/nexus.md b/docs/vs/nexus.md index e518ae399..b258c754f 100644 --- a/docs/vs/nexus.md +++ b/docs/vs/nexus.md @@ -1,4 +1,50 @@ # Nexus -!!! warning - This page is a work in progress! \ No newline at end of file +[Sonatype Nexus Repository](https://www.sonatype.com/products/sonatype-nexus-repository) is a multi-format repository manager; NuGet is one of its formats. + +| Feature | Nexus Repository | BaGet Extension | +|---|---|---| +| Formats | 27 formats (Maven, npm, Docker, PyPI, NuGet, ...) | NuGet, npm, Maven and Docker repositories (local, remote, virtual); `.nupkg`, `.snupkg`, tarballs, Maven files, OCI images | +| NuGet V3 | Yes | Yes: `/v3/index.json`; registration not paged | +| NuGet V2 | Yes | Yes: `/api/v2` OData, on by default (`Feeds:EnableV2`); `$filter`/`$orderby`/`$select`/`$expand` ignored | +| Symbols | `.snupkg` and Symbol Server protocol on proxy, hosted, group (new in 3.95.0) | Yes: `.snupkg` push, download endpoint; Portable PDB only | +| Proxy / upstream cache | Proxy repositories | [Remote repositories](../remote-repositories.md): per-repository upstream (NuGet, npm, Maven, Docker), credentials, cache periods, offline mode, purge; stored copies are permanent until purged; search does not query upstream | +| Virtual / group feeds | Group repositories (proxy + hosted + groups) behind one URL | [Virtual repositories](../virtual-repositories.md): ordered members (local, remote, nested virtual) behind one URL; uploads go to a chosen member | +| Multiple feeds | Many repositories per instance | Many [repositories](../repositories.md) per instance (`/r/{name}/`) | +| Private (authenticated) reads | Yes: anonymous access can be disabled (default anonymous role is read-only) | Yes: `AnonymousRead` per repository; a private one answers `401` + Basic challenge | +| Permissions model | Roles and privileges per repository; content selectors (path-based) | [Access control](../access-control.md): private repositories, groups, permission targets, project roles; anonymous read per repository; Basic auth or API key for reads; package ownership on top | +| Accounts / API keys | Users, NuGet API keys (NuGet API-Key realm); user tokens Pro only | Accounts (on in shipped config), OpenID Connect, TOTP 2FA, scoped expiring API keys, global `ApiKey` | +| Storage / DB backends | File (all editions); S3 (Community per feature matrix); Azure/GCS Pro only; H2 (default since 3.71) or PostgreSQL | File system, Azure Blob, S3, Google Cloud, Aliyun OSS; SQLite, SQL Server, PostgreSQL, MySQL, Azure Table | +| UI | Web UI (browse, admin, security) | Search, details, upload, stats, package management, account pages | +| Deployment | Self-hosted (Community: self-hosted only); Pro also Cloud | Self-hosted .NET 10 (Windows/Linux/macOS), Docker, IIS | +| HA / scale-out | Pro and Pro+ only (needs external PostgreSQL and shared S3/Azure blob storage) | [High availability](../high-availability.md): several nodes on one database, object store and Redis (not on SQLite, the file system store or Azure Table) | +| Licence / cost | Community free with usage limits; Pro/Pro+ paid | MIT, free; you pay only infrastructure | + +Editions (Sonatype tiers page): Community Edition, Pro, Pro+. + +| Edition | Limits | Notes | +|---|---|---| +| Community | 40,000 components or 100,000 requests/day; over either limit, no new components until back under both (usage updates hourly) | Free, self-hosted only, no HA; PostgreSQL available | +| Pro | No component limit listed | HA/clustering, SAML/OIDC SSO, cloud blob storage, DR replication; usage-based pricing | +| Pro+ | None listed | Adds malware quarantine, policy gates, licence compliance | + +## When to choose which + +- Nexus: more formats (PyPI, Conan, ...), vendor support, SSO and malware/policy features in Pro. +- BaGet Extension: NuGet, npm, Maven and Docker with remote and virtual repositories, access control, retention, scanning, replication and HA, with no usage cap and no licence cost. +- Nexus: when you need a format BaGet Extension lacks or vendor support. +- BaGet Extension: when NuGet, npm, Maven and Docker are enough and you want HA without a paid tier. + +## Sources + +Checked 2026-10. + +- +- +- +- +- +- +- +- +- BaGet Extension side: this fork's code and docs. diff --git a/docs/vs/nugetorg.md b/docs/vs/nugetorg.md index aaaea68f1..cc7a830c7 100644 --- a/docs/vs/nugetorg.md +++ b/docs/vs/nugetorg.md @@ -1,41 +1,67 @@ # nuget.org -!!! warning - This page is a work in progress! - -[nuget.org](https://www.nuget.org/), also known as the "Gallery", is the defacto feed to host open -source packages. You should publish NuGet packages for your open-source projects here. - -The Gallery is battle-tested and proven to scale well. You can find a guide on how to host -your own Gallery instance on [the Gallery's wiki](https://github.com/NuGet/NuGetGallery/wiki/Hosting-nuget.org's-v3-services). -You can find the Gallery's code on GitHub: - -* [NuGet/NuGetGallery](https://github.com/NuGet/NuGetGallery) - the [nuget.org](https://nuget.org) -website and v2 APIs -* [NuGet/NuGet.Jobs](https://github.com/NuGet/NuGet.Jobs/) - the Gallery's jobs for things like validation and package statistics. -* [NuGet/NuGet.Services.Metadata](https://github.com/NuGet/NuGet.Services.Metadata/) - NuGet's v3 implementation -* [NuGet/ServerCommon](https://github.com/NuGet/ServerCommon) - common libraries used across NuGet's services - -As you can tell, nuget.org is a complex beast. Hosting your own instance of the Gallery is not for the faint of heart. - -# BaGet vs nuget.org - -TODO. See [this issue](https://github.com/loic-sharma/BaGet/issues/71) for a deep-dive. - -* BaGet only competes with [NuGet/NuGet.Services.Metadata](https://github.com/NuGet/NuGet.Services.Metadata/) -* nuget.org's v3 implementation is static - * Runs only on Windows - * Highly tied to Azure - * Scales reads to near infinity - * Doesn't scale well for writes - * Static JSON files are hosted on Azure Blob Storage - * Served by a Content Delivery Network - * Files are updated by `feed2catalog`, `catalog2registration`, `catalog2dnx`, and `catalog2lucene` jobs -* BaGet's v3 implementation is dynamic - * Cross-platform implementation - * Requests are served by a service that queries a database - * Simpler architecture, which makes it easier to deploy and run small feeds - * Easier to scale for writes - * Harder to scale for reads - * Easier to add new features - * Harder to make as reliable \ No newline at end of file +[nuget.org](https://www.nuget.org/), the "Gallery", is the default public NuGet feed. Publish open-source +packages there; use BaGet Extension for private or mirrored feeds. + +Gallery code (self-hosting is possible but not simple; the +[hosting wiki](https://github.com/NuGet/NuGetGallery/wiki/Hosting-nuget.org's-v3-services) was last edited in 2018, so verify it before use): + +* [NuGet/NuGetGallery](https://github.com/NuGet/NuGetGallery) - website, jobs, V3 pipeline and search +* NuGet.Jobs, NuGet.Services.Metadata and ServerCommon are archived and merged into NuGetGallery + +# BaGet Extension vs nuget.org + +| Feature | nuget.org | BaGet Extension | +| --- | --- | --- | +| Visibility | Public; no private packages | Public or internal; private repositories with Basic auth or API key reads ([access control](../access-control.md)) | +| V3 (push, restore, search, autocomplete, registration) | Yes | Yes (registration not paged) | +| V2 (OData) | Yes | Yes, on by default (`Feeds:EnableV2`); `$skip`/`$top`, `searchTerm`, `id`, `includePrerelease`, `semVerLevel`; `$filter`/`$orderby`/`$select`/`$expand` ignored | +| Symbols (`.snupkg`) | Yes | Yes, portable PDBs only | +| Catalog | Yes | Yes, relational DB only (`catalog rebuild` to backfill) | +| Vulnerability info | Yes | Manual entry through the [API](../advanced/api.md), plus [scanning](../vulnerability-scanning.md) against OSV.dev (online or offline copy), off by default | +| Deprecation | Yes | Manual (API or manage page) | +| Accounts, organizations, owners | Yes (Microsoft/Entra login) | Yes, on by default (`Accounts:Enabled=true` in shipped settings); optional OpenID Connect | +| API keys | Yes: scoped (glob), expiring; new keys max 30 days since 2026-08-17, older keys expire 2026-11-01 | Global `ApiKey`, plus scoped expiring per-account keys (on with accounts) | +| Two-factor sign-in | Required since 2022-03-08 (via MSA/Entra) | TOTP + recovery codes | +| ID prefix reservation | Yes | Not supported (per-ID verified-owner flag only, no UI) | +| Validation before serving | Yes | Opt-in (`Validation:Enabled`), in-process; no malware scanner built in | +| Repository signing | Yes | Opt-in (needs a certificate) | +| Package size limit | 250 MB | About 2 GB for push and upload (multipart limit); IIS 250 MB | +| Deletion | Generally not supported ([policy](https://learn.microsoft.com/en-us/nuget/nuget-org/policies/deleting-packages)) | Unlist (default) or hard delete; overwrite off by default | +| Mirroring | n/a | [Remote repositories](../remote-repositories.md) (per repository) and the optional `Mirror:Enabled` mirror; search does not query upstream | +| Download statistics | Not re-verified | Totals plus `/stats` page; no per-day | +| Search | Full index | Package ID substring only (`Database`), or Azure Search | +| Administration | Admin-only Settings page (edits settings, marks restart-required ones); copy of all data between SQLite, SQL Server, PostgreSQL and MySQL behind a read-only gate; optional SMTP email | +| Web UI | Full Gallery | Search, details, upload, manage, stats, account | +| Storage / DB | Azure (Blob, SQL, Search, CDN) | FileSystem, Azure Blob, S3, GCS, Aliyun OSS; SQLite, SQL Server, PostgreSQL, MySQL, Azure Table | +| Platform | Azure-hosted service | .NET 10, Windows/Linux/macOS, Docker, IIS | +| Scale / HA | Global, CDN-backed | Single node, or several with [high availability](../high-availability.md) (database, object store and Redis shared) | +| Licence / cost | Free service; Gallery code Apache-2.0 | MIT, self-hosted, infrastructure cost only | + +## Architecture + +* nuget.org V3 is static (JSON on blob storage behind a CDN, built by catalog jobs): reads scale + almost without limit, writes and operation are heavy and tied to Azure. +* BaGet Extension V3 is dynamic (service plus database): simple to deploy, easy to extend, weaker read + scaling and reliability. + +## When to choose which + +* Publish public open-source packages: nuget.org. +* Internal or private packages, or a cache of nuget.org for CI or offline use: BaGet Extension. +* Need CDN-scale reads or prefix reservation: nuget.org. +* Need your own accounts, ownership and validation on infrastructure you control: BaGet Extension. + +See also [importing from nuget.org](../import/nugetorg.md) and [configuration](../configuration.md). + +## Sources + +Checked 2026-10. + +* +* +* +* (Apache-2.0, active) +* +* (API key expiry) +* diff --git a/docs/vs/nugetserver.md b/docs/vs/nugetserver.md index f0fd1bb13..5fd86b38c 100644 --- a/docs/vs/nugetserver.md +++ b/docs/vs/nugetserver.md @@ -1,21 +1,41 @@ # NuGet.Server -!!! warning - This page is a work in progress! +[NuGet.Server](https://github.com/NuGet/NuGet.Server) is a ASP.NET (.NET Framework) application +that serves a folder of packages over HTTP (OData). **It is deprecated**: the repository was archived on +2026-05-29 and its README states no further features, bug fixes or security patches. Migrate; see the +[migration guide](../import/nugetserver.md). -[NuGet.Server](https://github.com/NuGet/NuGet.Server) is a lightweight standalone NuGet server. It is strongly recommended that you upgrade to BaGet if you use NuGet.Server. Feel free to open [GitHub issues](https://github.com/loic-sharma/BaGet/issues) if you need help migrating. +# BaGet Extension vs NuGet.Server -* NuGet.Server - * Only runs on Windows - * Supports NuGet v2 APIs (missing verified packages, signed packages, etc...) - * Doesn't support NuGet's v3 APIs - * Does not scale well - * Not well documented - * Not well maintained -* BaGet - * Cross-platform - * Supports NuGet v3 APIs +| Feature | NuGet.Server | BaGet Extension | +| --- | --- | --- | +| Maintenance | Deprecated, archived 2026-05-29 (last release 3.4.3, same day) | Maintained fork | +| Platform | ASP.NET Web Application (.NET Framework 4.6) on IIS | .NET 10; Windows/Linux/macOS, Docker, IIS | +| Protocols | OData V2 only | V3, plus V2 OData at `/api/v2` (on by default) | +| Symbols | No symbol server (`ignoreSymbolsPackages`, default true) | Yes, portable PDBs only | +| Push auth | One shared API key (`apiKey`, `requireApiKey`) | Global key, or accounts with scoped expiring keys (on by default) | +| Accounts / owners | No | Users, organizations, package owners, OpenID Connect, 2FA | +| Delete | Delete, or delist via `enableDelisting` | Unlist (default) or hard delete; relist | +| Mirroring | No | Remote repositories and optional read-through mirror | +| Storage | Folder (`packagesPath`) | FileSystem, Azure Blob, S3, GCS, Aliyun OSS | +| Database | None (folder scan) | SQLite, SQL Server, PostgreSQL, MySQL, Azure Table | +| Search | OData queries (V2 only) | V3 search; package ID substring match | +| Web UI | Feed home page only | Search, details, upload, manage, stats | +| Validation / signing | No | Opt-in validation and repository signing | +| Scale / HA | Not documented | Single node, or [high availability](../high-availability.md) | +| Licence / cost | Apache-2.0, free | MIT, free | -## Migration Guide +## When to choose which -You can use the [NuGet.Server migration](../import/nugetserver.md) guide to import your NuGet.Server packages into BaGet. \ No newline at end of file +* New feed, or any feed that must stay patched: BaGet Extension. +* Existing NuGet.Server that must keep running unchanged on IIS: it works, but gets no fixes; plan the move. +* Need V3-only clients, symbols, accounts or cross-platform hosting: BaGet Extension. + +## Sources + +Checked 2026-10. + +* (archived, deprecation notice, Apache-2.0) +* (3.4.3, 2026-05-29) +* +* diff --git a/docs/vs/teamcity.md b/docs/vs/teamcity.md index 58d545f02..45d6d3a4d 100644 --- a/docs/vs/teamcity.md +++ b/docs/vs/teamcity.md @@ -1,4 +1,40 @@ # TeamCity -!!! warning - This page is a work in progress! \ No newline at end of file +[TeamCity](https://www.jetbrains.com/teamcity/) is the JetBrains CI/CD server. Its built-in NuGet feed serves packages produced by its own builds; it is not a general package registry. + +| Feature | TeamCity built-in feed | BaGet Extension | +|---|---|---| +| Package formats | NuGet only | NuGet, npm, Maven, Docker | +| NuGet protocol | V1, V2, V3 (`.../app/nuget/feed///v1`, `/v2`, `/v3/index.json`) | V3, plus V2 OData `/api/v2` | +| What it serves | `.nupkg` build artifacts, indexed per build configuration or project | Any pushed package | +| Push | Only from a build (feed URL + `%teamcity.nuget.feed.api.key%`); external pushes fail | Any client: `PUT /api/v2/package`, browser upload | +| Symbols | Not built in; separate TeamCity Symbol Server plugin (Symbol Files Indexer). TW-25512: symbol packages in the feed can break external source servers | Symbol server (portable PDBs) | +| Upstream / proxy | None found | [Remote repositories](../remote-repositories.md), optional mirror | +| Multiple feeds | Several feeds per project | Many [repositories](../repositories.md) per instance | +| Private reads | Basic auth needs "View project" permission; guest access optional | Yes: private repositories ([access control](../access-control.md)) | +| Permissions | TeamCity project permissions | Accounts, organizations, groups, permission targets, per-package owners | +| Accounts / API keys | TeamCity users, access tokens | Local accounts, OIDC, 2FA, scoped API keys | +| Retention | Tied to build artifacts: removed on artifact cleanup; pin the build to keep | [Retention policies](../retention.md), or manual `Unlist` / `HardDelete` | +| UI | TeamCity UI | Package search, details, stats, manage | +| Hosting | On-Premises, or TeamCity Cloud (JetBrains-hosted; details not verified) | Self-hosted .NET 10 | +| HA | On-Premises Enterprise: secondary HA nodes need no licence | [High availability](../high-availability.md): several nodes on one database, object store and Redis (not on SQLite, the file system store or Azure Table) | +| Licence / cost | Free Professional on-prem: 3 agents, 100 build configurations, 10 pipelines, community support; Enterprise paid | MIT, free | +| Maintenance | Active JetBrains product (2026.2 help) | Community fork | + +## When to choose which + +- TeamCity feed: packages are CI outputs consumed by other builds, with lifetime tied to the builds. +- BaGet Extension: a permanent feed that outlives builds, accepts pushes from any client, needs symbols or mirroring. +- Together: TeamCity builds and pushes to BaGet Extension with the NuGet Publish step. + +## Sources + +Checked 2026-10. + +- https://www.jetbrains.com/help/teamcity/using-teamcity-as-nuget-feed.html +- https://www.jetbrains.com/help/teamcity/nuget.html +- https://www.jetbrains.com/help/teamcity/licensing-policy.html +- https://www.jetbrains.com/help/teamcity/teamcity-cloud.html +- https://blog.jetbrains.com/teamcity/2015/02/setting-up-teamcity-as-symbol-and-source-server/ + +Unconfirmed: TeamCity Cloud pricing and feature differences; the missing upstream support is inferred from the pages read. diff --git a/docs/vulnerability-scanning.md b/docs/vulnerability-scanning.md new file mode 100644 index 000000000..e202c7cca --- /dev/null +++ b/docs/vulnerability-scanning.md @@ -0,0 +1,107 @@ +# Vulnerability scanning + +Artifacts are checked against vulnerability databases; findings are shown on every package page and in an +administrator dashboard, feed NuGet's vulnerability resource, and a per-repository **policy** can warn about them or refuse +downloads and deploys with `403` and the reason. Off by default (`Scanning:Enabled`): scanning calls OSV.dev. + +## What is scanned, and by what + +| Format | Scanned | Source | +|---|---|---| +| NuGet | the package and each dependency at the lowest version of its range (the version NuGet restores); a dependency without a lower bound is skipped | OSV, ecosystem `NuGet` | +| npm | the version and its `dependencies` that name **one exact version** (`1.2.3`); ranges (`^1.2.0`) are resolved by the client and cannot be judged here | OSV, `npm` | +| Maven | the artifact and the POM's compile and runtime dependencies with a literal version (`1.2.3`, or the lower bound of `[1.2,2.0)`); property, managed, `test`, `provided` and optional dependencies are skipped | OSV, `Maven` (`group:artifact`) | +| Docker | each image manifest (not indexes, signatures or other artifacts that refer to an image; each platform's manifest is) | Trivy, optional | + +A remote repository scans what it has cached (the first download of a version is served before it can be scanned); a virtual +repository holds nothing and has no results of its own (its members do). Azure Table storage (no relational database) cannot scan. + +## Data sources and licensing (B5) + +| Source | Use | Licence and attribution | +|---|---|---| +| [OSV.dev](https://osv.dev) API (`POST /v1/querybatch`, `GET /v1/vulns/{id}`) | default, online | the API is free; each record keeps the licence of its source (GitHub Advisory Database: CC-BY 4.0; others per OSV's [data licences](https://google.github.io/osv.dev/data/)). Every advisory in the UI shows its id and links to its source; the pages name OSV.dev | +| An offline copy of the OSV data (`Scanning:OsvOfflinePath`) | no internet | a directory (searched recursively for `*.json`) or a `.zip` of OSV records, e.g. `https://osv-vulnerabilities.storage.googleapis.com/NuGet/all.zip` (also `npm`, `Maven`); same licences. Reloaded when the path changes (checked every 30 s). When set, the online API is never contacted | +| [Trivy](https://trivy.dev) | container images | Apache-2.0; run as an external executable, its databases are Trivy's | + +OSV answers per package and version, so a record is matched by the server, not by BaGet. In an offline copy BaGet matches +`affected` ranges itself (`SEMVER`/`ECOSYSTEM` events, explicit `versions`; `GIT` ranges are ignored). Severity: the record's +`database_specific.severity` (GitHub), else the CVSS v3 base score computed from its vector, else `ecosystem_specific.severity`, +else **Moderate** (CVSS v4 vectors carry no number and are not computed). + +## Configuration + +| Key | Default | Meaning | +|---|---|---| +| `Scanning:Enabled` | `false` | master switch: nothing is scanned, no policy is enforced, package pages show no section. Live | +| `Scanning:ScanOnDeploy` | `true` | queue a scan when a version is stored (publish, push, deploy, cache fill). Off: the schedule and *Scan now* only | +| `Scanning:RescanInterval` | `1.00:00:00` | a background sweep (every 10 minutes) scans versions whose last scan is older; zero or negative: never | +| `Scanning:OsvUrl` | `https://api.osv.dev` | the OSV API root | +| `Scanning:OsvOfflinePath` | empty | directory or zip of OSV records (offline mode) | +| `Scanning:OsvTimeout` | `00:00:30` | one OSV request | +| `Scanning:OsvCacheLifetime` | `01:00:00` | answers per component are reused this long (in memory, per node) | +| `Scanning:TrivyPath` | empty | the `trivy` executable; without it (or the registry host) images are **not scanned** and the UI says so | +| `Scanning:TrivyRegistryHost` | empty | this server's registry address as Docker clients use it (`registry.example.com`, `host:port`); images are named `{host}/{repository}/{image}@{digest}` | +| `Scanning:TrivyServerUrl` | empty | passed as `--server`: Trivy's database and analysis live on a `trivy server`; the executable is still run | +| `Scanning:TrivyInsecure` | `false` | `--insecure` and `TRIVY_NON_SSL`, for a registry without TLS | +| `Scanning:TrivyRegistryUser`, `Scanning:TrivyRegistryPassword` | empty | credentials Trivy pulls with (an API key as the password when accounts are on); passed in `TRIVY_USERNAME`/`TRIVY_PASSWORD`, never on the command line; the password is a sensitive setting. **Multi-node deployments must set the user**: without one, the scanner's pull is recognised from an in-memory, per-process list of running scans, so a pull answered by another node is not exempt | +| `Scanning:TrivyTimeout` | `00:10:00` | one Trivy run | + +## Policies + +One policy per **repository** or **project** (`ScanPolicies`; deleting the repository or the project deletes its policy); a repository's own policy replaces its project's. Each threshold +is Low, Moderate, High or Critical ("and above"), or off. + +| Setting | Effect | +|---|---| +| Warn | the package page shows a warning for a version with a finding at or above the threshold | +| Block download | such a version cannot be downloaded: `403` with the reason (below) | +| Block deploy | an artifact whose own coordinates or declared dependencies have such a finding is refused with `403` **before anything is stored** (NuGet, npm, Maven); a container image cannot be inspected before it is stored, so it is scanned right after the push and removed again when it reaches the threshold. A vulnerability source that is down lets the deploy through (logged) | +| Block unscanned | a stored, scannable version with no successful scan cannot be downloaded (a scan is queued; the first download of a version a remote repository has not fetched yet is not refused, since fetching it is what lets it be scanned). Not enforced while no engine can scan the repository (Trivy not configured, scanning off), for Docker indexes and artifacts whose config is not an image config (a manifest is an image by its media type and its config's media type; the self-declared `artifactType` and `subject` are ignored, as the runtimes ignore them), or for the scanner's own pull (the user named by `Scanning:TrivyRegistryUser`; without one, any pull while an image with no successful scan is being scanned; the severity block is never lifted for an image already scanned). Through a virtual repository the member that stores the version applies its own setting, scanned or not | + +Only **stored results** decide a download, so a new advisory takes effect at the next scan (schedule, *Scan now*, or the +operation). Policy lookups are remembered for 5 seconds per node. + +### Where a refusal shows + +| Format | Download refused | Deploy refused | +|---|---|---| +| NuGet | `GET v3/package/{id}/{version}/{id}.{version}.nupkg` (metadata, nuspec, readme and icon stay readable): `403`, plain text | `PUT api/v2/package` and the Upload page: `403` plus the reason | +| npm | tarball `GET npm/{name}/-/{file}`: `403 {"error": reason}` (the packument stays readable) | `PUT npm/{name}` and the Upload page | +| Maven | any file of the version except `maven-metadata.xml`: `403`, plain text | `PUT` of a POM (dependencies) or any file (the artifact itself), and the Upload page | +| Docker | `GET`/`HEAD manifests/{tag or digest}` of an image: `403 {"errors":[{"code":"DENIED"…}]}`. An index is not refused (its platform manifests are). Layers are content-addressed and are **not** blocked on their own | `PUT manifests`: the image is scanned, removed again and answered `403 DENIED` when it reaches the threshold | + +In a virtual repository the first member the caller can read that has a result for the version decides, under that member's policy (the same members the content is served from). + +## NuGet's vulnerability resource + +What a scan finds about **the package version itself** is written to `PackageVulnerabilities` (`Source` = `osv`) and so appears in +`v3/vulnerabilities/*` and in registration (`vulnerabilities`) and search results; a client matches its own restore graph +against it. Entries set by hand (the metadata API, the Manage page) have no `Source` and are never touched by a scan; setting the +list by hand replaces the manual entries only, and the Manage page lists the scanner's as read-only. Advisories about dependencies +are those packages' own entries. + +## Web UI + +| Page | What | +|---|---| +| Package pages (`/packages/{id}/{version}`, `/npm-packages/{name}`, `/maven-artifacts/{group}/{artifact}/{version}`, `/docker-images/{image}?digest=`) | *Vulnerabilities* section: state (clean, findings with severity, advisory link, component, fixed-in, summary; not scanned; scanning unavailable, e.g. "Trivy is not configured"), the policy's warning or refusal, *Scan now* for people who may manage the package | +| `/scan-artifact?name=&version=` | *Scan now* of one version (signed in, may manage the package; an image is queued, the rest scanned before the answer); also at `/r/{repo}/scan-artifact` | +| `/admin/scanning` | engines in use, every repository with its counts and policy, projects | +| `/admin/scanning/{repository}` | counts by severity, versions with findings (filter, paging), the policy editor (password asked), *Scan the whole repository now* (the `vulnerability-scan` operation, also on Operations) | +| `/admin/scanning/projects/{name}` | the project's policy (password asked) | +| Admin Settings | every `Scanning:*` key | + +Scanning a version needs the Manage permission on the package (the access model plus ownership), a repository dashboard or a policy +needs an administrator; without accounts only the schedule and scan-on-deploy scan. Every write is refused with `503` while the +server is read-only. + +## Limits + +- Results and policies are database rows shared by every node; OSV answers, the offline index and the 5-second policy cache are per node, in memory. +- At most 1000 findings are kept per version (worst first). +- Layers of a blocked Docker image can still be fetched by digest; the manifest is what is refused. +- A store (push, publish, deploy, cache fill) forgets the earlier result of the same name and version (for Maven only when the file is the main POM, the one file the scan reads; other files just queue a scan): it described other bytes, and would count as a scan for *Block unscanned*. The next scan makes a new one. +- A **pass-through** remote repository (`StoreLocally=false`) stores nothing, so there is nothing to scan: its download policies (*Block download*, *Block unscanned*) have no effect there. Use a caching remote repository to enforce them. +- One artifact that cannot be scanned (unreadable file, unexpected error) is recorded as a failed result and the repository sweep goes on with the next one. +- Names longer than 400 characters or versions longer than 200 are not scanned. diff --git a/global.json b/global.json new file mode 100644 index 000000000..9e9a6858a --- /dev/null +++ b/global.json @@ -0,0 +1,9 @@ +{ + "sdk": { + "version": "10.0.402", + "rollForward": "latestFeature" + }, + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/mkdocs.yml b/mkdocs.yml index 82c25d0b9..67cc8c750 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,10 +1,10 @@ -site_name: BaGet -site_description: A lightweight NuGet and symbol server +site_name: BaGet Extension +site_description: A NuGet, Maven, NVM, Docker and symbol server site_author: Loic Sharma -site_url: https://loic-sharma.github.io/BaGet/ +site_url: https://pieroviano.github.io/BaGet/ -repo_name: loic-sharma/BaGet -repo_url: https://github.com/loic-sharma/BaGet +repo_name: pieroviano/BaGet +repo_url: https://github.com/pieroviano/BaGet copyright: 'Copyright © 2020 Loic Sharma' @@ -20,10 +20,8 @@ theme: extra: social: - - type: github-alt - link: https://github.com/loic-sharma - - type: twitter - link: https://twitter.com/bagetapp + - icon: fontawesome/brands/github + link: https://github.com/pieroviano/BaGet markdown_extensions: - markdown.extensions.admonition @@ -32,8 +30,15 @@ markdown_extensions: - markdown.extensions.toc: permalink: true -pages: +# Plan documents are working notes, never published (CLAUDE.md). +exclude_docs: | + plans/ + +nav: - Overview: index.md + - Installation manual: installation-manual.md + - DevOps manual: devops-manual.md + - How-to: howto.md - Installation: - On your computer: installation/local.md - Docker: installation/docker.md @@ -42,15 +47,35 @@ pages: - Google cloud: installation/gcp.md - Alibaba cloud: installation/aliyun.md - Windows IIS proxy: installation/iis-proxy.md + - User manual: user-manual.md - Configuration: configuration.md + - Repositories: repositories.md + - Package formats: formats.md + - npm registry: npm-registry.md + - Maven repositories: maven-repositories.md + - Docker registry: docker-registry.md + - Retention and cleanup: retention.md + - Remote repositories: remote-repositories.md + - Replication: replication.md + - High availability: high-availability.md + - Virtual repositories: virtual-repositories.md + - Access control: access-control.md + - Vulnerability scanning: vulnerability-scanning.md + - Administration REST API: admin-api.md + - UI API (/api/ui): ui-api.md + - Custom frontend (React, Angular): custom-frontend.md + - Testing the APIs with Scalar: scalar.md + - UI coverage: ui-coverage.md - Import: - Local feeds: import/local-feeds.md - NuGet.Server: import/nugetserver.md - NuGet.org: import/nugetorg.md - Advanced: + - Architecture: advanced/architecture.md - Debugging: advanced/debugging.md - - BaGet SDK: advanced/sdk.md - - BaGet vs. other: + - BaGet Extension SDK: advanced/sdk.md + - Server API: advanced/api.md + - BaGet Extension vs. other: - nuget.org: vs/nugetorg.md - NuGet.Server: vs/nugetserver.md - Local feeds: vs/local-feeds.md diff --git a/nuget.config b/nuget.config index fbcef1011..98a8fe27f 100644 --- a/nuget.config +++ b/nuget.config @@ -1,7 +1,7 @@ - + - - - - - + + + + + \ No newline at end of file diff --git a/readme.md b/readme.md index c7c22dfe6..d754d2ba1 100644 --- a/readme.md +++ b/readme.md @@ -1,48 +1,75 @@ -# BaGet :baguette_bread: +# BaGet Extension :baguette_bread: -![Build status] [![Discord][Discord image]][Discord link] [![Twitter][Twitter image]][Twitter link] +![Build status] -A lightweight [NuGet] and [symbol] server. +A [NuGet], npm, Maven and Docker registry and [symbol] server.

- +

## Getting Started -1. Install the [.NET SDK] -2. Download and extract [BaGet's latest release] +1. Install the [.NET SDK] (BaGet Extension targets .NET 10) +2. Download the `BaGet` artifact of a [Release workflow] run, or build it from source (see [CONTRIBUTING.md](CONTRIBUTING.md)) 3. Start the service with `dotnet BaGet.dll` -4. Browse `http://localhost:5000/` in your browser +4. Browse `http://localhost:6060/` in your browser (the port is set by `Kestrel:Endpoints` in `appsettings.json`) +5. Sign in as the default administrator `Admin` / `Admin1234!` (created on a fresh install) and change that password at once ([details](docs/configuration.md#default-administrator)) -For more information, please refer to the [documentation]. +For more information, please refer to the [documentation]. To build and test from source (nuget.config lists the untracked `Packages` folder as a package source, so create it once): + +``` +mkdir Packages +dotnet build BaGet.sln -p:GeneratePackageOnBuild=false +dotnet test BaGet.sln -p:GeneratePackageOnBuild=false +``` + +The screenshot above shows the upstream project's UI, not the current one. ## Features * **Cross-platform**: runs on Windows, macOS, and Linux! -* **Cloud native**: supports [Docker], [Azure], [AWS], [Google Cloud], [Alibaba Cloud] +* **Cloud native**: runs in [Docker], [Azure], [AWS], [Google Cloud], [Alibaba Cloud] +* **Four databases**: SQLite, SQL Server, PostgreSQL and MySQL, plus Azure Table Storage +* **Repositories and formats**: several [repositories] per server (`/r/{name}/`), each NuGet, [npm], [Maven] or [Docker registry] (OCI) +* **Remote and virtual repositories**: [cache an upstream] (NuGet, npm, Maven, Docker; offline mode, purge) and [merge several repositories] behind one URL * **Offline support**: [mirror a NuGet server] to speed up builds and enable offline downloads +* **NuGet V3 protocol**, including the catalog, vulnerability info, deprecation, report abuse and package details templates +* **NuGet V2 (OData) feed** for `nuget list`, older clients and PowerShellGet (on by default; `Feeds:EnableV2=false` turns it off) +* **Accounts** (on by default; `Accounts:Enabled=false` restores the global `ApiKey` alone; while `ApiKey` is empty, pushes need a user API key): sign-in, OpenID Connect, package owners, organizations and scoped, expiring API keys +* **Access control**: groups, permission targets, project roles, private repositories and an audit log ([access control]) +* **Validation pipeline** (opt-in): packages are checked before they are served, and can be repository signed +* **Retention**, **vulnerability scanning** (OSV.dev, Trivy; opt-in) and **replication** between BaGet servers: [retention], [scanning], [replication] +* **High availability** (opt-in): several nodes on one database, object store and Redis ([high availability]) +* **Administration REST API** (`/api/v1`, OpenAPI 3) and admin pages for everything the API does: [admin API] +* **OpenTelemetry export** (traces, metrics, logs; needs an OTLP endpoint) and a live Settings page +* **Web UI**: package pages (with "Open in NuGet Package Explorer", web and desktop), owner management pages, profiles, statistics and abuse reports -Stay tuned, more features are planned! - -[Build status]: https://img.shields.io/github/actions/workflow/status/loic-sharma/BaGet/.github/workflows/main.yml -[Discord image]: https://img.shields.io/discord/889377258068930591 -[Discord link]: https://discord.gg/MWbhpf66mk -[Twitter image]: https://img.shields.io/twitter/follow/bagetapp?label=Follow -[Twitter link]: https://twitter.com/bagetapp +[Build status]: https://img.shields.io/github/actions/workflow/status/pieroviano/BaGet/main.yml?branch=main [NuGet]: https://learn.microsoft.com/nuget/what-is-nuget [symbol]: https://docs.microsoft.com/en-us/windows/desktop/debug/symbol-servers-and-symbol-stores [.NET SDK]: https://www.microsoft.com/net/download -[Node.js]: https://nodejs.org/ -[BaGet's latest release]: https://github.com/loic-sharma/BaGet/releases +[Release workflow]: https://github.com/pieroviano/BaGet/actions/workflows/release.yml -[Documentation]: https://loic-sharma.github.io/BaGet/ -[Docker]: https://loic-sharma.github.io/BaGet/installation/docker/ -[Azure]: https://loic-sharma.github.io/BaGet/installation/azure/ -[AWS]: https://loic-sharma.github.io/BaGet/installation/aws/ -[Google Cloud]: https://loic-sharma.github.io/BaGet/installation/gcp/ -[Alibaba Cloud]: https://loic-sharma.github.io/BaGet/installation/aliyun/ +[Documentation]: docs/index.md +[Docker]: docs/installation/docker.md +[Azure]: docs/installation/azure.md +[AWS]: docs/installation/aws.md +[Google Cloud]: docs/installation/gcp.md +[Alibaba Cloud]: docs/installation/aliyun.md -[Mirror a NuGet server]: https://loic-sharma.github.io/BaGet/configuration/#enable-read-through-caching \ No newline at end of file +[Mirror a NuGet server]: docs/configuration.md#enable-read-through-caching +[Repositories]: docs/repositories.md +[npm]: docs/npm-registry.md +[Maven]: docs/maven-repositories.md +[Cache an upstream]: docs/remote-repositories.md +[Merge several repositories]: docs/virtual-repositories.md +[Access control]: docs/access-control.md +[Retention]: docs/retention.md +[Scanning]: docs/vulnerability-scanning.md +[Replication]: docs/replication.md +[High availability]: docs/high-availability.md +[Admin API]: docs/admin-api.md +[Docker registry]: docs/docker-registry.md diff --git a/samples/BaGet.Frontend.Angular/.editorconfig b/samples/BaGet.Frontend.Angular/.editorconfig new file mode 100644 index 000000000..f166060da --- /dev/null +++ b/samples/BaGet.Frontend.Angular/.editorconfig @@ -0,0 +1,17 @@ +# Editor configuration, see https://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.ts] +quote_type = single +ij_typescript_use_double_quotes = false + +[*.md] +max_line_length = off +trim_trailing_whitespace = false diff --git a/samples/BaGet.Frontend.Angular/.gitignore b/samples/BaGet.Frontend.Angular/.gitignore new file mode 100644 index 000000000..854acd5fc --- /dev/null +++ b/samples/BaGet.Frontend.Angular/.gitignore @@ -0,0 +1,44 @@ +# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. + +# Compiled output +/dist +/tmp +/out-tsc +/bazel-out + +# Node +/node_modules +npm-debug.log +yarn-error.log + +# IDEs and editors +.idea/ +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# Visual Studio Code +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/mcp.json +.history/* + +# Miscellaneous +/.angular/cache +.sass-cache/ +/connect.lock +/coverage +/libpeerconnection.log +testem.log +/typings +__screenshots__/ + +# System files +.DS_Store +Thumbs.db diff --git a/samples/BaGet.Frontend.Angular/.npmrc b/samples/BaGet.Frontend.Angular/.npmrc new file mode 100644 index 000000000..521a9f7c0 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/.npmrc @@ -0,0 +1 @@ +legacy-peer-deps=true diff --git a/samples/BaGet.Frontend.Angular/.prettierrc b/samples/BaGet.Frontend.Angular/.prettierrc new file mode 100644 index 000000000..d6c16d7ee --- /dev/null +++ b/samples/BaGet.Frontend.Angular/.prettierrc @@ -0,0 +1,12 @@ +{ + "printWidth": 100, + "singleQuote": true, + "overrides": [ + { + "files": "*.html", + "options": { + "parser": "angular" + } + } + ] +} diff --git a/samples/BaGet.Frontend.Angular/README.md b/samples/BaGet.Frontend.Angular/README.md new file mode 100644 index 000000000..c4b6248db --- /dev/null +++ b/samples/BaGet.Frontend.Angular/README.md @@ -0,0 +1,70 @@ +# BaGet.Frontend.Angular + +Minimal Angular (standalone components, signals, strict TypeScript, reactive forms) single-page application for BaGet, written +against the JSON UI API (`/api/ui`, see `docs/ui-api.md`) only. It shows packages, package detail, sign-in (password, two-factor, +recovery code, external provider), register / forgot / reset password / confirm email, and one administrator screen (users). + +## Prerequisites + +Node 22+ (or Docker: `docker run --rm -v "$PWD:/app" -w /app node:22-alpine sh -c "npm install && npx ng build"`) and a BaGet with +accounts on (default administrator `Admin` / `Admin1234!`). + +## BaGet settings + +| Use | Settings | +|---|---| +| Development (`npm start`, http://localhost:4200, BaGet on another origin) | `Cors:AllowedOrigins=http://localhost:4200`. Without it the session endpoints refuse a browser from another origin (`403`). Set `Frontend:SpaUrl=http://localhost:4200` so emails link to the dev server. Point `src/environments/environment.development.ts` at your BaGet (default `http://localhost:6060`) | +| Hosted by BaGet under `/app` | `npm run build`, then `Frontend:SpaPath=/dist/baget-frontend-angular/browser`, `Frontend:SpaBasePath=/app` (the build uses `baseHref=/app/`; `apiBaseUrl` is empty = same origin, so no CORS) | +| Emails link to this app | `Frontend:SpaLinks=true` (or `Frontend:Mvc=false`), or `Frontend:SpaUrl=` when the app is hosted elsewhere: `/app/confirm-email`, `/app/reset-password`, `/app/sign-in` are routes here | +| External sign-in (OIDC) | the return address `{origin}{base}sign-in/external` must be under `Frontend:SpaBasePath` (same origin) or an origin of `Cors:AllowedOrigins`. The app adds a random `state` to that address (saved in `sessionStorage`) and exchanges the token only when it comes back unchanged; each exchange token works once | + +A different base path: change `baseHref` in `angular.json` (production configuration) and `Frontend:SpaBasePath` together. + +## Commands + +| Command | Does | +|---|---| +| `npm install` | installs (`.npmrc` sets `legacy-peer-deps`: openapi-typescript 7 still declares a TypeScript 5 peer) | +| `npm start` | dev server on 4200, development environment | +| `npm run build` | production build into `dist/` | +| `npm run gen:api` | regenerates `src/app/api/schema.d.ts` from `openapi/ui.json` | +| `npm run smoke` | `scripts/smoke.mjs` against a running BaGet: `BAGET_URL=http://localhost:6060 BAGET_USER=Admin BAGET_PASSWORD=... npm run smoke` | + +## Regenerating the client + +`openapi/ui.json` is the `ui` OpenAPI document. Download a fresh one with an administrator's `admin:api` key (API Keys page) or the +global `ApiKey` (anyone else gets `404`), then `npm run gen:api`: + +``` +curl -H "Authorization: Bearer " http://localhost:6060/openapi/ui.json -o openapi/ui.json +``` + +## How it is built + +| Piece | Where | Notes | +|---|---|---| +| Typed client | `src/app/api/api-client.ts`, `api-types.ts` | A thin wrapper over `HttpClient`: path, method, query/path values, body and answer are derived from the generated `paths` type. Chosen over openapi-fetch because the Angular interceptor, DI and RxJS pipeline stay the single HTTP stack (one place for the token and the refresh), and the wrapper is ~100 lines. Only types are generated, no runtime code | +| `ScreenResult` | `src/app/api/screens.ts` | `next.screen` (`controller/action`) + `routeValues` to router URLs (`nextToUrlTree`, `follow`), flash messages, `errors` onto reactive forms (`applyServerErrors`: case-insensitive field match, `""` and unknown fields returned as form-level messages) | +| Errors | `ApiClient` | Never throws for an HTTP error: 400/401/403/404 bodies are `ScreenResult`s and are returned as they are, other failures (503, network) become a synthetic one. Screens switch on `status` | +| Session | `src/app/session/` | `SessionService`, `sessionInterceptor`, `authGuard` | + +Session behaviour: the access token is only in memory; the refresh token is in `sessionStorage` (survives F5, dies with the tab, but is +readable by any script of the origin: an XSS can steal it, which an HttpOnly cookie would prevent. For a same-origin deployment BaGet also +offers the cookie mode, `POST /api/ui/session/cookie` + `X-XSRF-TOKEN`, not used here). The interceptor adds `Authorization: Bearer` to calls +to the API only, on a `401` refreshes once (single flight, shared by concurrent requests) and retries, and takes renewed pairs from +`X-Session-Access-Token`, `X-Session-Access-Expires`, `X-Session-Refresh-Token`, `X-Session-Refresh-Expires`. A refused refresh (30-day +cap, password changed, signed out everywhere) sends the person to `/sign-in`. External sign-in: the fragment of `sign-in/external` is erased with +`history.replaceState` before the 60-second `exchange_token` is posted to `/api/ui/session/exchange`. + +## Security notes + +- Return addresses (`returnUrl`) are followed only when they are paths of this app (`safeLocalUrl`). +- The token is sent to the configured API origin only. +- Password and codes are never stored; a content security policy (`script-src 'self'`) on the host is the best protection of `sessionStorage`. +- The server's `Cors:AllowedOrigins` is what lets another origin call the session endpoints; keep the list exact. + +## Known API friction + +- The OpenAPI document types enums (`ScreenStatus`, `SearchSort`) as integers while the JSON carries names; `api-types.ts` declares `ScreenStatus` by hand. +- The optional route value `{version?}` of `packages/{id}/{version?}` is documented as a path segment `{version}` plus a query parameter; `ApiClient` fills the segment from either and drops it when empty. +- Integer fields are typed `number | string`. diff --git a/samples/BaGet.Frontend.Angular/angular.json b/samples/BaGet.Frontend.Angular/angular.json new file mode 100644 index 000000000..e11ce782f --- /dev/null +++ b/samples/BaGet.Frontend.Angular/angular.json @@ -0,0 +1,77 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "cli": { + "packageManager": "npm" + }, + "newProjectRoot": "projects", + "projects": { + "baget-frontend-angular": { + "projectType": "application", + "schematics": {}, + "root": "", + "sourceRoot": "src", + "prefix": "app", + "architect": { + "build": { + "builder": "@angular/build:application", + "options": { + "browser": "src/main.ts", + "tsConfig": "tsconfig.app.json", + "assets": [ + { + "glob": "**/*", + "input": "public" + } + ], + "styles": [ + "src/styles.css" + ] + }, + "configurations": { + "production": { + "budgets": [ + { + "type": "initial", + "maximumWarning": "1MB", + "maximumError": "2MB" + }, + { + "type": "anyComponentStyle", + "maximumWarning": "8kB", + "maximumError": "16kB" + } + ], + "outputHashing": "all", + "baseHref": "/app/" + }, + "development": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true, + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.development.ts" + } + ] + } + }, + "defaultConfiguration": "production" + }, + "serve": { + "builder": "@angular/build:dev-server", + "configurations": { + "production": { + "buildTarget": "baget-frontend-angular:build:production" + }, + "development": { + "buildTarget": "baget-frontend-angular:build:development" + } + }, + "defaultConfiguration": "development" + } + } + } + } +} diff --git a/samples/BaGet.Frontend.Angular/dist/baget-frontend-angular/browser/favicon.ico b/samples/BaGet.Frontend.Angular/dist/baget-frontend-angular/browser/favicon.ico new file mode 100644 index 000000000..d23a8b45a Binary files /dev/null and b/samples/BaGet.Frontend.Angular/dist/baget-frontend-angular/browser/favicon.ico differ diff --git a/samples/BaGet.Frontend.Angular/openapi/ui.json b/samples/BaGet.Frontend.Angular/openapi/ui.json new file mode 100644 index 000000000..7132e5afb --- /dev/null +++ b/samples/BaGet.Frontend.Angular/openapi/ui.json @@ -0,0 +1,44455 @@ +{ + "openapi": "3.0.4", + "info": { + "title": "BaGet UI API", + "description": "The JSON twin of every screen of the web UI (/api/ui). Authenticate with an API key as 'Authorization: Bearer ' or the X-NuGet-ApiKey header, or, for a person, with a session token ('Authorization: Bearer bgs.xxx') from POST /api/ui/session (a single-page application on any origin). A same-origin client may use the browser cookie if it sends the antiforgery token of GET /api/ui/antiforgery in the X-XSRF-TOKEN header on every request; the bare cookie and HTTP Basic are not accepted. Administration screens need an administrator's key with the admin:api scope and no repository limit, or an administrator's interactive session (the global ApiKey is refused). Account self-service and package ownership screens need an interactive session; API keys are refused with 403.", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost:6193/" + } + ], + "paths": { + "/api/ui/account/login": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The sign-in form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Signs in. Success sets the session cookie and continues at `next.localUrl` (the local return URL, else the site root), or at the second-factor screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LoginForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LoginForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LoginForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/loginwith2fa": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The authenticator code form (back to sign-in without the half-signed-in cookie).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "rememberMe", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Completes the sign-in with an authenticator code.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorLoginForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorLoginForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorLoginForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/loginwithrecoverycode": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The recovery code form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Completes the sign-in with a recovery code (each works once).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RecoveryCodeLoginForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RecoveryCodeLoginForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RecoveryCodeLoginForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/logout": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The sign-out screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Signs the user out.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/account/register": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The registration form (404 while `Accounts:AllowRegistration` is off).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Creates an account (and signs it in when no confirmation or approval is pending).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RegisterForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RegisterForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RegisterForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/confirmemail": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The target of the links in confirmation emails (a GET that confirms the address, like the page).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "userId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "code", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "email", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/forgotpassword": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The \"forgot password\" form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Asks for a reset link. The answer is the same whether or not an account matches.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/resetpassword": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The new-password form behind the link of a reset email.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "userId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "code", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Sets the new password from the link; success continues at the sign-in screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResetPasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResetPasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResetPasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/reauthenticate": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The \"confirm it is you\" screen (the button that starts the provider's sign-in is browser-only).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations": { + "get": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "The organizations of the user.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations/create": { + "post": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "Create an organization.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/CreateOrganizationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/CreateOrganizationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/CreateOrganizationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations/add-member": { + "post": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "Add a member (organization administrators only; 403 otherwise).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AddOrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AddOrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AddOrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations/remove-member": { + "post": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "Remove a member (an administrator removes anyone; any member may leave; 403 otherwise).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveOrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveOrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveOrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/packages": { + "get": { + "tags": [ + "AccountPackagesApi" + ], + "summary": "The package IDs the user owns, per repository.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/access": { + "get": { + "tags": [ + "AccountPackagesApi" + ], + "summary": "What the user may do in each repository (optionally for one package ID).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "package", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/profile": { + "get": { + "tags": [ + "AccountPackagesApi" + ], + "summary": "The user's own profile: continues at `next.localUrl` (`~/profiles/{name}`).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/account/settings": { + "get": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Account settings.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/change-password": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Change the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangePasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangePasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangePasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/change-email": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Change the email address (asks the password again).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangeEmailForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangeEmailForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangeEmailForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/unlink-external": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Unlinks the account's login at an external provider (asks the password again; refused when it is the only way to sign in). Linking is browser-only: it redirects to the provider.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UnlinkExternalForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UnlinkExternalForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UnlinkExternalForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/delete": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Delete the account (asks the password again). Success signs the user out.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor": { + "get": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Two-factor authentication (the setup key and QR code while it is off).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor/enable": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Turn two-factor authentication on with a code from the authenticator; the answer carries the recovery codes, once.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorCodeForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorCodeForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorCodeForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor/disable": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Turn two-factor authentication off (asks the password again).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor/reset": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Reset the authenticator (asks the password again).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/apikeys": { + "get": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "The user's API keys (never their values) and the new-key form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/apikeys/create": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Creates a key. The answer carries its value (`createdKey`) once.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ApiKeyForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ApiKeyForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ApiKeyForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/apikeys/revoke/{key}": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Revokes a key.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/audit": { + "get": { + "tags": [ + "AdminAuditApi" + ], + "summary": "Lists the entries that match the filter.", + "parameters": [ + { + "name": "actor", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "subject", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "from", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "to", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups": { + "get": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Lists the groups.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Creates a group and points at it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupCreation" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupCreation" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupCreation" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}": { + "get": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Shows one group, with the member search for q.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/rename": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Renames the group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupRename" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupRename" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupRename" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/add-member": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Adds a user to the group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/remove-member": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Removes a user from the group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/delete": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Deletes the group with the grants and project roles that name it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/operations": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Lists the operations and their status.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Starts an operation on a repository.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OperationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OperationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OperationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Lists the pending and quarantined submissions.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation/retry": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Validates the submission again.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation/release": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Indexes the quarantined package although validation failed.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation/reject": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Deletes the quarantined package.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/abuse": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Lists the abuse reports (the unresolved ones unless all).", + "parameters": [ + { + "name": "all", + "in": "query", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/abuse/resolve": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Marks a report resolved.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/abuse/reopen": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Reopens a resolved report.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/cluster": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "The cluster status; `?refresh=true` runs the health checks again.", + "parameters": [ + { + "name": "refresh", + "in": "query", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/formats": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "The package formats this server can host.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/access-unavailable": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Why the access screens are not available: the configured database has no access model.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations": { + "get": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Lists the organizations.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}": { + "get": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Shows one organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/rename": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Renames the organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationRenameForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationRenameForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationRenameForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/delete": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Deletes the organization (refused while it owns packages).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/add-member": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Adds a user to the organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/set-admin": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Makes a member an administrator of the organization, or not.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/remove-member": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Removes a member from the organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/packages": { + "get": { + "tags": [ + "AdminPackagesApi" + ], + "summary": "Lists the ownerless IDs of every repository, pageNumber being one-based.", + "parameters": [ + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/admin/packages": { + "get": { + "tags": [ + "AdminPackagesApi" + ], + "summary": "Lists the ownerless IDs of every repository, pageNumber being one-based.", + "parameters": [ + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions": { + "get": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Lists the permission targets.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Creates a target and points at it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/preview": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Previews the form patterns without saving anything.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/restore-built-ins": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Re-creates the built-in groups and targets that are missing (the upgrade defaults).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}": { + "get": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Shows one target. principalType and principalName pre-fill the grant form.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "testPackage", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "principalType", + "in": "query", + "schema": { + "$ref": "#/components/schemas/PrincipalType" + } + }, + { + "name": "principalName", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/preview": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Previews the form patterns (and the test package) without saving anything.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/save": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Replaces the target's patterns.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/set-grant": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Gives a principal the ticked actions through the target, replacing an earlier grant to it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GrantForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GrantForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GrantForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/remove-grant": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Removes a principal's grant.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/delete": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Deletes the target and its grants.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects": { + "get": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Lists the projects the caller may open.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Creates a project (server administrators only) and points at it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectCreation" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectCreation" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectCreation" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}": { + "get": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Shows one project.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/set-member": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Gives a user or group a role in the project, replacing an earlier one.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/remove-member": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Takes a user or group out of the project.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/assign-repository": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Puts a repository in the project (server administrators only); it leaves any project it was in.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/unassign-repository": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Takes a repository out of the project (server administrators only).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/create-target": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Creates a permission target that applies only to the project's repositories.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/preview": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Previews the new target's patterns without saving anything.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/delete": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Deletes the project (server administrators only) with its members and targets; the repositories stay.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories": { + "get": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Lists the repositories (narrowed by format, kind, q) and describes the create forms.", + "parameters": [ + { + "name": "format", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "kind", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a local NuGet repository (`name`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/create/format": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a local repository of a format other than NuGet (`name`, `format`, `fields`, `anonymousRead`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/create/virtual": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a virtual repository with no members (`name`, `format`, `anonymousRead`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/create/remote": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a remote repository (`name`, `format`, `remote`, `anonymousRead`, `password`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}": { + "get": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Shows one repository.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Saves the repository (`anonymousRead`; a remote one also `remote` and `password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/maven-settings": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Saves the policy of a local Maven repository (`policy`, `redeploy`, `snapshotBuilds`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/test": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Asks a remote repository's upstream with the unsaved `remote` values and saves nothing (`password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/purge": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Deletes everything a remote repository cached (`password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/purge-package": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Deletes one cached package of a remote repository (`packageId`, `packageVersion`, `password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/add-member": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Adds a member at the end of a virtual repository (`member`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/remove-member": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Removes a member of a virtual repository (`member`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/move-member": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Moves a member of a virtual repository up or down (`member`, `direction`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/deploy": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Sets the member of a virtual repository that receives uploads (`deploy`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/preview": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Shows where a package version would come from in a virtual repository (`previewPackageId`, `previewVersion`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/delete": { + "get": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Shows what deleting the repository does.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Deletes the repository (refused while it holds packages or is a member of a virtual repository).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings": { + "get": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Shows the settings; section is the id of the section to show.", + "parameters": [ + { + "name": "section", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Saves the settings of one section: the body names the section, the password and the fields (`v:<key>` values, `reset:<key>`,\r\n`clear:<key>`, `copyData`), each an array of strings.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/copy-status": { + "get": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "The progress of the database copy.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/save-provider": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Adds or changes a named OpenID Connect provider (password in the body; takes effect after a restart; a blank secret keeps the saved one).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SignInProviderForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SignInProviderForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SignInProviderForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/remove-provider": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Removes a named OpenID Connect provider saved on this screen (takes effect after a restart).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveSignInProviderForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveSignInProviderForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveSignInProviderForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/set-log-level": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Sets the lowest level logged for one source.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/remove-log-level": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Removes a per-source level saved on this screen.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/test-telemetry": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Sends one test span to the posted, unsaved telemetry endpoint (`v:Telemetry:Otlp:*` fields) and answers the outcome; nothing is saved.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Lists the users, filtered by q (user name contains), one page of them.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/approve": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Enables a self-registered account that waits for approval.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/promote": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Makes a user an administrator.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/demote": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Removes a user's administrator flag.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/reset-password": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Replaces a user's password with a generated one, which the answer carries once (`generatedPassword`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/send-reset-link": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Mails a user a password reset link.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/create": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Creates an account (typed, generated or invited password). A generated password is in the answer once.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserCreation" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserCreation" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserCreation" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Shows one account. package is a package ID to evaluate the effective permissions for.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "package", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/approve": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Enables the account when it waits for approval.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/revoke-key": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Revokes one of the account's API keys.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserKeyForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserKeyForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserKeyForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/add-group": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Adds the account to a group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/remove-group": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Removes the account from a group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/delete": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Shows what deleting the account does.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Deletes the account after the administrator's password.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserDeletionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserDeletionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserDeletionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/packages": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Lists the package IDs one user owns.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/admin/users/{name}/packages": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Lists the package IDs one user owns.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/contact-owners": { + "get": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "The form's state; 404 when the package has no owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "Sends the message to the owners (400 with the field errors when the message is missing or too long).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/contact-owners": { + "get": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "The form's state; 404 when the package has no owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "Sends the message to the owners (400 with the field errors when the message is missing or too long).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/{image}": { + "get": { + "tags": [ + "DockerManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/{image}": { + "get": { + "tags": [ + "DockerManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/delete-tag/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a tag, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/delete-tag/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a tag, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/delete-manifest/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a manifest with its tags, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/delete-manifest/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a manifest with its tags, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/prune/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Removes the layers no manifest uses, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/prune/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Removes the layers no manifest uses, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/delete-image/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes the whole image, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/delete-image/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes the whole image, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}": { + "get": { + "tags": [ + "MavenManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}": { + "get": { + "tags": [ + "MavenManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/add-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/add-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/remove-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/remove-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/delete-file": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one file of the chosen version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-file": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one file of the chosen version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/delete-version": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-version": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/delete-artifact": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes the whole artifact, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-artifact": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes the whole artifact, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/cleanup": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes old snapshot builds of a version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/cleanup": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes old snapshot builds of a version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/{id}": { + "get": { + "tags": [ + "NpmManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/{id}": { + "get": { + "tags": [ + "NpmManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/add-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/add-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/remove-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/remove-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/set-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Points a dist-tag at a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/set-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Points a dist-tag at a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/remove-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a dist-tag.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/remove-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a dist-tag.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/deprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/deprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/undeprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/undeprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/unpublish/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes one version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/unpublish/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes one version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/unpublish-all/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes every version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/unpublish-all/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes every version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage": { + "get": { + "tags": [ + "PackageManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage": { + "get": { + "tags": [ + "PackageManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/add-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/add-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/remove-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/remove-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/unlist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Unlists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/unlist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Unlists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/relist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Relists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/relist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Relists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes a version as the server is configured to (unlist or permanent).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes a version as the server is configured to (unlist or permanent).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/hard-delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes a version (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes a version (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/hard-delete-all": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes every version and the owners (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete-all": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes every version and the owners (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/deprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/deprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/undeprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/undeprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/add-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds a vulnerability to a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/add-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds a vulnerability to a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/remove-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a vulnerability from a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/remove-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a vulnerability from a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/set-verified": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Marks or unmarks the ID as verified (administrators).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/set-verified": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Marks or unmarks the ID as verified (administrators).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/delete-symbols": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes the PDBs recorded for a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/delete-symbols": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes the PDBs recorded for a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/resolve-report": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Resolves an abuse report.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/resolve-report": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Resolves an abuse report.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/profiles/{name}": { + "get": { + "tags": [ + "ProfileApi" + ], + "summary": "The profile named name; 404 when neither a user nor an organization has it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/profiles/{name}": { + "get": { + "tags": [ + "ProfileApi" + ], + "summary": "The profile named name; 404 when neither a user nor an organization has it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication": { + "get": { + "tags": [ + "ReplicationApi" + ], + "summary": "Lists the replications and the form that creates one.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Creates a replication and opens it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}": { + "get": { + "tags": [ + "ReplicationApi" + ], + "summary": "Shows one replication with its log.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/save": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Saves the settings.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/test": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Tests the connection with the typed settings; saves nothing.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/run": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Starts a run.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/resume": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Starts a run that continues the last interrupted or failed one.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/stop": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Asks the running replication to stop; it ends as interrupted and can be resumed.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/delete": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Deletes the configuration with its log.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention": { + "get": { + "tags": [ + "RetentionApi" + ], + "summary": "Lists the policies and the form that creates one.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Creates a policy and opens it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}": { + "get": { + "tags": [ + "RetentionApi" + ], + "summary": "Shows one policy, its last run and report.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/save": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Saves the rules.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/dry-run": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Starts a dry run: the report of what a run would delete.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/run": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Starts a run that deletes.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/delete": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Deletes the policy (what it deleted stays deleted).", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/holds": { + "get": { + "tags": [ + "RetentionApi" + ], + "summary": "Lists the legal holds (of `?repository=` only, when given).", + "parameters": [ + { + "name": "repository", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/holds/add": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Places a hold.", + "parameters": [ + { + "name": "repository", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/holds/remove": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Lifts a hold.", + "parameters": [ + { + "name": "repository", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldRemoval" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldRemoval" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldRemoval" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + } + } + } + }, + "/api/ui/scan-artifact": { + "get": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Shows the form (and the stored result) of the version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "name", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Scans the version now (or queues it, for an image) and shows the outcome.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/scan-artifact": { + "get": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Shows the form (and the stored result) of the version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "name", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Scans the version now (or queues it, for an image) and shows the outcome.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning": { + "get": { + "tags": [ + "ScanningApi" + ], + "summary": "The overview of every repository and project.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/{name}": { + "get": { + "tags": [ + "ScanningApi" + ], + "summary": "The dashboard of a repository: `?min=` is the lowest severity listed (0 to 3), `?p=` the page.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "min", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/{name}/policy": { + "post": { + "tags": [ + "ScanningApi" + ], + "summary": "Saves the repository policy; empty values remove it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/{name}/scan": { + "post": { + "tags": [ + "ScanningApi" + ], + "summary": "Starts a scan of every artifact of the repository in the background.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/projects/{name}": { + "get": { + "tags": [ + "ScanningApi" + ], + "summary": "The scanning policy of a project.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/projects/{name}/policy": { + "post": { + "tags": [ + "ScanningApi" + ], + "summary": "Saves the project policy; empty values remove it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + } + } + } + }, + "/api/ui/session": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Signs in with the user name and password. Answers the tokens, or `twoFactorRequired` with a short-lived `twoFactorTicket` for\r\n`/session/two-factor` or `/session/recovery-code`. 401 for wrong credentials, 403 for a locked, unapproved or unconfirmed account.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignInForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignInForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignInForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/two-factor": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Completes a sign-in with a code of the authenticator app.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionTwoFactorForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionTwoFactorForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionTwoFactorForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/recovery-code": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Completes a sign-in with a recovery code (each works once).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRecoveryCodeForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRecoveryCodeForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRecoveryCodeForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/refresh": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Exchanges the refresh token for a new pair of tokens (the authentication time is kept; the session ends `Accounts:SessionMaxLifetime` after the sign-in).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRefreshForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRefreshForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRefreshForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/exchange": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Exchanges the 60-second `exchange_token` of an external sign-in's redirect for the tokens (or the two-factor ticket).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionExchangeForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionExchangeForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionExchangeForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/sign-out": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Ends the session: the client forgets its tokens. With `everywhere` the account's security stamp changes and every token and cookie\r\nsession of the account stops working. The caller is the access token, or the refresh token in the body.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignOutForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignOutForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignOutForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/session/cookie": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Signs in with the cookie (same origin only; needs the antiforgery token of `GET /api/ui/antiforgery` fetched while signed out, so a cross-site page cannot\r\nsign a visitor in): the rules of `POST /session`, the second factor in the same endpoint (`ticket` with `code` or `recoveryCode`), but the answer holds no tokens.\r\nFetch the antiforgery token again afterwards: it is bound to the signed-in user.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionCookieForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionCookieForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionCookieForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/cookie/sign-out": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Signs the cookie session out (same origin; send the cookie with the antiforgery header). 401 for anything but a cookie session.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/session/providers": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "The external sign-in providers a client can offer before anyone is signed in (the sign-in screen's model is interactive-only): their ids, to put in\r\n`/session/external/{id}`, and the names for the buttons. An empty list when none is configured.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + } + } + } + }, + "/api/ui/antiforgery": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "The antiforgery request token for a same-origin client that uses the cookie session: send it in the `X-XSRF-TOKEN` header (every method). It\r\nis bound to the signed-in user, so fetch it again after signing in or out. Also sets the antiforgery cookie.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + } + } + } + }, + "/api/ui/account/resend-confirmation": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Mails a new confirmation link to an account whose address is not confirmed. The answer is the same whether or not an account matches or the mail was allowed\r\n(one per account per ten minutes, and per client); 404 without outgoing mail.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + } + } + } + }, + "/api/ui/session/external/{provider}": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "Starts the sign-in with the external provider (a browser navigation, not a fetch). The result comes back in the URL fragment of\r\nreturnUrl, which must lie under `Frontend:SpaBasePath` of this server, or be an address of an origin listed in `Cors:AllowedOrigins`.", + "parameters": [ + { + "name": "provider", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { } + } + } + } + } + }, + "/api/ui/session/external-callback": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "The provider's answer: redirects to returnUrl with, in the URL fragment, `exchange_token` (+ `exchange_expires_at`, `user_name`), to exchange within\r\na minute at `POST /api/ui/session/exchange`, or `notice` (account created, not usable yet) or `error`. No token of the session itself is ever put in a URL.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { } + } + } + } + } + }, + "/api/ui/packages/{id}/validation": { + "get": { + "tags": [ + "ValidationStatusApi" + ], + "summary": "The submissions of the ID.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/validation": { + "get": { + "tags": [ + "ValidationStatusApi" + ], + "summary": "The submissions of the ID.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/api": { + "get": { + "tags": [ + "ApiCatalogApi" + ], + "summary": "The operations of the REST API.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-images": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "The image list with a search box and the client commands.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-images": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "The image list with a search box and the client commands.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-images/{image}": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "One image: tags, manifests, and with `digest` one manifest in full.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "digest", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactType", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-images/{image}": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "One image: tags, manifests, and with `digest` one manifest in full.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "digest", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactType", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + } + } + } + }, + "/api/ui/home": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "The front page of the repository, or the results when the query asks for something.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/home": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "The front page of the repository, or the results when the query asks for something.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/packages": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "One page of the package list.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "One page of the package list.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/privacy": { + "get": { + "tags": [ + "LegalApi" + ], + "summary": "The Privacy Policy.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + } + } + } + }, + "/api/ui/terms": { + "get": { + "tags": [ + "LegalApi" + ], + "summary": "The Terms of Use.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + } + } + } + }, + "/api/ui/maven-artifacts": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The artifact list with a search box and the client configuration.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-artifacts": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The artifact list with a search box and the client configuration.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-artifacts/{group}/{artifact}/{version}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}/{version}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-upload": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The upload form's state.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "Deploys the chosen files under the given coordinates.", + "parameters": [ + { + "name": "groupId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "packaging", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "classifier", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "allOf": [ + { + "type": "object", + "properties": { + "file": { + "$ref": "#/components/schemas/IFormFile" + } + } + }, + { + "type": "object", + "properties": { + "pom": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + ] + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-upload": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The upload form's state.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "Deploys the chosen files under the given coordinates.", + "parameters": [ + { + "name": "groupId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "packaging", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "classifier", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "allOf": [ + { + "type": "object", + "properties": { + "file": { + "$ref": "#/components/schemas/IFormFile" + } + } + }, + { + "type": "object", + "properties": { + "pom": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + ] + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-packages": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The package list with a search box.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-packages": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The package list with a search box.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-packages/{id}": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "One package: readme, versions, dist-tags, install commands.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-packages/{id}": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "One package: readme, versions, dist-tags, install commands.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-upload": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The upload form's state.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "Publishes the chosen tarball with the dist-tag tag (default `latest`).", + "parameters": [ + { + "name": "tag", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-upload": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The upload form's state.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "Publishes the chosen tarball with the dist-tag tag (default `latest`).", + "parameters": [ + { + "name": "tag", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/{version}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/{version}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/{version}/report-abuse": { + "get": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "The empty form.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + }, + "post": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "Records the report.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/{version}/report-abuse": { + "get": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "The empty form.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + }, + "post": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "Records the report.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + } + }, + "/api/ui/stats": { + "get": { + "tags": [ + "StatisticsApi" + ], + "summary": "The feed's statistics.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/stats": { + "get": { + "tags": [ + "StatisticsApi" + ], + "summary": "The feed's statistics.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload": { + "get": { + "tags": [ + "UploadApi" + ], + "summary": "Step one: the form.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload": { + "get": { + "tags": [ + "UploadApi" + ], + "summary": "Step one: the form.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload/stage": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Stages the chosen file and describes what it contains.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload/stage": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Stages the chosen file and describes what it contains.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload/submit": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Publishes the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload/submit": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Publishes the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload/cancel": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Discards the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload/cancel": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Discards the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-artifacts/{group}/{artifact}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "AbuseForm": { + "required": [ + "key", + "all" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The report's number.", + "format": "int32" + }, + "all": { + "type": "boolean", + "description": "Whether the list to come back to shows the resolved reports too." + } + }, + "description": "A decision on an abuse report." + }, + "AbuseReportSummary": { + "required": [ + "key", + "repository", + "packageId", + "packageVersion", + "reason", + "details", + "reporterEmail", + "created", + "resolved" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repository": { + "type": "string" + }, + "packageId": { + "type": "string", + "nullable": true + }, + "packageVersion": { + "type": "string", + "nullable": true + }, + "reason": { + "type": "string", + "nullable": true + }, + "details": { + "type": "string", + "nullable": true + }, + "reporterEmail": { + "type": "string", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "resolved": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "isResolved": { + "type": "boolean" + } + }, + "description": "An abuse report with the name of its repository." + }, + "AbuseViewModel": { + "type": "object", + "properties": { + "all": { + "type": "boolean", + "description": "Show the resolved reports too." + }, + "isSupported": { + "type": "boolean", + "description": "Whether reports are stored with the configured database." + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AbuseReportSummary" + }, + "description": "The reports, newest first." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + } + }, + "description": "What the abuse reports screen (`/admin/abuse`) shows: the reports of every repository." + }, + "AccessAction": { + "enum": [ + "None", + "Read", + "Annotate", + "Deploy", + "Delete", + "Manage", + "All" + ], + "type": "string", + "description": "What a permission grants. Independent flags: AccessAction.Deploy does not imply AccessAction.Read, as in\r\nArtifactory. Package ownership (IPackageAuthorizationService) is a second, separate requirement\r\nfor the actions that change an existing package ID." + }, + "AccessAuditEntry": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "created": { + "type": "string", + "format": "date-time" + }, + "actor": { + "type": "string", + "description": "The user name that made the change; null for the server itself.", + "nullable": true + }, + "action": { + "type": "string", + "description": "What happened, such as `group.create` or `grant.set`.", + "nullable": true + }, + "subject": { + "type": "string", + "description": "What it happened to (a group, target or repository name).", + "nullable": true + }, + "details": { + "type": "string", + "description": "JSON with the details (never credentials).", + "nullable": true + } + }, + "description": "One change to the access model." + }, + "AccessExplanation": { + "required": [ + "actions", + "override", + "reasons" + ], + "type": "object", + "properties": { + "actions": { + "$ref": "#/components/schemas/AccessAction" + }, + "override": { + "type": "string", + "description": "A rule that grants everything or bypasses the model (administrator, global API key, no\r\n access model), instead of Reasons; null when the grants decide.", + "nullable": true + }, + "reasons": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccessReason" + }, + "description": "The grants and project roles that apply to the caller." + } + }, + "description": "What a caller may do in a repository, and why (Task<AccessExplanation> IAccessEvaluator.ExplainAsync(BaGetPrincipal? principal, RepositoryInfo repository, string? packageId, CancellationToken cancellationToken))." + }, + "AccessReason": { + "required": [ + "source", + "principalType", + "principalId", + "principal", + "granted", + "effective", + "packages", + "note" + ], + "type": "object", + "properties": { + "source": { + "type": "string", + "description": "Where it comes from, such as `Permission target 'Anyone reads every repository'`." + }, + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string", + "description": "The principal's id (user id, group or organization key)." + }, + "principal": { + "type": "string", + "description": "The principal in words (a user name, `group Developers`, `organization Contoso`)." + }, + "granted": { + "$ref": "#/components/schemas/AccessAction" + }, + "effective": { + "$ref": "#/components/schemas/AccessAction" + }, + "packages": { + "type": "string", + "description": "The package filter of the target, such as `Contoso.* except Contoso.Internal.*`; null for all.", + "nullable": true + }, + "note": { + "type": "string", + "description": "Why AccessAction AccessReason.Effective differs from AccessAction AccessReason.Granted, if it does.", + "nullable": true + } + }, + "description": "One grant or project role behind an access decision, for the admin pages that explain it." + }, + "AccessUnavailableViewModel": { + "required": [ + "reason" + ], + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "Why the access screens are not available." + } + }, + "description": "What the \"access control unavailable\" screen (`/admin/access-unavailable`) says: why, as the JSON carries it (the page has fixed text)." + }, + "AccountAccessViewModel": { + "type": "object", + "properties": { + "package": { + "type": "string", + "description": "A package ID to evaluate the grants for; empty means the repository as a whole.", + "nullable": true + }, + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryAccessRow" + }, + "description": "The repositories where the user holds some action." + }, + "administeredProjects": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The projects the user administers." + }, + "modelAvailable": { + "type": "boolean", + "description": "Whether the configured database has an access model at all." + } + }, + "description": "The \"My access\" screen: the signed-in user's own effective permissions." + }, + "AccountApiKey": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The key's id (the number the revoke button posts).", + "format": "int32" + }, + "description": { + "type": "string", + "description": "What the key is for.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "What the key may do." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs the key applies to.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When it was created.", + "format": "date-time" + }, + "expires": { + "type": "string", + "description": "When it expires; null = never.", + "format": "date-time", + "nullable": true + } + }, + "description": "One API key as the screen lists it: never the key itself or its hash (only the creation response shows a new key, once)." + }, + "AccountOrganization": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization's name.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the current user administers it." + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccountOrganizationMember" + }, + "description": "The members, by user name.", + "nullable": true + } + }, + "description": "One organization with its members." + }, + "AccountOrganizationMember": { + "required": [ + "userName", + "isAdmin" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The member's user name." + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the member administers the organization." + } + }, + "description": "One member of an organization (a flat record, so the screen's JSON names its fields)." + }, + "AccountPackagesViewModel": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryPackages" + }, + "description": "The owned packages of each repository that has any, `default` first." + }, + "isEmpty": { + "type": "boolean", + "description": "Whether the user owns nothing in any repository." + }, + "showRepositoryNames": { + "type": "boolean", + "description": "Whether the list needs repository headings: more than the default repository holds packages of the user." + } + }, + "description": "The \"My packages\" screen: the packages the user owns in each repository." + }, + "AddOrganizationMemberForm": { + "type": "object", + "properties": { + "organization": { + "type": "string", + "description": "The organization.", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The user to add.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the new member administers the organization." + } + }, + "description": "What the \"add a member\" form posts." + }, + "AdminDeletionPreview": { + "required": [ + "apiKeys", + "directPackageIds", + "soleOwnedPackages", + "organizations" + ], + "type": "object", + "properties": { + "apiKeys": { + "type": "integer", + "description": "How many API keys go.", + "format": "int32" + }, + "directPackageIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Package IDs the user owns directly." + }, + "soleOwnedPackages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SoleOwnedPackage" + }, + "description": "The subset nobody else owns, in every repository." + }, + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrganizationOutcome" + }, + "description": "What happens to each organization the user belongs to." + } + }, + "description": "What deleting a user as an administrator would remove or change." + }, + "AdminJobState": { + "enum": [ + "Running", + "Succeeded", + "Failed" + ], + "type": "string" + }, + "AdminJobStatus": { + "type": "object", + "properties": { + "operation": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/AdminJobState" + }, + "actor": { + "type": "string", + "nullable": true + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "message": { + "type": "string", + "description": "The result on success, the exception type and message on failure.", + "nullable": true + } + }, + "description": "The last run of an operation on a repository. In memory: a restart forgets it." + }, + "AdminOrganizationsViewModel": { + "type": "object", + "properties": { + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrganizationSummary" + }, + "description": "The organizations, by name." + } + }, + "description": "What the organizations screen (`/admin/organizations`) lists: every organization with its members and packages." + }, + "AdminPackageRow": { + "required": [ + "package", + "owners" + ], + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/OwnedPackage" + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of its owners; empty for an ownerless ID." + }, + "repositoryName": { + "type": "string", + "description": "The repository the ID is in; ownership and versions are per repository.", + "default": "default" + } + }, + "description": "A package ID as the administrator pages list it." + }, + "AdminPackagesViewModel": { + "type": "object", + "properties": { + "pageNumber": { + "type": "integer", + "description": "One-based page number (the `p` query value).", + "format": "int32" + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminPackageRow" + }, + "description": "The ownerless IDs on this page." + }, + "showRepository": { + "type": "boolean", + "description": "Whether a Repository column is worth showing: some listed ID is outside the default repository." + }, + "pageCount": { + "type": "integer", + "description": "The number of pages.", + "format": "int32" + } + }, + "description": "What the ownerless packages screen (`/admin/packages`) shows: the package IDs nobody owns, in every repository." + }, + "AdminSettingsViewModel": { + "type": "object", + "properties": { + "sectionList": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SettingsSection" + }, + "description": "The same sections as IReadOnlyList<IGrouping<string, SettingState>> AdminSettingsViewModel.Sections, each with its key and DOM id, as the JSON carries them.", + "nullable": true + }, + "overridesPath": { + "type": "string", + "description": "The file the settings are saved to.", + "nullable": true + }, + "pendingRestart": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The keys changed since startup that only apply after a restart." + }, + "errors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the last save was refused." + }, + "errorSection": { + "type": "string", + "description": "The section the IReadOnlyList<string> AdminSettingsViewModel.Errors belong to.", + "nullable": true + }, + "logLevels": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LogLevelOverride" + }, + "description": "The per-source log levels (`Serilog:MinimumLevel:Override`) shown under the Serilog section." + }, + "logLevelNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The level names offered for a source.", + "nullable": true + }, + "signInProviders": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SignInProviderView" + }, + "description": "The named OpenID Connect providers (`Accounts:OpenIdConnectProviders`) shown in the \"Sign-in providers\" panel of the Accounts section. No secret is carried." + }, + "loadError": { + "type": "string", + "description": "Why the overrides file could not be read, or null.", + "nullable": true + }, + "telemetrySignals": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TelemetrySignalReport" + }, + "description": "The state of each telemetry signal for the Telemetry section, or null when the host exports no telemetry.", + "nullable": true + }, + "hostExportsTelemetry": { + "type": "boolean", + "description": "True when this host exports telemetry (registers ITelemetryDiagnostics). When false the Telemetry\r\nsection stays editable (the settings file may be shared with a host that does export) but a note says it has no effect here." + }, + "telemetryTest": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TelemetryTestOutcome" + } + ] + }, + "canCopyDatabase": { + "type": "boolean", + "description": "Whether the running database is relational, so a change of database can copy the data (the \"Copy all data\" option of the\r\nDatabase section)." + }, + "copyTargetTypes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The `Database:Type` values a copy can target; the option is hidden for any other type." + }, + "copyStatus": { + "$ref": "#/components/schemas/DatabaseCopyStatus" + }, + "selectedId": { + "type": "string", + "description": "The DOM id (slug) of the section shown; every other section is rendered `hidden`. Chosen by the workflow: the failed\r\nsection, else the Telemetry section after \"Test connection\", else the `?section=` value, else the first section. The URL\r\nfragment is only known to the browser, so the page's script applies it on load unless bool AdminSettingsViewModel.SelectionLocked." + }, + "selectionLocked": { + "type": "boolean", + "description": "True when the server picked the section for a reason the URL fragment must not override (a failed save, a connection test)." + }, + "message": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the server settings screen (`/admin/settings`) shows: every registered setting by section and the state of the last save." + }, + "AntiforgeryTokenModel": { + "type": "object", + "properties": { + "headerName": { + "type": "string", + "description": "The header to send the token in (`X-XSRF-TOKEN`).", + "nullable": true + }, + "requestToken": { + "type": "string", + "description": "The request token. It is bound to the signed-in user: ask again after signing in or out.", + "nullable": true + } + }, + "description": "What `GET /api/ui/antiforgery` answers: the request token to send with a cookie session." + }, + "ApiCatalogViewModel": { + "required": [ + "endpoints", + "apiBase", + "confirmHeader" + ], + "type": "object", + "properties": { + "endpoints": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ApiEndpointSummary" + }, + "description": "Every operation, ordered by path." + }, + "apiBase": { + "type": "string", + "description": "The address of the API on this server." + }, + "confirmHeader": { + "type": "string", + "description": "The header that carries the password of the owner." + }, + "openApiUrl": { + "type": "string", + "description": "Where the OpenAPI document is.", + "nullable": true + } + }, + "description": "What the REST API page shows (also the model of its JSON twin)." + }, + "ApiEndpointSummary": { + "required": [ + "method", + "path", + "summary", + "uiScreen", + "confirm" + ], + "type": "object", + "properties": { + "method": { + "type": "string", + "description": "The HTTP method." + }, + "path": { + "type": "string", + "description": "The path template (`/api/v1/groups/{name}`)." + }, + "summary": { + "type": "string", + "description": "What the operation does." + }, + "uiScreen": { + "$ref": "#/components/schemas/ScreenRef" + }, + "confirm": { + "type": "boolean", + "description": "Whether the owner's password is asked (the confirmation header)." + } + }, + "description": "One operation of the REST API as the page (and the JSON twin) lists it: flat, with no reflection objects." + }, + "ApiKeyForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it.", + "nullable": true + }, + "description": { + "maxLength": 256, + "minLength": 0, + "type": "string", + "description": "What the key is for.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The scopes of the new key." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs the key applies to." + }, + "expiresInDays": { + "maximum": 3650, + "minimum": 1, + "type": "integer", + "description": "Days until the key expires; none = never.", + "format": "int32", + "nullable": true + }, + "repositoryKeys": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "description": "The keys of the repositories the new key is limited to; none (the default) means every repository." + } + }, + "description": "What the new-key form posts (and the body of `POST /api/ui/account/apikeys`)." + }, + "ApiKeysViewModel": { + "type": "object", + "properties": { + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories offered in the picker: those the user can read. Empty (picker hidden) where the server holds\r\nthe default repository only." + }, + "keys": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccountApiKey" + }, + "description": "The user's keys." + }, + "keyRepositories": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "The names of the repositories each key (by key id) is limited to." + }, + "createdKey": { + "type": "string", + "description": "The key just created. Shown once: only its hash is kept.", + "nullable": true + }, + "allScopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The scopes the new-key form offers: the package scopes, plus string ApiKeyScopes.Admin (the REST API under\r\n`/api/v1`) for an administrator." + }, + "password": { + "type": "string", + "description": "The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it.", + "nullable": true + }, + "description": { + "maxLength": 256, + "minLength": 0, + "type": "string", + "description": "What the key is for.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The scopes of the new key." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs the key applies to." + }, + "expiresInDays": { + "maximum": 3650, + "minimum": 1, + "type": "integer", + "description": "Days until the key expires; none = never.", + "format": "int32", + "nullable": true + }, + "repositoryKeys": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "description": "The keys of the repositories the new key is limited to; none (the default) means every repository." + } + }, + "description": "The API keys screen: the new-key form's fields it repeats and the user's keys. A request binds ApiKeyForm, never this type,\r\nso the outputs cannot be set from outside." + }, + "AuditViewModel": { + "type": "object", + "properties": { + "actorFilter": { + "type": "string", + "description": "The user name that made the change.", + "nullable": true + }, + "subject": { + "type": "string", + "description": "Part of what the change was done to (a group, target, project or repository name).", + "nullable": true + }, + "from": { + "type": "string", + "description": "First day, `yyyy-MM-dd`.", + "nullable": true + }, + "to": { + "type": "string", + "description": "Last day, `yyyy-MM-dd`.", + "nullable": true + }, + "entries": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccessAuditEntry" + }, + "description": "The matching entries." + }, + "filterError": { + "type": "string", + "description": "Why the filter was not applied, if a date could not be read.", + "nullable": true + } + }, + "description": "What the access audit screen (`/admin/audit`) shows: the filter and the matching entries." + }, + "ChangeEmailForm": { + "type": "object", + "properties": { + "newEmail": { + "type": "string", + "description": "The new address.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password, asked again (an account without one needs a fresh provider sign-in instead).", + "nullable": true + } + }, + "description": "What the change-email form posts." + }, + "ChangePasswordForm": { + "type": "object", + "properties": { + "currentPassword": { + "type": "string", + "description": "The current password (an account without one sets its first after signing in again with its provider).", + "nullable": true + }, + "newPassword": { + "type": "string", + "description": "The new password.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The new password again.", + "nullable": true + } + }, + "description": "What the change-password form posts (the body of `POST /api/ui/account/settings/change-password`)." + }, + "ClusterStatus": { + "required": [ + "enabled", + "thisNode", + "backend", + "backendReachable", + "nodes", + "leases", + "gateReason", + "readiness" + ], + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether this node is in a cluster." + }, + "thisNode": { + "type": "string", + "description": "This node's name." + }, + "backend": { + "type": "string", + "description": "The store, without credentials.", + "nullable": true + }, + "backendReachable": { + "type": "boolean", + "description": "Whether the store answered." + }, + "nodes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NodeInfo" + }, + "description": "The nodes with a recent heartbeat, this one included." + }, + "leases": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LeaseInfo" + }, + "description": "The job leases held now." + }, + "gateReason": { + "type": "string", + "description": "Why the cluster is read-only, or null.", + "nullable": true + }, + "readiness": { + "$ref": "#/components/schemas/ReadinessReport" + } + }, + "description": "What the cluster page shows." + }, + "ClusterViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ClusterStatus" + } + }, + "description": "What the cluster screen (`/admin/cluster`) shows: nodes, leases, shared state and health." + }, + "ConfirmEmailViewModel": { + "type": "object", + "properties": { + "succeeded": { + "type": "boolean", + "description": "Whether the link was valid." + }, + "emailChanged": { + "type": "boolean", + "description": "Whether the link changed the address of an existing account." + }, + "pendingApproval": { + "type": "boolean", + "description": "Whether the account still waits for an administrator (`Accounts:RequireApproval`) after the confirmation." + } + }, + "description": "The result of following the link of a confirmation email." + }, + "ContactOwnersForm": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "The message to send to the owners.", + "nullable": true + }, + "copyToSelf": { + "type": "boolean", + "description": "Whether the sender also gets a copy." + } + }, + "description": "The fields of the contact-owners form as the screen receives them (a page's form post or the JSON body of the twin). It carries no\r\nvalidation attributes: the use case validates by itself (ContactOwnersViewModel holds the rules), so a page's model\r\nbinding does not report the same error a second time." + }, + "ContactOwnersViewModel": { + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "maxLength": 4000, + "minLength": 0, + "type": "string", + "description": "The message to send to the owners.", + "nullable": true + }, + "copyToSelf": { + "type": "boolean", + "description": "Whether the sender also gets a copy." + }, + "packageId": { + "type": "string", + "description": "The package ID as stored, which is the only text that reaches the subject.", + "nullable": true + }, + "sent": { + "type": "boolean", + "description": "Whether the message was sent." + }, + "error": { + "type": "string", + "description": "Why the message was not sent, or null.", + "nullable": true + }, + "senderHasEmail": { + "type": "boolean", + "description": "Replies come to the sender's address, so there must be one, and it must be confirmed: an unconfirmed address could be anyone's." + } + }, + "description": "The contact-owners screen (`/packages/{id}/contact-owners`): the two form fields (string? ContactOwnersViewModel.Message,\r\nbool ContactOwnersViewModel.CopyToSelf, bound on POST) and what the screen shows; filled by the screen's workflow." + }, + "CreateOrganizationForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization's name.", + "nullable": true + } + }, + "description": "What the \"create an organization\" form posts." + }, + "DatabaseCopyPhase": { + "enum": [ + "Idle", + "Queued", + "Checking", + "Migrating", + "Copying", + "Verifying", + "SavingSettings", + "RollingBack", + "Succeeded", + "Failed" + ], + "type": "string", + "description": "The stage a database copy is in." + }, + "DatabaseCopyStatus": { + "required": [ + "phase", + "table", + "tableRowsCopied", + "tableRowsTotal", + "tablesDone", + "tablesTotal", + "rowsCopied", + "rowsTotal", + "errors", + "message" + ], + "type": "object", + "properties": { + "phase": { + "$ref": "#/components/schemas/DatabaseCopyPhase" + }, + "table": { + "type": "string", + "description": "The table being copied, or null.", + "nullable": true + }, + "tableRowsCopied": { + "type": "integer", + "description": "Rows of Table copied so far.", + "format": "int64" + }, + "tableRowsTotal": { + "type": "integer", + "description": "Rows of Table in the source.", + "format": "int64" + }, + "tablesDone": { + "type": "integer", + "description": "Tables completed.", + "format": "int32" + }, + "tablesTotal": { + "type": "integer", + "description": "Tables to copy.", + "format": "int32" + }, + "rowsCopied": { + "type": "integer", + "description": "Rows copied over all tables.", + "format": "int64" + }, + "rowsTotal": { + "type": "integer", + "description": "Rows to copy over all tables.", + "format": "int64" + }, + "errors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the copy was refused or failed." + }, + "message": { + "type": "string", + "description": "A one-line summary of the current state.", + "nullable": true + }, + "isActive": { + "type": "boolean", + "description": "A copy is queued or running." + }, + "isFinished": { + "type": "boolean", + "description": "The copy ended, either way." + }, + "restartRequired": { + "type": "boolean", + "description": "The copy succeeded: the settings are saved and the process must restart to use them." + } + }, + "description": "A snapshot of the copy's progress, as shown by the Settings page. Holds no connection string." + }, + "DatabaseCopyStatusView": { + "required": [ + "phase", + "active", + "finished", + "succeeded", + "restartRequired", + "table", + "tableRowsCopied", + "tableRowsTotal", + "tablesDone", + "tablesTotal", + "rowsCopied", + "rowsTotal", + "message", + "errors" + ], + "type": "object", + "properties": { + "phase": { + "type": "string", + "description": "The stage, by name." + }, + "active": { + "type": "boolean", + "description": "A copy is queued or running." + }, + "finished": { + "type": "boolean", + "description": "The copy ended, either way." + }, + "succeeded": { + "type": "boolean", + "description": "The copy succeeded." + }, + "restartRequired": { + "type": "boolean", + "description": "The settings are saved and the process must restart to use them." + }, + "table": { + "type": "string", + "description": "The table being copied, or null.", + "nullable": true + }, + "tableRowsCopied": { + "type": "integer", + "description": "Rows of the table copied so far.", + "format": "int64" + }, + "tableRowsTotal": { + "type": "integer", + "description": "Rows of the table in the source.", + "format": "int64" + }, + "tablesDone": { + "type": "integer", + "description": "Tables completed.", + "format": "int32" + }, + "tablesTotal": { + "type": "integer", + "description": "Tables to copy.", + "format": "int32" + }, + "rowsCopied": { + "type": "integer", + "description": "Rows copied over all tables.", + "format": "int64" + }, + "rowsTotal": { + "type": "integer", + "description": "Rows to copy over all tables.", + "format": "int64" + }, + "message": { + "type": "string", + "description": "A one-line summary of the current state.", + "nullable": true + }, + "errors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the copy was refused or failed." + } + }, + "description": "The progress of the database copy as the Settings page polls it (`?handler=CopyStatus`): the properties are those the page's script reads\r\n(`phase` as the phase name, `active`, `finished`, `succeeded`, `restartRequired` ...). Holds no connection string." + }, + "DeleteUserViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The user to delete (route).", + "nullable": true + }, + "soleOwned": { + "type": "string", + "description": "\"keep\" (default) or \"delete\": what to do with the IDs only this user owns." + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AdminDeletionPreview" + } + ] + }, + "lastAdministrator": { + "type": "boolean", + "description": "Whether the user is the server's only administrator." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Read-only mode: the account may go, but package files are not deleted." + }, + "error": { + "type": "string", + "description": "Why the deletion was refused.", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the delete-user screen (`/admin/users/{name}/delete`) shows: what the deletion would remove or change." + }, + "DeletionBlockers": { + "required": [ + "lastOwnerPackageIds", + "organizations" + ], + "type": "object", + "properties": { + "lastOwnerPackageIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Package IDs the user is the only direct owner of, in any repository (ownership is per repository, so the same\r\nID in two repositories counts once each). Same rule as\r\nTask<OwnerChangeResult> PackageOwnershipService.RemoveOwnerAsync(string? packageId, string ownerName, CancellationToken cancellationToken): an owned ID keeps an owner." + }, + "organizations": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Organizations the user is the last administrator of while others still belong to it, or\r\nthat own packages and so cannot be left without anyone to run them. Same rule as\r\nTask<bool> PackageOwnershipService.RemoveMemberAsync(string organizationName, string userId, CancellationToken cancellationToken)." + }, + "lastAdministrator": { + "type": "boolean", + "description": "The user is the server's only administrator, so deleting them would leave nobody able to\r\nchange the settings.", + "default": false + }, + "lastOwnerPackages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SoleOwnedPackage" + }, + "description": "Per-repository detail of IReadOnlyList<string?> DeletionBlockers.LastOwnerPackageIds; never null.", + "nullable": true + }, + "any": { + "type": "boolean", + "description": "Whether anything blocks the deletion." + } + }, + "description": "What stops a user from deleting their account." + }, + "DependencyGroupModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "nullable": true + }, + "dependencies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DependencyModel" + }, + "nullable": true + } + } + }, + "DependencyModel": { + "type": "object", + "properties": { + "packageId": { + "type": "string", + "nullable": true + }, + "versionSpec": { + "type": "string", + "nullable": true + } + } + }, + "DockerImagesViewModel": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The page, from 1.", + "format": "int32" + }, + "result": { + "$ref": "#/components/schemas/OciImagePage" + }, + "host": { + "type": "string", + "description": "The registry host as a Docker client writes it (`host:port`)." + }, + "isHttp": { + "type": "boolean", + "description": "Whether the registry is reached over plain http (the Docker daemon then needs it as an insecure registry)." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name, the first path segment of every image reference." + }, + "isRemote": { + "type": "boolean", + "description": "Whether the repository caches an upstream registry (it takes no pushes)." + }, + "isVirtual": { + "type": "boolean", + "description": "Whether the repository merges other repositories (a push goes to its deploy repository)." + }, + "hasNext": { + "type": "boolean", + "description": "Whether another page follows." + }, + "commandTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + } + }, + "description": "What the Docker front page (`/docker-images`) shows: this page of images and the commands for the client." + }, + "DockerImageViewModel": { + "type": "object", + "properties": { + "image": { + "type": "string", + "description": "The image name from the address (it may contain slashes).", + "nullable": true + }, + "digest": { + "type": "string", + "description": "The manifest to show in full (`?digest=`), or null for the overview.", + "nullable": true + }, + "artifactType": { + "type": "string", + "description": "Narrows the referrers to one artifact type (`?artifactType=`); empty keeps them all.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with: 200, or 404 when the image or manifest does not exist (the page then explains).", + "format": "int32" + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciImageInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciManifestDetail" + } + ] + }, + "referrers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciDescriptor" + }, + "description": "The manifests whose `subject` is the chosen manifest (signatures, SBOMs). Empty without a selection." + }, + "host": { + "type": "string", + "description": "The registry host as a Docker client writes it." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name." + }, + "isRemote": { + "type": "boolean", + "description": "Whether the repository caches an upstream registry (it takes no pushes)." + }, + "canManage": { + "type": "boolean", + "description": "Whether the signed-in user holds Delete on the image, so the manage page is offered." + }, + "pullTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + }, + "registryUrl": { + "type": "string", + "description": "The address of the registry API for the image (what a script calls)." + } + }, + "description": "What the page of one Docker image (`/docker-images/{image}`, `?digest=` for a manifest) shows." + }, + "DockerManageForm": { + "type": "object", + "properties": { + "tag": { + "type": "string", + "description": "The tag to delete (`DeleteTag`).", + "nullable": true + }, + "digest": { + "type": "string", + "description": "The manifest digest to delete (`DeleteManifest`).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of the Docker management handlers; every one asks for the caller's password." + }, + "DockerManageViewModel": { + "type": "object", + "properties": { + "image": { + "type": "string", + "description": "The image name from the address (it may contain slashes).", + "nullable": true + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciImageInfo" + } + ] + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? DockerManageViewModel.Message reports a refusal." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the user has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + } + }, + "description": "What the Docker image management screen (`/docker-manage/{**image}`) shows; filled by the screen's workflow." + }, + "EffectiveScanPolicy": { + "required": [ + "values", + "from", + "name" + ], + "type": "object", + "properties": { + "values": { + "$ref": "#/components/schemas/ScanPolicyValues" + }, + "from": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyScope" + } + ] + }, + "name": { + "type": "string", + "description": "The repository or project name it is stored for, or null.", + "nullable": true + } + }, + "description": "The policy in force for a repository: its own, else its project's, else none." + }, + "EmptyScreen": { + "type": "object", + "description": "The model of a screen that shows nothing but itself (the sign-out button), or of an action that only continues elsewhere." + }, + "ExternalLoginStatus": { + "required": [ + "id", + "displayName", + "linked" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id." + }, + "displayName": { + "type": "string", + "description": "The provider's name." + }, + "linked": { + "type": "boolean", + "description": "Whether the account has a linked login at this provider." + } + }, + "description": "A configured external provider as the account settings list it for one user." + }, + "ExternalProviderInfo": { + "required": [ + "id", + "displayName" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id: the value a form or `/api/ui/session/external/{provider}` names it by." + }, + "displayName": { + "type": "string", + "description": "The name on the button." + } + }, + "description": "An external sign-in provider as a screen offers it (one button per provider)." + }, + "FeedStatistics": { + "type": "object", + "properties": { + "packageIds": { + "type": "integer", + "format": "int32" + }, + "packageVersions": { + "type": "integer", + "format": "int32" + }, + "downloads": { + "type": "integer", + "format": "int64" + }, + "topPackages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDownloads" + }, + "description": "The most downloaded package IDs, all versions together.", + "nullable": true + }, + "recentVersions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDownloads" + }, + "description": "The most recently published versions.", + "nullable": true + } + } + }, + "ForgotPasswordForm": { + "required": [ + "identifier" + ], + "type": "object", + "properties": { + "identifier": { + "type": "string", + "description": "The user name or email address.", + "nullable": true + } + }, + "description": "What the \"forgot password\" form posts." + }, + "ForgotPasswordViewModel": { + "required": [ + "identifier" + ], + "type": "object", + "properties": { + "sent": { + "type": "boolean", + "description": "Whether the request was answered (always the same answer, see the use case)." + }, + "identifier": { + "type": "string", + "description": "The user name or email address.", + "nullable": true + } + }, + "description": "The \"forgot password\" screen. A request binds ForgotPasswordForm, never this type." + }, + "FormatCreateField": { + "required": [ + "name", + "label" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The key in the dictionary string? IFormatModule.CreateSettings(IReadOnlyDictionary<string, string?> fields) receives." + }, + "label": { + "type": "string", + "description": "The visible label." + }, + "help": { + "type": "string", + "description": "One line of explanation, or null.", + "nullable": true + }, + "required": { + "type": "boolean", + "description": "Whether an empty value is refused by the form.", + "default": false + }, + "options": { + "type": "array", + "items": { + "type": "string" + }, + "description": "For a choice: the allowed values; null for free text.", + "nullable": true + } + }, + "description": "An input of the create form a format contributes." + }, + "FormatLink": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "A stable identifier (`browse`, `upload`); becomes the CSS class `repository-{id}`.", + "nullable": true + }, + "label": { + "type": "string", + "description": "The visible text.", + "nullable": true + }, + "controller": { + "type": "string", + "description": "The MVC controller (without the suffix) of the screen it opens; null for a path link.", + "nullable": true + }, + "action": { + "type": "string", + "description": "The action of that controller that shows the screen; null for a path link.", + "nullable": true + }, + "path": { + "type": "string", + "description": "A path under the repository base; null for a screen link.", + "nullable": true + }, + "needsUploads": { + "type": "boolean", + "description": "Shown only for repositories that take uploads (not a remote one, nor a virtual one without a deploy repository)." + } + }, + "description": "A link a format contributes to the administration of a repository: to one of its screens or to a path under its base." + }, + "FormatRow": { + "required": [ + "module", + "repositories", + "capabilities" + ], + "type": "object", + "properties": { + "module": { + "$ref": "#/components/schemas/IFormatModule" + }, + "repositories": { + "type": "integer", + "description": "How many repositories use it.", + "format": "int32" + }, + "capabilities": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The capabilities its services implement." + } + }, + "description": "One format with what it offers, as the formats screen lists it." + }, + "FormatsViewModel": { + "type": "object", + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatRow" + }, + "description": "The formats." + } + }, + "description": "What the formats screen (`/admin/formats`) lists: the package formats this server can host." + }, + "FrameworkGroup": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The family (.NET, .NET Core, .NET Standard, .NET Framework, Other).", + "nullable": true + }, + "declared": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Frameworks the package ships assets for.", + "nullable": true + }, + "computed": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Frameworks the package works with without declaring them.", + "nullable": true + } + }, + "description": "The frameworks of one package, as the package page's Frameworks tab shows them." + }, + "GrantForm": { + "required": [ + "principalType", + "principalName", + "actions", + "password" + ], + "type": "object", + "properties": { + "principalType": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalType" + } + ] + }, + "principalName": { + "type": "string", + "description": "The principal's name.", + "nullable": true + }, + "actions": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The ticked AccessAction names (`Read`, `Annotate`, `Deploy`, `Delete`, `Manage`); none removes the grant.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Giving a principal the ticked actions through a permission target, replacing an earlier grant to it." + }, + "GrantInfo": { + "required": [ + "target", + "principalType", + "principalId", + "principal", + "actions" + ], + "type": "object", + "properties": { + "target": { + "type": "string" + }, + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string" + }, + "principal": { + "type": "string" + }, + "actions": { + "$ref": "#/components/schemas/AccessAction" + } + }, + "description": "A grant, with the target and principal in words." + }, + "GroupCreation": { + "required": [ + "name", + "description" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The group's name.", + "nullable": true + }, + "description": { + "type": "string", + "description": "What the group is for, or null.", + "nullable": true + } + }, + "description": "A new group." + }, + "GroupDetails": { + "required": [ + "group", + "members", + "grants" + ], + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/GroupSummary" + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupMemberInfo" + } + }, + "grants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GrantInfo" + } + } + }, + "description": "A group with its members and the grants naming it." + }, + "GroupDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The group name (route).", + "nullable": true + }, + "q": { + "type": "string", + "description": "User-name search for the member picker (contains).", + "nullable": true + }, + "group": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupDetails" + } + ] + }, + "found": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupMemberInfo" + }, + "description": "The users found by string? GroupDetailViewModel.Q, not yet members." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the group screen (`/admin/groups/{name}`) shows: the group, its members and the member search." + }, + "GroupMemberChange": { + "required": [ + "userId", + "password" + ], + "type": "object", + "properties": { + "userId": { + "type": "string", + "description": "The user's id (string GroupMemberInfo.UserId).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Adding a user to a group or removing them." + }, + "GroupMemberInfo": { + "required": [ + "userId", + "userName" + ], + "type": "object", + "properties": { + "userId": { + "type": "string" + }, + "userName": { + "type": "string" + } + }, + "description": "A member of a group." + }, + "GroupRename": { + "required": [ + "newName" + ], + "type": "object", + "properties": { + "newName": { + "type": "string", + "description": "The new name.", + "nullable": true + } + }, + "description": "Renaming a group." + }, + "GroupSummary": { + "required": [ + "key", + "name", + "description", + "isBuiltIn", + "memberCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string", + "nullable": true + }, + "isBuiltIn": { + "type": "boolean" + }, + "memberCount": { + "type": "integer", + "format": "int32" + } + }, + "description": "A group as the admin pages list it." + }, + "GroupsViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new group name.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The new group description.", + "nullable": true + }, + "groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupSummary" + }, + "description": "The groups." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the groups screen (`/admin/groups`) shows: the groups and the new-group form." + }, + "HealthProbe": { + "required": [ + "name", + "healthy", + "detail" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "`database`, `storage` or `cluster`." + }, + "healthy": { + "type": "boolean", + "description": "Whether it answered." + }, + "detail": { + "type": "string", + "description": "A short, credential-free note (the exception type when it failed).", + "nullable": true + }, + "informational": { + "type": "boolean", + "description": "The probe is reported but a failure does not make the node unready (the shared store: a node keeps serving without it).", + "default": false + } + }, + "description": "One probe of the readiness check." + }, + "HtmlString": { + "required": [ + "value" + ], + "type": "object", + "properties": { + "value": { + "type": "string", + "nullable": true + } + } + }, + "IAdminOperation": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The stable id used in forms and status (`catalog-rebuild`).", + "nullable": true + }, + "title": { + "type": "string", + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "requiresConfirmation": { + "type": "boolean", + "description": "Whether the operation deletes data, so the Operations page asks the administrator's password again before it starts it (as the\r\nother destructive pages do). Default: no." + } + }, + "description": "A long-running maintenance operation an administrator can start from the web UI for one repository\r\n(what the `catalog rebuild` and `import downloads` commands do). Registered as a singleton." + }, + "IFormatModule": { + "type": "object", + "properties": { + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "displayName": { + "type": "string", + "description": "The name shown to people: `NuGet`, `npm`.", + "nullable": true + }, + "routePrefix": { + "type": "string", + "description": "The path segment (or segments, without slashes at the ends) every route of the format starts with, after the repository\r\nbase: `npm`. Empty for NuGet, whose routes were there first.", + "nullable": true + }, + "feedPath": { + "type": "string", + "description": "The address a client is configured with, relative to the repository base (`r/{repo}/`, or the root for the default\r\nrepository): `v3/index.json` for NuGet, `npm/` for npm.", + "nullable": true + }, + "creatableKinds": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "description": "The kinds of repository that can be created through IRepositoryService without a dedicated administration\r\nservice (a virtual repository is created with its members by IVirtualRepositoryAdministration and is not\r\nlisted here). Kinds not listed are refused for this format.", + "nullable": true + }, + "supportsVirtual": { + "type": "boolean", + "description": "Whether virtual repositories of this format exist (Task<RepositoryInfo> IVirtualRepositoryAdministration.CreateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null, bool anonymousRead = true, RepositoryFormat format = RepositoryFormat.NuGet)): the format's\r\nreads then merge the members, and a write goes to the deploy repository. False for a format that has not implemented the\r\nmerge." + }, + "requiresStreamingStorage": { + "type": "boolean", + "description": "Whether the format stores blobs too large to buffer (Docker layers) and so needs a store that is an\r\nIStreamingStorageService. A repository of such a format is refused at creation when the configured store\r\ncannot stream (IStreamingStorageService StreamingStorage.Require(IStorageService? storage, string purpose))." + }, + "storageFolders": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The top-level storage folders the format writes below a repository's string RepositoryStorage.Prefix(RepositoryInfo repository)\r\n(`packages`, `symbols`…). Two modules may not claim the same folder, nor string RepositoryStorage.ReposFolder:\r\nFormatRegistry refuses the registration, since a collision would let one format read another's files.", + "nullable": true + }, + "createFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatCreateField" + }, + "description": "What the administrator fills in to create a repository of this format, on top of the name. Empty when a name is all that\r\nis needed.", + "nullable": true + } + }, + "description": "One package format (NuGet, npm, later Maven and OCI) as the common code sees it: what its repositories are called and where\r\nthey live, which kinds a repository of it can have, the UI it contributes, and how its artifacts are counted and purged.\r\nA module only describes the format; what it does per request is a set of services registered beside it\r\n(IFormatIndexer, IFormatSearchProvider, IFormatRetentionHooks,\r\nIFormatScanner, looked up with T? FormatServices.GetFormatService<T>(IServiceProvider provider, RepositoryFormat format)) and the format's own controllers,\r\nwhose routes go through `BaGetEndpointBuilder.MapRoute` with the module's RepositoryFormat IFormatModule.Format." + }, + "IFormFile": { + "type": "string", + "format": "binary" + }, + "IndexScreen": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The 1-based page of results.", + "format": "int32" + }, + "packageType": { + "type": "string", + "description": "The package type filter, `any` for none." + }, + "framework": { + "type": "string", + "description": "The target framework filter, `any` for none." + }, + "prerelease": { + "type": "boolean", + "description": "Whether prerelease versions are included." + }, + "sortBy": { + "$ref": "#/components/schemas/SearchSort" + }, + "supportedSorts": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchSort" + }, + "description": "The orders the search provider can apply on the server; with only the default there is nothing to choose." + }, + "isHome": { + "type": "boolean", + "description": "True for the front page: the repository's root with no search. Everything else lists packages." + }, + "totals": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/FeedStatistics" + } + ] + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchResult" + }, + "description": "The page of results (empty on the front page)." + }, + "lastUpdated": { + "type": "object", + "additionalProperties": { + "type": "string", + "format": "date-time" + }, + "description": "When each listed package ID was last published, by ID; empty when unsupported." + } + }, + "description": "What the front page and the package list show: the search that was asked for and its results." + }, + "InstallSnippet": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The tool the tab is for.", + "nullable": true + }, + "prefix": { + "type": "string", + "description": "A shell prompt shown before the first line; not part of the copied text.", + "nullable": true + }, + "lines": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The lines to copy.", + "nullable": true + } + }, + "description": "One tab of the \"install / configure / push\" commands of a package, artifact or image page (one tool per tab)." + }, + "JsonObject": { + "type": "object" + }, + "LeaseInfo": { + "required": [ + "job", + "node", + "since" + ], + "type": "object", + "properties": { + "job": { + "type": "string", + "description": "The job's name." + }, + "node": { + "type": "string", + "description": "The holder." + }, + "since": { + "type": "string", + "description": "When it was acquired (UTC).", + "format": "date-time" + } + }, + "description": "A lease as stored: the holder's node, a token that tells two holders of one node apart, and when it was taken." + }, + "LegalScreen": { + "required": [ + "title", + "contentHtml" + ], + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "The heading and page title." + }, + "contentHtml": { + "type": "string", + "description": "The operator's Markdown file as HTML (raw HTML in the source is escaped, script links neutralised: HtmlString? ReadmeMarkdown.ToSafeHtml(string? markdown))." + } + }, + "description": "What a legal page (Terms of Use, Privacy Policy) shows: its heading and the operator's Markdown rendered to safe HTML." + }, + "LoginForm": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed: a screen's model leaves it empty.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the sign-in form posts (and the body of `POST /api/ui/account/login`)." + }, + "LoginViewModel": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "allowRegistration": { + "type": "boolean", + "description": "Whether the registration link is shown." + }, + "hasExternalProvider": { + "type": "boolean", + "description": "Whether sign-in with an external provider is offered (any provider in IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders)." + }, + "externalProviderName": { + "type": "string", + "description": "The first provider's display name (kept for clients that offer one button); see IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders.", + "nullable": true + }, + "externalProviders": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalProviderInfo" + }, + "description": "The configured external providers, one sign-in button each." + }, + "emailIsConfigured": { + "type": "boolean", + "description": "Whether mail is configured (the forgot-password link is shown)." + }, + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "notice": { + "type": "string", + "description": "The notice to show.", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed: a screen's model leaves it empty.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The sign-in screen: the form fields it repeats and what it shows. A request never binds this type (the form is LoginForm), so\r\nthe outputs cannot be set from outside; string? LoginForm.Password is always empty." + }, + "LogLevelForm": { + "required": [ + "source", + "level", + "password" + ], + "type": "object", + "properties": { + "source": { + "type": "string", + "description": "The source (a namespace prefix).", + "nullable": true + }, + "level": { + "type": "string", + "description": "The level (ignored when removing).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Setting or removing the lowest level logged for one source." + }, + "LogLevelOverride": { + "required": [ + "source", + "level", + "inOverridesFile" + ], + "type": "object", + "properties": { + "source": { + "type": "string", + "description": "The namespace or type name prefix." + }, + "level": { + "type": "string", + "description": "Verbose, Debug, Information, Warning, Error or Fatal." + }, + "inOverridesFile": { + "type": "boolean", + "description": "True when the Settings overrides file holds it, so it can be removed from here; false when only a configuration file or the environment sets it." + } + }, + "description": "One `Serilog:MinimumLevel:Override:{Source}` entry: the lowest level logged for a source (a namespace or type\r\nname prefix such as `Microsoft.AspNetCore`)." + }, + "MavenArtifactInfo": { + "required": [ + "groupId", + "artifactId", + "created", + "modified", + "versions" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id." + }, + "artifactId": { + "type": "string", + "description": "The artifact id." + }, + "created": { + "type": "string", + "description": "The first deploy (UTC).", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenVersionSummary" + }, + "description": "Its versions, highest first." + }, + "latest": { + "$ref": "#/components/schemas/MavenVersionSummary" + }, + "name": { + "type": "string", + "description": "`group:artifact`.", + "nullable": true + } + }, + "description": "An artifact with its versions, newest first." + }, + "MavenArtifactsViewModel": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The page, from 1.", + "format": "int32" + }, + "result": { + "$ref": "#/components/schemas/MavenSearchPage" + }, + "settings": { + "$ref": "#/components/schemas/MavenRepositorySettings" + }, + "repositoryUrl": { + "type": "string", + "description": "The address Maven is configured with for this repository." + }, + "kind": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "repositoryName": { + "type": "string", + "description": "The repository's name, which is the `id` in `settings.xml` and the POM." + }, + "hasNext": { + "type": "boolean", + "description": "Whether another page follows." + }, + "configurationTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + } + }, + "description": "What the Maven front page (`/maven-artifacts`) shows: this page of search results and the client configuration." + }, + "MavenArtifactViewModel": { + "type": "object", + "properties": { + "group": { + "type": "string", + "description": "The group id from the address.", + "nullable": true + }, + "artifact": { + "type": "string", + "description": "The artifact id from the address.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version from the address; the latest when absent.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with: 200, or 404 when the artifact or version does not exist (the page then explains).", + "format": "int32" + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenArtifactInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenVersionDetail" + } + ] + }, + "repositoryUrl": { + "type": "string", + "description": "The address Maven is configured with for this repository." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name (the `id` in `settings.xml`)." + }, + "installTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The owners, when accounts are on; empty otherwise." + }, + "canManage": { + "type": "boolean", + "description": "Whether the signed-in user can open the manage page (an owner or an administrator)." + } + }, + "description": "What the page of one Maven artifact (`/maven-artifacts/{group}/{artifact}/{version?}`) shows." + }, + "MavenDeployment": { + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id.", + "nullable": true + }, + "artifactId": { + "type": "string", + "description": "The artifact id.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "packaging": { + "type": "string", + "description": "The packaging, the extension of the main file when it has no other (default `jar`).", + "nullable": true + }, + "classifier": { + "type": "string", + "description": "The classifier of the main file, or null.", + "nullable": true + }, + "extension": { + "type": "string", + "description": "The extension of the main file (default: the packaging).", + "nullable": true + }, + "file": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Stream" + } + ] + }, + "pom": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Stream" + } + ] + } + }, + "description": "What the upload page hands to Task<MavenResult> IMavenRepository.DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken)." + }, + "MavenFileDetail": { + "required": [ + "fileName", + "classifier", + "extension", + "size", + "sha1", + "md5", + "sha256", + "sha512", + "created", + "snapshotTimestamp", + "snapshotBuild" + ], + "type": "object", + "properties": { + "fileName": { + "type": "string", + "description": "The file name." + }, + "classifier": { + "type": "string", + "description": "The classifier, or null.", + "nullable": true + }, + "extension": { + "type": "string", + "description": "The extension." + }, + "size": { + "type": "integer", + "description": "Bytes.", + "format": "int64" + }, + "sha1": { + "type": "string", + "description": "SHA-1 hex." + }, + "md5": { + "type": "string", + "description": "MD5 hex." + }, + "sha256": { + "type": "string", + "description": "SHA-256 hex." + }, + "sha512": { + "type": "string", + "description": "SHA-512 hex." + }, + "created": { + "type": "string", + "description": "When stored (UTC).", + "format": "date-time" + }, + "snapshotTimestamp": { + "type": "string", + "description": "The snapshot build timestamp, or null.", + "nullable": true + }, + "snapshotBuild": { + "type": "integer", + "description": "The snapshot build number, or 0.", + "format": "int32" + } + }, + "description": "A file of a version as the pages list it." + }, + "MavenManageForm": { + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization (`AddOwner`, `RemoveOwner`).", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version whose files are listed, and the one a handler acts on (`DeleteFile`, `DeleteVersion`, `Cleanup`).", + "nullable": true + }, + "fileName": { + "type": "string", + "description": "The file to delete (`DeleteFile`).", + "nullable": true + }, + "keep": { + "type": "string", + "description": "How many snapshot builds to keep (`Cleanup`).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password, for the deleting handlers.", + "nullable": true + } + }, + "description": "The form of the Maven management handlers: the chosen version and what the handler needs." + }, + "MavenManageViewModel": { + "type": "object", + "properties": { + "group": { + "type": "string", + "description": "The group id from the address.", + "nullable": true + }, + "artifact": { + "type": "string", + "description": "The artifact id from the address.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version whose files are listed (`?version=`), or null.", + "nullable": true + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenArtifactInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenVersionDetail" + } + ] + }, + "owners": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageOwner" + }, + "description": "The artifact's owners." + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? MavenManageViewModel.Message reports a refusal." + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is an administrator." + }, + "actingAsAdministrator": { + "type": "boolean", + "description": "Whether the user manages the artifact only as an administrator (they are not an owner)." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the user has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "name": { + "type": "string", + "description": "`group:artifact`.", + "nullable": true + } + }, + "description": "What the Maven artifact management screen (`/maven-manage/{group}/{artifact}`) shows; filled by the screen's workflow." + }, + "MavenPolicy": { + "enum": [ + "Releases", + "Snapshots", + "Both" + ], + "type": "string", + "description": "Which versions a local Maven repository accepts." + }, + "MavenPomDependency": { + "required": [ + "groupId", + "artifactId", + "version", + "scope", + "optional" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id." + }, + "artifactId": { + "type": "string", + "description": "The artifact id." + }, + "version": { + "type": "string", + "description": "The version, or null (managed elsewhere).", + "nullable": true + }, + "scope": { + "type": "string", + "description": "The scope, or null (compile).", + "nullable": true + }, + "optional": { + "type": "boolean", + "description": "Whether the dependency is optional." + } + }, + "description": "A dependency a POM declares (versions and scopes as written; properties are not resolved)." + }, + "MavenPomInfo": { + "required": [ + "groupId", + "artifactId", + "version", + "packaging", + "name", + "description", + "url", + "parent", + "dependencies" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id (the parent's when the POM has none).", + "nullable": true + }, + "artifactId": { + "type": "string", + "description": "The artifact id.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version (the parent's when the POM has none).", + "nullable": true + }, + "packaging": { + "type": "string", + "description": "The packaging, `jar` by default." + }, + "name": { + "type": "string", + "description": "The `name`.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The `description`.", + "nullable": true + }, + "url": { + "type": "string", + "description": "The project `url`.", + "nullable": true + }, + "parent": { + "type": "string", + "description": "The parent as `group:artifact:version`, or null.", + "nullable": true + }, + "dependencies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenPomDependency" + }, + "description": "The declared dependencies, in order." + } + }, + "description": "What the search and the pages read from a POM." + }, + "MavenRepositorySettings": { + "type": "object", + "properties": { + "policy": { + "$ref": "#/components/schemas/MavenPolicy" + }, + "allowRedeploy": { + "type": "boolean", + "description": "Whether a release file that exists may be deployed again (replaced). The caller then also needs the Delete action, as\r\nArtifactory's Delete/Overwrite does. Default false: a release is immutable. Snapshots are never refused for this." + }, + "maxSnapshotBuilds": { + "type": "integer", + "description": "How many timestamped builds of a snapshot version are kept: when a deploy brings a newer build, older ones beyond this\r\nnumber are deleted. Zero keeps all (clean up on the artifact's page).", + "format": "int32" + } + }, + "description": "The settings of a local Maven repository, kept as JSON in string? Repository.Settings (no schema of their own)." + }, + "MavenSearchHit": { + "required": [ + "groupId", + "artifactId", + "version", + "name", + "description", + "modified" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id." + }, + "artifactId": { + "type": "string", + "description": "The artifact id." + }, + "version": { + "type": "string", + "description": "The newest version (a release if there is one), or null.", + "nullable": true + }, + "name": { + "type": "string", + "description": "The POM's name of it, or null.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The POM's description of it, or null.", + "nullable": true + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "coordinateName": { + "type": "string", + "description": "`group:artifact`.", + "nullable": true + } + }, + "description": "A search hit." + }, + "MavenSearchPage": { + "required": [ + "total", + "hits" + ], + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "All matches.", + "format": "int32" + }, + "hits": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenSearchHit" + }, + "description": "This page." + } + }, + "description": "A page of hits." + }, + "MavenUploadViewModel": { + "type": "object", + "properties": { + "accountsEnabled": { + "type": "boolean", + "description": "Whether accounts are on (the uploader then signs in)." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server is read-only." + }, + "signedIn": { + "type": "boolean", + "description": "Whether the visitor is signed in." + }, + "needsApiKey": { + "type": "boolean", + "description": "Without accounts there is no user to own an upload, so the uploader proves itself with the API key." + }, + "nothingCanAuthenticate": { + "type": "boolean", + "description": "Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed." + }, + "canUpload": { + "type": "boolean", + "description": "Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in." + }, + "repositoryUrl": { + "type": "string", + "description": "The address Maven is configured with for this repository." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name (the `id` in `settings.xml`)." + }, + "settings": { + "$ref": "#/components/schemas/MavenRepositorySettings" + }, + "message": { + "type": "string", + "description": "What happened, for the page to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? MavenUploadViewModel.Message reports a failure." + }, + "deployedName": { + "type": "string", + "description": "The artifact just deployed (`group:artifact`), so the page can link to it.", + "nullable": true + }, + "deployedVersion": { + "type": "string", + "description": "The version just deployed.", + "nullable": true + }, + "posted": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenDeployment" + } + ] + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with (200, or the refusal's).", + "format": "int32" + } + }, + "description": "What the Maven upload page (`/maven-upload`) shows, before and after a deployment." + }, + "MavenVersionDetail": { + "required": [ + "summary", + "files", + "pom", + "pomText" + ], + "type": "object", + "properties": { + "summary": { + "$ref": "#/components/schemas/MavenVersionSummary" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenFileDetail" + }, + "description": "Its files, by name." + }, + "pom": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenPomInfo" + } + ] + }, + "pomText": { + "type": "string", + "description": "The POM text (for the view), or null.", + "nullable": true + } + }, + "description": "One version with its files and POM." + }, + "MavenVersionSummary": { + "required": [ + "version", + "isSnapshot", + "name", + "description", + "packaging", + "created", + "modified", + "fileCount", + "size", + "builds" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version." + }, + "isSnapshot": { + "type": "boolean", + "description": "Whether it is a snapshot." + }, + "name": { + "type": "string", + "description": "The POM's name, or null.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The POM's description, or null.", + "nullable": true + }, + "packaging": { + "type": "string", + "description": "The POM's packaging, or null.", + "nullable": true + }, + "created": { + "type": "string", + "description": "The first file (UTC).", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "fileCount": { + "type": "integer", + "description": "Files of the version.", + "format": "int32" + }, + "size": { + "type": "integer", + "description": "Bytes of the version.", + "format": "int64" + }, + "builds": { + "type": "integer", + "description": "For a snapshot: how many timestamped builds it holds.", + "format": "int32" + } + }, + "description": "A version as the artifact page lists it." + }, + "NodeInfo": { + "required": [ + "id", + "started", + "seen", + "version", + "ready", + "problem", + "gateClosed" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The node's name." + }, + "started": { + "type": "string", + "description": "When it started (UTC).", + "format": "date-time" + }, + "seen": { + "type": "string", + "description": "Its latest heartbeat (UTC).", + "format": "date-time" + }, + "version": { + "type": "string", + "description": "The BaGet version it runs." + }, + "ready": { + "type": "boolean", + "description": "Whether its last readiness check passed." + }, + "problem": { + "type": "string", + "description": "What failed, when it did not.", + "nullable": true + }, + "gateClosed": { + "type": "boolean", + "description": "Whether its read-only gate is closed." + } + }, + "description": "A node as it publishes itself." + }, + "NpmManageDeprecateForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "message": { + "type": "string", + "description": "The deprecation message (`Deprecate` only).", + "nullable": true + } + }, + "description": "The form of `Deprecate` and `Undeprecate`." + }, + "NpmManageOwnerForm": { + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization.", + "nullable": true + } + }, + "description": "The form of the npm management handlers that name an owner." + }, + "NpmManageTagForm": { + "type": "object", + "properties": { + "tag": { + "type": "string", + "description": "The dist-tag.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version it points at (not used by `RemoveTag`).", + "nullable": true + } + }, + "description": "The form of `SetTag`." + }, + "NpmManageUnpublishForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version (`Unpublish` only).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of `Unpublish` (one version) and `UnpublishAll` (the version is ignored); the password confirms." + }, + "NpmManageViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package name from the address.", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmPackageInfo" + } + ] + }, + "owners": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageOwner" + }, + "description": "The package's owners." + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? NpmManageViewModel.Message reports a refusal." + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is an administrator." + }, + "actingAsAdministrator": { + "type": "boolean", + "description": "Whether the user manages the package only as an administrator (they are not an owner)." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the user has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "unpublishWindow": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": "string", + "description": "How long after publishing a version its owner may unpublish it with Deploy alone." + } + }, + "description": "What the npm package management screen (`/npm-manage/{*id}`) shows; filled by the screen's workflow." + }, + "NpmPackageInfo": { + "required": [ + "name", + "created", + "modified", + "distTags", + "versions" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name (`@scope/name` for a scoped package)." + }, + "created": { + "type": "string", + "description": "The first publish.", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change.", + "format": "date-time" + }, + "distTags": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Tag to version." + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NpmVersionInfo" + }, + "description": "Every version, oldest first by semantic version." + }, + "latest": { + "$ref": "#/components/schemas/NpmVersionInfo" + }, + "revision": { + "type": "string", + "description": "The document revision clients send back on a write (`?write=true` reads, `/-rev/{rev}` writes): changes with every change of the package.", + "nullable": true + } + }, + "description": "A package with its versions and dist-tags, as stored." + }, + "NpmPackagesViewModel": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The page, from 1.", + "format": "int32" + }, + "result": { + "$ref": "#/components/schemas/NpmSearchPage" + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "hasNext": { + "type": "boolean", + "description": "Whether another page follows." + } + }, + "description": "What the npm front page (`/npm-packages`) shows: this page of search results and the registry address." + }, + "NpmPackageViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package name from the address.", + "nullable": true + }, + "requestedVersion": { + "type": "string", + "description": "The version asked for with `?version=`; the latest when absent or unknown.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with: 200, or 404 when the package does not exist (the page then explains).", + "format": "int32" + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmPackageInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmVersionInfo" + } + ] + }, + "readme": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/HtmlString" + } + ] + }, + "selectedTags": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The dist-tags that point at the selected version." + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "tarballUrl": { + "type": "string", + "description": "Where the selected version's tarball is.", + "nullable": true + }, + "installTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The owners, when accounts are on; empty otherwise." + }, + "canManage": { + "type": "boolean", + "description": "Whether the signed-in user can open the manage page (an owner or an administrator)." + } + }, + "description": "What the page of one npm package (`/npm-packages/{name}`) shows." + }, + "NpmSearchHit": { + "required": [ + "name", + "version", + "description", + "keywords", + "modified" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name." + }, + "version": { + "type": "string", + "description": "The latest version.", + "nullable": true + }, + "description": { + "type": "string", + "description": "Its description.", + "nullable": true + }, + "keywords": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Its keywords." + }, + "modified": { + "type": "string", + "description": "The last change.", + "format": "date-time" + } + }, + "description": "One package in a search result." + }, + "NpmSearchPage": { + "required": [ + "total", + "hits" + ], + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "All matches.", + "format": "int32" + }, + "hits": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NpmSearchHit" + }, + "description": "This page, ordered by name." + } + }, + "description": "A page of packages." + }, + "NpmUploadViewModel": { + "type": "object", + "properties": { + "accountsEnabled": { + "type": "boolean", + "description": "Whether accounts are on (the uploader then signs in)." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server is read-only." + }, + "signedIn": { + "type": "boolean", + "description": "Whether the visitor is signed in." + }, + "needsApiKey": { + "type": "boolean", + "description": "Without accounts there is no user to own an upload, so the uploader proves itself with the API key." + }, + "nothingCanAuthenticate": { + "type": "boolean", + "description": "Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed." + }, + "canUpload": { + "type": "boolean", + "description": "Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in." + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "publishLines": { + "type": "array", + "items": { + "type": "string" + } + }, + "message": { + "type": "string", + "description": "What happened, for the page to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? NpmUploadViewModel.Message reports a failure." + }, + "publishedName": { + "type": "string", + "description": "The package just published, so the page can link to it.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with (200, or the refusal's).", + "format": "int32" + } + }, + "description": "What the npm upload page (`/npm-upload`) shows, before and after a publish." + }, + "NpmVersionInfo": { + "required": [ + "version", + "published", + "deprecated", + "tarballSize", + "integrity", + "shasum", + "manifest" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version string as published." + }, + "published": { + "type": "string", + "description": "When it was published.", + "format": "date-time" + }, + "deprecated": { + "type": "string", + "description": "The deprecation message, or null.", + "nullable": true + }, + "tarballSize": { + "type": "integer", + "description": "Bytes of the tarball.", + "format": "int64" + }, + "integrity": { + "type": "string", + "description": "The tarball's SRI string (`sha512-…`)." + }, + "shasum": { + "type": "string", + "description": "The tarball's SHA-1 in hex." + }, + "manifest": { + "$ref": "#/components/schemas/JsonObject" + }, + "description": { + "type": "string", + "description": "The manifest's `description`, or null.", + "nullable": true + }, + "readme": { + "type": "string", + "description": "The manifest's `readme`, or null.", + "nullable": true + }, + "license": { + "type": "string", + "description": "The manifest's `license` when it is a string, or null.", + "nullable": true + }, + "keywords": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The manifest's `keywords` that are strings.", + "nullable": true + } + }, + "description": "One published version as stored." + }, + "NuGetVersion": { + "type": "object", + "properties": { + "version": { + "pattern": "^\\d+(\\.\\d+){1,3}$", + "type": "string", + "nullable": true + }, + "isLegacyVersion": { + "type": "boolean" + }, + "revision": { + "type": "integer", + "format": "int32" + }, + "isSemVer2": { + "type": "boolean" + }, + "originalVersion": { + "type": "string", + "nullable": true + }, + "major": { + "type": "integer", + "format": "int32" + }, + "minor": { + "type": "integer", + "format": "int32" + }, + "patch": { + "type": "integer", + "format": "int32" + }, + "releaseLabels": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "release": { + "type": "string", + "nullable": true + }, + "isPrerelease": { + "type": "boolean" + }, + "hasMetadata": { + "type": "boolean" + }, + "metadata": { + "type": "string", + "nullable": true + } + } + }, + "OciDescriptor": { + "required": [ + "mediaType", + "digest", + "size", + "artifactType", + "annotations" + ], + "type": "object", + "properties": { + "mediaType": { + "type": "string", + "description": "The referrer's media type." + }, + "digest": { + "type": "string", + "description": "Its digest." + }, + "size": { + "type": "integer", + "description": "Its size.", + "format": "int64" + }, + "artifactType": { + "type": "string", + "description": "Its artifact type, or null.", + "nullable": true + }, + "annotations": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Its annotations, or null.", + "nullable": true + } + }, + "description": "A descriptor in a referrers index." + }, + "OciGcItem": { + "required": [ + "kind", + "subject", + "bytes", + "image" + ], + "type": "object", + "properties": { + "kind": { + "$ref": "#/components/schemas/OciGcItemKind" + }, + "subject": { + "type": "string", + "description": "A digest or a session reference." + }, + "bytes": { + "type": "integer", + "description": "Bytes it frees (0 for a session).", + "format": "int64" + }, + "image": { + "type": "string", + "description": "The image it belonged to, if any.", + "nullable": true + } + }, + "description": "One thing a garbage collection removes." + }, + "OciGcItemKind": { + "enum": [ + "ExpiredUpload", + "UnreferencedLayer", + "OrphanBlob", + "OrphanFile" + ], + "type": "string", + "description": "What a garbage collection found (or, outside a dry run, removed)." + }, + "OciGcReport": { + "required": [ + "dryRun", + "repository", + "expiredUploads", + "unreferencedLayers", + "blobs", + "orphanFiles", + "bytes", + "items", + "itemsTruncated", + "note" + ], + "type": "object", + "properties": { + "dryRun": { + "type": "boolean", + "description": "Whether nothing was changed (the numbers are what a run would remove)." + }, + "repository": { + "type": "string", + "description": "The repository." + }, + "expiredUploads": { + "type": "integer", + "description": "Upload sessions discarded.", + "format": "int32" + }, + "unreferencedLayers": { + "type": "integer", + "description": "Image-to-layer links dropped (a layer two images hold counts twice).", + "format": "int32" + }, + "blobs": { + "type": "integer", + "description": "Blobs (rows and files) removed: those no image holds after the links are dropped, orphan rows included.", + "format": "int32" + }, + "orphanFiles": { + "type": "integer", + "description": "Files under the blob folder with no row, removed.", + "format": "int32" + }, + "bytes": { + "type": "integer", + "description": "Bytes freed by the blobs and orphan files, as far as they are known (an orphan file's size is not).", + "format": "int64" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciGcItem" + }, + "description": "The first of the things removed (the list is capped)." + }, + "itemsTruncated": { + "type": "boolean", + "description": "Whether there are more than Items holds." + }, + "note": { + "type": "string", + "description": "Something the run could not do (the store cannot list files), or null.", + "nullable": true + }, + "summary": { + "type": "string", + "description": "One line for the Operations page and the audit log.", + "nullable": true + } + }, + "description": "The outcome of one garbage collection of a repository." + }, + "OciImageInfo": { + "required": [ + "name", + "created", + "modified", + "tags", + "manifests", + "size", + "unreferencedBlobs" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The image name." + }, + "created": { + "type": "string", + "description": "When the first upload arrived (UTC).", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "tags": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciTagInfo" + }, + "description": "The tags, by name." + }, + "manifests": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciManifestSummary" + }, + "description": "The manifests, newest first." + }, + "size": { + "type": "integer", + "description": "Bytes of the distinct blobs the image holds.", + "format": "int64" + }, + "unreferencedBlobs": { + "type": "integer", + "description": "Blobs held by the image that no manifest uses.", + "format": "int32" + } + }, + "description": "An image with its tags and manifests (the image page)." + }, + "OciImagePage": { + "required": [ + "total", + "images" + ], + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "All images that matched and may be read.", + "format": "int32" + }, + "images": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciImageSummary" + }, + "description": "The page." + } + }, + "description": "A page of OciImageSummary." + }, + "OciImageSummary": { + "required": [ + "name", + "tags", + "manifests", + "size", + "modified" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The image name." + }, + "tags": { + "type": "integer", + "description": "Number of tags.", + "format": "int32" + }, + "manifests": { + "type": "integer", + "description": "Number of manifests (including indexes).", + "format": "int32" + }, + "size": { + "type": "integer", + "description": "Bytes of the distinct blobs the image holds.", + "format": "int64" + }, + "modified": { + "type": "string", + "description": "The last manifest or tag change (UTC).", + "format": "date-time" + } + }, + "description": "An image as the browse page lists it." + }, + "OciLayerInfo": { + "required": [ + "digest", + "size", + "mediaType" + ], + "type": "object", + "properties": { + "digest": { + "type": "string", + "description": "The digest." + }, + "size": { + "type": "integer", + "description": "The size announced by the manifest.", + "format": "int64" + }, + "mediaType": { + "type": "string", + "description": "The media type." + } + }, + "description": "A layer, config or other blob a manifest lists." + }, + "OciManifestDetail": { + "required": [ + "summary", + "json", + "config", + "layers", + "platforms", + "annotations" + ], + "type": "object", + "properties": { + "summary": { + "$ref": "#/components/schemas/OciManifestSummary" + }, + "json": { + "type": "string", + "description": "The manifest document, pretty-printed for display (the stored bytes are unchanged)." + }, + "config": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciLayerInfo" + } + ] + }, + "layers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciLayerInfo" + }, + "description": "The layers in order (empty for an index)." + }, + "platforms": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciPlatformInfo" + }, + "description": "The entries of an index (empty for a single-image manifest)." + }, + "annotations": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The manifest's annotations." + } + }, + "description": "One manifest in full (the manifest page)." + }, + "OciManifestSummary": { + "required": [ + "digest", + "mediaType", + "size", + "isIndex", + "created", + "tags", + "artifactType", + "subjectDigest", + "platform", + "layerCount", + "contentSize" + ], + "type": "object", + "properties": { + "digest": { + "type": "string", + "description": "Its digest." + }, + "mediaType": { + "type": "string", + "description": "Its media type." + }, + "size": { + "type": "integer", + "description": "Bytes of the manifest document.", + "format": "int64" + }, + "isIndex": { + "type": "boolean", + "description": "Whether it is an index of platform manifests." + }, + "created": { + "type": "string", + "description": "When it was first pushed to the image (UTC).", + "format": "date-time" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The tags that point at it." + }, + "artifactType": { + "type": "string", + "description": "Its artifact type, or null.", + "nullable": true + }, + "subjectDigest": { + "type": "string", + "description": "The digest it refers to, or null.", + "nullable": true + }, + "platform": { + "type": "string", + "description": "For a single-image manifest, its platform when the config says so (`linux/amd64`); otherwise null.", + "nullable": true + }, + "layerCount": { + "type": "integer", + "description": "Number of layers (0 for an index).", + "format": "int32" + }, + "contentSize": { + "type": "integer", + "description": "Bytes of the config and layers (the children are not summed for an index).", + "format": "int64" + } + }, + "description": "A manifest as the image page lists it." + }, + "OciPlatformInfo": { + "required": [ + "digest", + "mediaType", + "size", + "os", + "architecture", + "variant", + "present" + ], + "type": "object", + "properties": { + "digest": { + "type": "string", + "description": "The child manifest." + }, + "mediaType": { + "type": "string", + "description": "The child's media type." + }, + "size": { + "type": "integer", + "description": "The child's size.", + "format": "int64" + }, + "os": { + "type": "string", + "description": "The operating system, or null.", + "nullable": true + }, + "architecture": { + "type": "string", + "description": "The architecture, or null.", + "nullable": true + }, + "variant": { + "type": "string", + "description": "The variant (`v7`), or null.", + "nullable": true + }, + "present": { + "type": "boolean", + "description": "Whether the child manifest is in this image." + }, + "platform": { + "type": "string", + "description": "The platform as one string: `linux/arm64/v8` (or `unknown` for an entry with none).", + "nullable": true + } + }, + "description": "A platform entry of an index." + }, + "OciTagInfo": { + "required": [ + "name", + "digest", + "updated" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The tag." + }, + "digest": { + "type": "string", + "description": "The manifest it points at." + }, + "updated": { + "type": "string", + "description": "When it was created or moved (UTC).", + "format": "date-time" + } + }, + "description": "A tag of an image." + }, + "OperationForm": { + "required": [ + "operation", + "repository", + "password" + ], + "type": "object", + "properties": { + "operation": { + "type": "string", + "description": "The operation's name (`catalog-rebuild`).", + "nullable": true + }, + "repository": { + "type": "string", + "description": "The repository it runs on.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (asked for operations that delete data).", + "nullable": true + } + }, + "description": "Starting a maintenance operation." + }, + "OperationRow": { + "required": [ + "operation", + "repository", + "status" + ], + "type": "object", + "properties": { + "operation": { + "$ref": "#/components/schemas/IAdminOperation" + }, + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "status": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AdminJobStatus" + } + ] + } + }, + "description": "One row of the operations screen: an operation on a repository." + }, + "OperationsViewModel": { + "type": "object", + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OperationRow" + }, + "description": "The operations available on this server, for every repository." + }, + "anyRunning": { + "type": "boolean", + "description": "Whether any job is running (the page refreshes itself)." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the operations screen (`/admin/operations`) shows: the maintenance operations and the status of each." + }, + "Organization": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + } + }, + "description": "An account that several users own packages through." + }, + "OrganizationDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization's name (route).", + "nullable": true + }, + "organization": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Organization" + } + ] + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrganizationMemberRow" + }, + "description": "Its members, by name." + }, + "ownedPackageIds": { + "type": "integer", + "description": "How many package IDs it owns, in every repository.", + "format": "int32" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the organization screen (`/admin/organizations/{name}`) shows: the organization, its members and the last action." + }, + "OrganizationMemberForm": { + "required": [ + "userName", + "isAdmin", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The member's user name.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the member administers the organization (ignored when removing)." + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Adding a member to an organization, changing their administrator flag or removing them." + }, + "OrganizationMemberRow": { + "required": [ + "userName", + "isAdmin" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the member administers the organization." + } + }, + "description": "A member as the organization page lists them." + }, + "OrganizationOutcome": { + "required": [ + "name", + "outcome" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization.", + "nullable": true + }, + "outcome": { + "type": "string", + "description": "A sentence for the confirmation page." + } + }, + "description": "What happens to one organization when an administrator deletes a member." + }, + "OrganizationRenameForm": { + "required": [ + "newName", + "password" + ], + "type": "object", + "properties": { + "newName": { + "type": "string", + "description": "The new name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Renaming an organization." + }, + "OrganizationSummary": { + "required": [ + "name", + "created", + "members", + "administrators", + "packageIds" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When it was created.", + "format": "date-time" + }, + "members": { + "type": "integer", + "description": "How many members it has.", + "format": "int32" + }, + "administrators": { + "type": "integer", + "description": "How many of them administer it.", + "format": "int32" + }, + "packageIds": { + "type": "integer", + "description": "How many package IDs it owns, counted per repository.", + "format": "int32" + } + }, + "description": "An organization as the administrator's list shows it." + }, + "OrganizationsViewModel": { + "type": "object", + "properties": { + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccountOrganization" + }, + "description": "The organizations the user belongs to." + }, + "message": { + "type": "string", + "description": "The answer to the last action.", + "nullable": true + } + }, + "description": "The signed-in user's organizations screen." + }, + "OwnedPackage": { + "type": "object", + "properties": { + "id": { + "type": "string", + "nullable": true + }, + "latestVersion": { + "type": "string", + "description": "The highest version, listed or not, or null when no version remains.", + "nullable": true + }, + "latestVersionIsListed": { + "type": "boolean" + }, + "versionCount": { + "type": "integer", + "format": "int32" + }, + "downloads": { + "type": "integer", + "format": "int64" + } + }, + "description": "One owned package ID, summarised across its versions." + }, + "Package": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "id": { + "type": "string", + "nullable": true + }, + "version": { + "$ref": "#/components/schemas/NuGetVersion" + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "downloads": { + "type": "integer", + "format": "int64" + }, + "hasReadme": { + "type": "boolean" + }, + "hasEmbeddedIcon": { + "type": "boolean" + }, + "isPrerelease": { + "type": "boolean" + }, + "releaseNotes": { + "type": "string", + "nullable": true + }, + "language": { + "type": "string", + "nullable": true + }, + "listed": { + "type": "boolean" + }, + "minClientVersion": { + "type": "string", + "nullable": true + }, + "published": { + "type": "string", + "description": "The time at which the package was published, in UTC.", + "format": "date-time" + }, + "requireLicenseAcceptance": { + "type": "boolean" + }, + "semVerLevel": { + "$ref": "#/components/schemas/SemVerLevel" + }, + "summary": { + "type": "string", + "nullable": true + }, + "title": { + "type": "string", + "nullable": true + }, + "iconUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "projectUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "repositoryUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "repositoryType": { + "type": "string", + "nullable": true + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "rowVersion": { + "type": "string", + "description": "Used for optimistic concurrency.", + "format": "byte", + "nullable": true + }, + "dependencies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDependency" + }, + "nullable": true + }, + "packageTypes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageType" + }, + "nullable": true + }, + "targetFrameworks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TargetFramework" + }, + "nullable": true + }, + "deprecation": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageDeprecation" + } + ] + }, + "vulnerabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageVulnerability" + }, + "description": "The known vulnerabilities affecting this version.", + "nullable": true + }, + "normalizedVersionString": { + "type": "string", + "nullable": true + }, + "originalVersionString": { + "type": "string", + "nullable": true + }, + "iconUrlString": { + "type": "string", + "nullable": true + }, + "licenseUrlString": { + "type": "string", + "nullable": true + }, + "projectUrlString": { + "type": "string", + "nullable": true + }, + "repositoryUrlString": { + "type": "string", + "nullable": true + } + } + }, + "PackageDeletionBehavior": { + "enum": [ + "Unlist", + "HardDelete" + ], + "type": "string", + "description": "How BaGet should interpret package deletion requests.\r\nSee: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package" + }, + "PackageDependency": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "id": { + "type": "string", + "description": "The dependency's package ID. Null if this is a dependency group without any dependencies.", + "nullable": true + }, + "versionRange": { + "type": "string", + "description": "The dependency's package version. Null if this is a dependency group without any dependencies.", + "nullable": true + }, + "targetFramework": { + "type": "string", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + } + }, + "PackageDependent": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The dependent package id.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description of the dependent package.", + "nullable": true + }, + "totalDownloads": { + "type": "integer", + "description": "The total downloads for the dependent package.", + "format": "int64" + } + }, + "description": "A package that depends on the queried package." + }, + "PackageDeprecation": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "reasons": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the package was deprecated. The protocol defines \"Legacy\", \"CriticalBugs\"\r\nand \"Other\"; a package may carry more than one.", + "nullable": true + }, + "message": { + "type": "string", + "description": "Free text explaining the deprecation. Optional.", + "nullable": true + }, + "alternatePackageId": { + "type": "string", + "description": "The ID of the package to use instead. Null if none was suggested.", + "nullable": true + }, + "alternateVersionRange": { + "type": "string", + "description": "The versions of the alternate package that may be used, or \"*\" for any.\r\nNull if no alternate package was suggested.", + "nullable": true + }, + "packageKey": { + "type": "integer", + "description": "The key of the deprecated package version. Nullable so that the relationship\r\nstays optional in the database: a required one would need a foreign key change,\r\nwhich SQLite cannot make in place.", + "format": "int32", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + }, + "description": "A package version marked as deprecated.\r\nSee: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation" + }, + "PackageDetails": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The normalized version.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description.", + "nullable": true + }, + "releaseNotes": { + "type": "string", + "description": "The release notes.", + "nullable": true + }, + "projectUrl": { + "type": "string", + "description": "The project website, or an empty string.", + "nullable": true + }, + "repositoryUrl": { + "type": "string", + "description": "The source repository, or an empty string.", + "nullable": true + }, + "downloads": { + "type": "integer", + "description": "The downloads of this version.", + "format": "int64" + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The authors." + } + }, + "description": "What the package page shows about the version it displays (a flat copy of the stored package, with no navigation properties)." + }, + "PackageDownloads": { + "type": "object", + "properties": { + "id": { + "type": "string", + "nullable": true + }, + "version": { + "type": "string", + "description": "Null when the downloads are a whole package ID's.", + "nullable": true + }, + "downloads": { + "type": "integer", + "format": "int64" + }, + "published": { + "type": "string", + "format": "date-time", + "nullable": true + } + } + }, + "PackageManageDeprecateForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "reasons": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The reasons (at least one of `Legacy`, `CriticalBugs`, `Other`).", + "nullable": true + }, + "message": { + "type": "string", + "description": "Free text, optional.", + "nullable": true + }, + "alternatePackageId": { + "type": "string", + "description": "The package to use instead, optional.", + "nullable": true + }, + "alternateVersionRange": { + "type": "string", + "description": "The versions of it that may be used, optional (needs string? PackageManageDeprecateForm.AlternatePackageId).", + "nullable": true + } + }, + "description": "The form of `Deprecate`." + }, + "PackageManageDeprecation": { + "required": [ + "reasons", + "message", + "alternatePackageId", + "alternateVersionRange" + ], + "type": "object", + "properties": { + "reasons": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why (`Legacy`, `CriticalBugs`, `Other`)." + }, + "message": { + "type": "string", + "description": "Free text, or null.", + "nullable": true + }, + "alternatePackageId": { + "type": "string", + "description": "The package to use instead, or null.", + "nullable": true + }, + "alternateVersionRange": { + "type": "string", + "description": "The versions of it that may be used, or null.", + "nullable": true + } + }, + "description": "A version's deprecation." + }, + "PackageManageHardDeleteForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of a permanent deletion of a version (administrators; the password confirms)." + }, + "PackageManageOwner": { + "required": [ + "ownerName", + "isVerified" + ], + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization name.", + "nullable": true + }, + "isVerified": { + "type": "boolean", + "description": "Whether the ID is reserved for this owner." + } + }, + "description": "An owner of a package ID." + }, + "PackageManageOwnerForm": { + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization.", + "nullable": true + } + }, + "description": "The form of a handler that names an owner." + }, + "PackageManagePasswordForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of a handler that only asks for the password." + }, + "PackageManageRemoveVulnerabilityForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "key": { + "type": "integer", + "description": "The vulnerability's key.", + "format": "int32" + } + }, + "description": "The form of `RemoveVulnerability`." + }, + "PackageManageReport": { + "required": [ + "key", + "packageVersion", + "reason", + "details", + "reporterEmail" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The report's key (what `ResolveReport` takes).", + "format": "int32" + }, + "packageVersion": { + "type": "string", + "description": "The reported version.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "The reason given.", + "nullable": true + }, + "details": { + "type": "string", + "description": "The details given.", + "nullable": true + }, + "reporterEmail": { + "type": "string", + "description": "Where to reply, if the reporter gave an address.", + "nullable": true + } + }, + "description": "An open abuse report." + }, + "PackageManageReportForm": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The report's key.", + "format": "int32" + } + }, + "description": "The form of `ResolveReport`." + }, + "PackageManageScreen": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID from the address.", + "nullable": true + }, + "owners": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageOwner" + }, + "description": "The ID's owners." + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageVersion" + }, + "description": "The ID's versions, newest first, unlisted ones included." + }, + "reports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageReport" + }, + "description": "The open abuse reports against the ID." + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "hasValidation": { + "type": "boolean", + "description": "Whether validation has submissions for the ID." + }, + "isVerified": { + "type": "boolean", + "description": "Whether the ID is verified (reserved)." + }, + "symbols": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageSymbol" + } + }, + "description": "The PDBs indexed from each version's symbol package, by normalized version." + }, + "symbolsSupported": { + "type": "boolean", + "description": "Whether the database records symbols per package version." + }, + "severityNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The severity names a vulnerability can have, by their protocol number." + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the caller is an administrator." + }, + "actingAsAdministrator": { + "type": "boolean", + "description": "Whether the caller manages this ID only as an administrator (not as an owner)." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the caller has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "deletionBehavior": { + "$ref": "#/components/schemas/PackageDeletionBehavior" + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server refuses writes." + } + }, + "description": "What the package management screen (`/packages/{id}/manage`) shows, as plain data (the JSON model of `/api/ui/packages/{id}/manage`).\r\nThe page's own `ManageViewModel` is built from it for the view." + }, + "PackageManageSymbol": { + "required": [ + "fileName", + "key" + ], + "type": "object", + "properties": { + "fileName": { + "type": "string", + "description": "The PDB file name." + }, + "key": { + "type": "string", + "description": "Its signature key." + } + }, + "description": "An indexed PDB of a version." + }, + "PackageManageVerifiedForm": { + "type": "object", + "properties": { + "verified": { + "type": "boolean", + "description": "Whether the ID is verified." + } + }, + "description": "The form of `SetVerified`." + }, + "PackageManageVersion": { + "required": [ + "version", + "normalizedVersion", + "downloads", + "listed", + "deprecation", + "vulnerabilities" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version as published (original text)." + }, + "normalizedVersion": { + "type": "string", + "description": "The normalized version, which the forms post back.", + "nullable": true + }, + "downloads": { + "type": "integer", + "description": "The download count.", + "format": "int64" + }, + "listed": { + "type": "boolean", + "description": "Whether the version is listed." + }, + "deprecation": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecation" + } + ] + }, + "vulnerabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageVulnerability" + }, + "description": "Its vulnerabilities." + } + }, + "description": "One version of the ID." + }, + "PackageManageVersionForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The (normalized) version.", + "nullable": true + } + }, + "description": "The form of a handler that names a version." + }, + "PackageManageVulnerability": { + "required": [ + "key", + "advisoryUrl", + "severity", + "versionRange", + "source" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The row's key (what `RemoveVulnerability` takes).", + "format": "int32" + }, + "advisoryUrl": { + "type": "string", + "description": "The advisory.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "0 low, 1 moderate, 2 high, 3 critical.", + "format": "int32" + }, + "versionRange": { + "type": "string", + "description": "The affected range, or null.", + "nullable": true + }, + "source": { + "type": "string", + "description": "Null for a manual entry, `osv` for one the scanner wrote (not editable here).", + "nullable": true + } + }, + "description": "A vulnerability recorded for a version." + }, + "PackageManageVulnerabilityForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "advisoryUrl": { + "type": "string", + "description": "The advisory URL.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "0 low, 1 moderate, 2 high, 3 critical.", + "format": "int32" + }, + "versionRange": { + "type": "string", + "description": "The affected range, optional.", + "nullable": true + } + }, + "description": "The form of `AddVulnerability`." + }, + "PackageOwner": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "packageId": { + "type": "string", + "nullable": true + }, + "ownerName": { + "type": "string", + "description": "A user name or an organization name.", + "nullable": true + }, + "isVerified": { + "type": "boolean", + "description": "Set by the server's administrator to mark the ID as reserved for this owner,\r\nwhich search reports as \"verified\"." + } + }, + "description": "An owner of every version of a package ID." + }, + "PackageScreen": { + "type": "object", + "properties": { + "found": { + "type": "boolean", + "description": "False when the package (or any listed version of it) does not exist; PackageDetails PackageScreen.Package then only names the ID." + }, + "package": { + "$ref": "#/components/schemas/PackageDetails" + }, + "isDotnetTemplate": { + "type": "boolean", + "description": "The package is a dotnet template." + }, + "isDotnetTool": { + "type": "boolean", + "description": "The package is a dotnet tool." + }, + "lastUpdated": { + "type": "string", + "description": "When any version was last published.", + "format": "date-time" + }, + "totalDownloads": { + "type": "integer", + "description": "Downloads of every version.", + "format": "int64" + }, + "usedBy": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDependent" + }, + "description": "The packages that depend on this one." + }, + "dependencyGroups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DependencyGroupModel" + }, + "description": "The dependencies, by framework." + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageVersionEntry" + }, + "description": "The listed versions, newest first." + }, + "readmeHtml": { + "type": "string", + "description": "The readme as safe HTML (ReadmeMarkdown), or null.", + "nullable": true + }, + "frameworkGroups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrameworkGroup" + }, + "description": "The frameworks the package supports, by family." + }, + "installTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + }, + "description": "The install commands, one tab per tool." + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Owner names; empty unless accounts are enabled and the package has owners." + }, + "ownerAvatars": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The avatar address of each owner by name; empty when Gravatar is off or accounts are disabled." + }, + "manageUrl": { + "type": "string", + "description": "Where the management page is, when the caller may open it (an owner holding the Manage permission, or an administrator), else null.\r\nThe use case answers an application-relative address (`~/packages/…`); the controller resolves it against the path base.", + "nullable": true + }, + "iconUrl": { + "type": "string", + "description": "The icon address.", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "description": "The license address, null for a license expression or file.", + "nullable": true + }, + "packageDownloadUrl": { + "type": "string", + "description": "Where the package file is downloaded.", + "nullable": true + }, + "packageExplorerUrl": { + "type": "string", + "description": "This version on nuget.info, the web app of NuGet Package Explorer, as nuget.org links it. nuget.info always downloads from\r\nnuget.org, so the link only works for a package that is also published there.", + "nullable": true + } + }, + "description": "What the package page shows." + }, + "PackageType": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "nullable": true + }, + "version": { + "type": "string", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + } + }, + "PackageValidation": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "submissionId": { + "type": "string", + "nullable": true + }, + "packageId": { + "type": "string", + "nullable": true + }, + "packageVersion": { + "type": "string", + "description": "The normalized version.", + "nullable": true + }, + "packageKey": { + "type": "integer", + "description": "The indexed package, once the submission succeeds. Nullable so that the\r\nrelationship is additive; see PackageDeprecation.", + "format": "int32", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + }, + "type": { + "type": "string", + "description": "The validator's name, or string PackageValidation.IndexType.", + "nullable": true + }, + "state": { + "$ref": "#/components/schemas/PackageValidationState" + }, + "message": { + "type": "string", + "description": "Why the step failed, if it did.", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "completed": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + "description": "One step of validating a pushed package: a validator's verdict, or the final\r\nindexing step. A submission is every row sharing a string? PackageValidation.SubmissionId." + }, + "PackageValidationState": { + "enum": [ + "Pending", + "Succeeded", + "Failed" + ], + "type": "string" + }, + "PackageVersionEntry": { + "required": [ + "version", + "downloads", + "selected", + "lastUpdated" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The normalized version." + }, + "downloads": { + "type": "integer", + "description": "Its downloads.", + "format": "int64" + }, + "selected": { + "type": "boolean", + "description": "Whether it is the version shown." + }, + "lastUpdated": { + "type": "string", + "description": "When it was published.", + "format": "date-time" + } + }, + "description": "One row of the versions table of the package page." + }, + "PackageVulnerability": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "advisoryUrl": { + "type": "string", + "description": "The URL of the advisory describing the vulnerability.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "The severity, as the protocol numbers it: 0 low, 1 moderate, 2 high, 3 critical.", + "format": "int32" + }, + "versionRange": { + "type": "string", + "description": "The range of versions the advisory applies to.", + "nullable": true + }, + "source": { + "type": "string", + "description": "Who recorded it: null for an entry set through the metadata API or the Manage page, `osv` for one the vulnerability\r\nscanner wrote from a scan of this version. Setting the list by hand replaces the manual entries only; the next scan\r\nreplaces the scanner's.", + "nullable": true + }, + "packageKey": { + "type": "integer", + "description": "The key of the affected package version. Nullable for the same reason as on\r\nPackageDeprecation.", + "format": "int32", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + }, + "description": "A known vulnerability affecting a package version.\r\nSee: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info" + }, + "PackageVulnerabilityMetadata": { + "type": "object", + "properties": { + "advisoryUrl": { + "type": "string", + "description": "The URL of the advisory describing the vulnerability.", + "nullable": true + }, + "severity": { + "type": "string", + "description": "The severity: \"0\" low, \"1\" moderate, \"2\" high, \"3\" critical. A string in the\r\nregistration metadata, unlike the VulnerabilityInfo resource, which uses a number.", + "nullable": true + } + }, + "description": "A known vulnerability affecting a package version, as it appears in the package's\r\nregistration metadata.\r\n\r\nSee https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#vulnerabilities" + }, + "PasswordConfirmationForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The password, asked again.", + "nullable": true + } + }, + "description": "What a form that only re-asks the password posts (delete the account, turn two-factor off, reset the authenticator)." + }, + "PasswordForm": { + "required": [ + "password" + ], + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "A write that only asks the administrator's password again (approve an account, delete an organization)." + }, + "PatternPreview": { + "required": [ + "repositories", + "testPackage", + "test" + ], + "type": "object", + "properties": { + "repositories": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The NuGet repositories whose names match the repository patterns." + }, + "testPackage": { + "type": "string", + "description": "The package ID typed in the test box, if any.", + "nullable": true + }, + "test": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternTest" + } + ] + } + }, + "description": "The result of previewing repository and package patterns." + }, + "PatternTest": { + "required": [ + "matches", + "explanation" + ], + "type": "object", + "properties": { + "matches": { + "type": "boolean", + "description": "Whether the target applies to the package." + }, + "explanation": { + "type": "string", + "description": "Which pattern decided, in words." + } + }, + "description": "The outcome of PatternTest AccessPatterns.Test(IEnumerable<string>? include, IEnumerable<string>? exclude, string packageId)." + }, + "PermissionDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The target name (route).", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository names or globs, one per line.", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalName": { + "type": "string", + "description": "The user, group or organization name in the grant form.", + "nullable": true + }, + "target": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TargetDetails" + } + ] + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternPreview" + } + ] + }, + "formActions": { + "$ref": "#/components/schemas/AccessAction" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the permission target screen (`/admin/permissions/{name}`) shows: the patterns, the preview and the grants." + }, + "PermissionsViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new target name.", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository names or `*` globs, one per line.", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line; none means all.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "project": { + "type": "string", + "description": "The project that administers the target, if any.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TargetSummary" + }, + "description": "The targets." + }, + "projects": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "description": "The projects a target can belong to." + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternPreview" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the permission targets screen (`/admin/permissions`) shows: the targets and the new-target form." + }, + "PermissionTargetForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new target's name (ignored for an existing target: the route names it).", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository names or `*` globs, one per line.", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line; none means all.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "project": { + "type": "string", + "description": "For a new target: the project that administers it, or null.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "principalType": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalType" + } + ] + }, + "principalName": { + "type": "string", + "description": "For an existing target: the principal name in the grant form (kept across a preview).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (saving the patterns of an existing target).", + "nullable": true + } + }, + "description": "The fields of the permission-target form (new target, or the patterns of an existing one) and its test box." + }, + "PrincipalRemoval": { + "required": [ + "type", + "principalId", + "password" + ], + "type": "object", + "properties": { + "type": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string", + "description": "The principal's id.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Removing a principal's grant or project role." + }, + "PrincipalType": { + "enum": [ + "User", + "Group", + "Organization" + ], + "type": "string", + "description": "Who a PermissionGrant or ProjectMember names." + }, + "ProfileViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The account's name.", + "nullable": true + }, + "isOrganization": { + "type": "boolean", + "description": "Whether the account is an organization." + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDownloads" + }, + "description": "The owned packages with their downloads." + }, + "members": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The members of an organization." + }, + "isCurrentUser": { + "type": "boolean", + "description": "Whether the profile is the signed-in user's own." + }, + "avatarUrl": { + "type": "string", + "description": "The account's avatar address, or null when Gravatar is off.", + "nullable": true + } + }, + "description": "A user's or an organization's public page: the packages it owns." + }, + "ProjectCreation": { + "required": [ + "name", + "displayName" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The project's name.", + "nullable": true + }, + "displayName": { + "type": "string", + "description": "A name to show, or null.", + "nullable": true + } + }, + "description": "A new project." + }, + "ProjectDetails": { + "required": [ + "project", + "repositories", + "members", + "targets" + ], + "type": "object", + "properties": { + "project": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "repositories": { + "type": "array", + "items": { + "type": "string" + } + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectMemberInfo" + } + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TargetSummary" + } + } + }, + "description": "A project with its repositories, members and targets." + }, + "ProjectDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The project name (route).", + "nullable": true + }, + "project": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectDetails" + } + ] + }, + "assignable": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The NuGet repositories not yet in this project, for the assignment picker." + }, + "targetName": { + "type": "string", + "description": "The new target name.", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository globs of the new target, one per line (they only ever reach the project repositories).", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Include globs of the new target.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Exclude globs of the new target.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternPreview" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the project screen (`/admin/projects/{name}`) shows: repositories, members and the project targets." + }, + "ProjectMemberForm": { + "required": [ + "type", + "principalName", + "role", + "password" + ], + "type": "object", + "properties": { + "type": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalName": { + "type": "string", + "description": "The principal's name.", + "nullable": true + }, + "role": { + "$ref": "#/components/schemas/ProjectRole" + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Giving a user or group a role in a project." + }, + "ProjectMemberInfo": { + "required": [ + "principalType", + "principalId", + "principal", + "role" + ], + "type": "object", + "properties": { + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string" + }, + "principal": { + "type": "string" + }, + "role": { + "$ref": "#/components/schemas/ProjectRole" + } + }, + "description": "A member of a project." + }, + "ProjectRepositoryForm": { + "required": [ + "repository", + "password" + ], + "type": "object", + "properties": { + "repository": { + "type": "string", + "description": "The repository's name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Putting a repository in a project or taking it out." + }, + "ProjectRole": { + "enum": [ + "Viewer", + "Developer", + "Admin" + ], + "type": "string", + "description": "A member's role in a Project, applying to the project's repositories." + }, + "ProjectSummary": { + "required": [ + "key", + "name", + "displayName", + "repositoryCount", + "memberCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + }, + "displayName": { + "type": "string", + "nullable": true + }, + "repositoryCount": { + "type": "integer", + "format": "int32" + }, + "memberCount": { + "type": "integer", + "format": "int32" + } + }, + "description": "A project as the admin pages list it." + }, + "ProjectsViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new project name.", + "nullable": true + }, + "displayName": { + "type": "string", + "description": "The new project display name.", + "nullable": true + }, + "projects": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "description": "The projects the signed-in user may open." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the projects screen (`/admin/projects`) shows: the projects the user may open and the new-project form." + }, + "ProjectTargetForm": { + "required": [ + "targetName", + "repositoryPatterns", + "includePatterns", + "excludePatterns", + "testPackage" + ], + "type": "object", + "properties": { + "targetName": { + "type": "string", + "description": "The new target's name.", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository globs, one per line (they only ever reach the project's repositories).", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + } + }, + "description": "The fields of a project's new permission target and its test box." + }, + "ReadinessReport": { + "required": [ + "checkedAt", + "probes" + ], + "type": "object", + "properties": { + "checkedAt": { + "type": "string", + "description": "When it ran (UTC).", + "format": "date-time" + }, + "probes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HealthProbe" + }, + "description": "Each probe." + }, + "isReady": { + "type": "boolean", + "description": "Every probe that decides readiness answered (an informational probe, the shared store, never takes the node out of rotation)." + }, + "problem": { + "type": "string", + "description": "The failing probes (informational ones too) as one line, or null.", + "nullable": true + } + }, + "description": "The result of the readiness check." + }, + "ReauthenticateViewModel": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "providers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalProviderInfo" + }, + "description": "The linked providers to pick from when the account has several (one button each); null otherwise.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after the provider answered; only a local URL is followed.", + "nullable": true + }, + "provider": { + "type": "string", + "description": "The id of the linked provider to sign in again with; empty takes the only linked one (several: the screen offers the choice).", + "nullable": true + } + }, + "description": "The \"confirm it is you\" screen of an account without a password. A request binds ReauthenticateForm, never this type." + }, + "RecoveryCodeLoginForm": { + "required": [ + "recoveryCode" + ], + "type": "object", + "properties": { + "recoveryCode": { + "type": "string", + "description": "The recovery code.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the recovery-code form posts." + }, + "RecoveryCodeLoginViewModel": { + "required": [ + "recoveryCode" + ], + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "recoveryCode": { + "type": "string", + "description": "The recovery code.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The second step of signing in with a recovery code. A request binds RecoveryCodeLoginForm, never this type." + }, + "RegisterForm": { + "required": [ + "userName", + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The wanted user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The password again. Never echoed.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the registration form posts." + }, + "RegisterViewModel": { + "required": [ + "userName", + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "awaitingApproval": { + "type": "boolean", + "description": "Whether the account was created but waits for an administrator (`Accounts:RequireApproval`)." + }, + "confirmationSent": { + "type": "boolean", + "description": "Whether a confirmation link was mailed." + }, + "emailRequired": { + "type": "boolean", + "description": "Whether the screen asks for an email address." + }, + "session": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionModel" + } + ] + }, + "userName": { + "type": "string", + "description": "The wanted user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The password again. Never echoed.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The registration screen. A request binds RegisterForm, never this type; the passwords are always empty here." + }, + "RemoteCacheOverview": { + "required": [ + "status", + "packageCount", + "packageIdCount" + ], + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/RemoteCacheStatus" + }, + "packageCount": { + "type": "integer", + "description": "Package versions stored.", + "format": "int32" + }, + "packageIdCount": { + "type": "integer", + "description": "Distinct package ids stored.", + "format": "int32" + }, + "storedBytes": { + "type": "integer", + "description": "Bytes of the blobs stored (a Docker repository: its layers); 0 when the format does not report it.", + "format": "int64", + "default": 0 + } + }, + "description": "What a remote repository holds and remembers." + }, + "RemoteCacheStatus": { + "required": [ + "metadataEntries", + "negativeEntries", + "hits", + "misses", + "negativeHits", + "staleServed", + "failures", + "lastSuccessUtc", + "lastFailureUtc", + "failingSinceUtc", + "lastError" + ], + "type": "object", + "properties": { + "metadataEntries": { + "type": "integer", + "description": "Cached answers of the upstream (version lists and metadata), expired ones included until used or purged.", + "format": "int32" + }, + "negativeEntries": { + "type": "integer", + "description": "Remembered \"the upstream does not have it\" answers still in force.", + "format": "int32" + }, + "hits": { + "type": "integer", + "description": "Answers served from the cache.", + "format": "int64" + }, + "misses": { + "type": "integer", + "description": "Questions that went to the upstream.", + "format": "int64" + }, + "negativeHits": { + "type": "integer", + "description": "Questions answered \"not found\" from the negative cache.", + "format": "int64" + }, + "staleServed": { + "type": "integer", + "description": "Expired answers served because the upstream could not be reached.", + "format": "int64" + }, + "failures": { + "type": "integer", + "description": "Failed attempts to reach the upstream.", + "format": "int64" + }, + "lastSuccessUtc": { + "type": "string", + "description": "The last time the upstream answered.", + "format": "date-time", + "nullable": true + }, + "lastFailureUtc": { + "type": "string", + "description": "The last time it could not be reached.", + "format": "date-time", + "nullable": true + }, + "failingSinceUtc": { + "type": "string", + "description": "When the current run of failures began, or null while it answers.", + "format": "date-time", + "nullable": true + }, + "lastError": { + "type": "string", + "description": "What failed, without URLs or credentials.", + "nullable": true + } + }, + "description": "What the cache of one remote repository looks like right now (in memory, per node; resets on restart)." + }, + "RemoteConnectionResult": { + "required": [ + "success", + "message", + "statusCode", + "elapsedMilliseconds" + ], + "type": "object", + "properties": { + "success": { + "type": "boolean", + "description": "Whether the upstream answered as the configured protocol requires." + }, + "message": { + "type": "string", + "description": "What was found or what failed, without URLs or credentials." + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status, when there was an answer.", + "format": "int32", + "nullable": true + }, + "elapsedMilliseconds": { + "type": "integer", + "description": "How long the attempt took.", + "format": "int64" + } + }, + "description": "The outcome of asking an upstream whether it answers." + }, + "RemoteFormModel": { + "type": "object", + "properties": { + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "url": { + "type": "string", + "description": "The upstream URL (V3 `index.json` or V2 feed, or an npm registry's base URL).", + "nullable": true + }, + "protocol": { + "$ref": "#/components/schemas/RemoteProtocol" + }, + "username": { + "type": "string", + "description": "The HTTP Basic user name, if the upstream needs one.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The HTTP Basic password or token; blank keeps the stored one. Input only: a screen never sends it back (the use cases clear it from every model they return).", + "nullable": true + }, + "clearPassword": { + "type": "boolean", + "description": "Remove the stored password on save." + }, + "metadataTtlSeconds": { + "type": "integer", + "description": "How long the upstream's answers are reused, in seconds (0 = ask every time).", + "format": "int32" + }, + "negativeTtlSeconds": { + "type": "integer", + "description": "How long \"not found\" is remembered, in seconds (0 = ask every time).", + "format": "int32" + }, + "downloadTimeoutSeconds": { + "type": "integer", + "description": "The download timeout in seconds.", + "format": "int32" + }, + "offline": { + "type": "boolean", + "description": "Never contact the upstream." + }, + "storeLocally": { + "type": "boolean", + "description": "Keep what is fetched (off = pass-through)." + }, + "hasPassword": { + "type": "boolean", + "description": "For display: whether a password is stored." + }, + "endpointFromMirror": { + "type": "boolean", + "description": "For display: URL, protocol and timeout are fixed because `Mirror:*` sets them." + } + }, + "description": "The fields of a remote repository's upstream settings as the create and edit pages post them (prefix\r\n`Remote`). The password is never rendered back: a blank one on save keeps the stored one." + }, + "RemoteProtocol": { + "enum": [ + "V3", + "V2", + "Npm", + "Maven", + "Docker" + ], + "type": "string", + "description": "The protocol a remote repository's upstream speaks." + }, + "RemoteRepositoryDetail": { + "required": [ + "repository", + "settings", + "hasPassword", + "isMirror" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "settings": { + "$ref": "#/components/schemas/RemoteRepositorySettings" + }, + "hasPassword": { + "type": "boolean", + "description": "Whether a password is stored." + }, + "isMirror": { + "type": "boolean", + "description": "Whether it is the string Repository.MirrorName repository the default repository fetches through while `Mirror:Enabled` is set (its URL, protocol and timeout then come from `Mirror:*`)." + } + }, + "description": "A remote repository as the administration pages edit it." + }, + "RemoteRepositorySettings": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The upstream: a V3 `index.json` URL or a V2 feed URL, the base URL of an npm registry, the root of a Maven repository or the address of a Docker registry (absolute http or https).", + "nullable": true + }, + "protocol": { + "$ref": "#/components/schemas/RemoteProtocol" + }, + "username": { + "type": "string", + "description": "The user name sent with HTTP Basic to the upstream's own host, if any. An npm upstream with a password and no user name\r\ngets the password as a bearer token (npm's `_authToken`) instead. A Docker upstream gets the pair at its token service\r\n(HTTP Basic, the `docker login` flow) or, when it asks for Basic itself, at its own host; a password with no user name\r\nis sent as a ready-made bearer token to the registry's own host.", + "nullable": true + }, + "protectedPassword": { + "type": "string", + "description": "The password as stored (protected). Opaque to everything but RemoteSettingsCodec.", + "nullable": true + }, + "metadataTtlSeconds": { + "type": "integer", + "description": "How long the upstream's version list and metadata of a package are reused before it is asked again. 0 asks\r\nevery time (what the mirror always did).", + "format": "int32" + }, + "negativeTtlSeconds": { + "type": "integer", + "description": "How long \"the upstream does not have it\" (404) is remembered. 0 asks every time.", + "format": "int32" + }, + "offline": { + "type": "boolean", + "description": "Offline mode: the upstream is never contacted; only what is already stored (and cached in memory) is served." + }, + "storeLocally": { + "type": "boolean", + "description": "Whether packages fetched from the upstream are stored (database and files) so later requests, and requests\r\nwhile the upstream is down, are served locally. Off, the repository is a pass-through: metadata comes from the\r\nupstream (cached by int RemoteRepositorySettings.MetadataTtlSeconds), downloads stream through and nothing is kept (so search\r\nand the package pages stay empty)." + }, + "downloadTimeoutSeconds": { + "type": "integer", + "description": "The time before a download from the upstream times out.", + "format": "int32" + } + }, + "description": "What a RepositoryKind.Remote repository knows about its upstream: kept as JSON in\r\nstring? Repository.Settings. The password never appears in clear there: it is stored as\r\nstring? RemoteRepositorySettings.ProtectedPassword (see IRemoteCredentialProtector) and string? RemoteRepositorySettings.Password only\r\nexists in memory." + }, + "RemoveOrganizationMemberForm": { + "type": "object", + "properties": { + "organization": { + "type": "string", + "description": "The organization.", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The member to remove.", + "nullable": true + } + }, + "description": "What the \"remove a member\" (or \"leave\") form posts." + }, + "RemoveSignInProviderForm": { + "required": [ + "id", + "password" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Removing a named OpenID Connect provider saved on the Settings screen." + }, + "ReplicationBody": { + "required": [ + "form", + "password" + ], + "type": "object", + "properties": { + "form": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationForm" + } + ] + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Creating, saving or testing a replication, or any write of it that asks the password." + }, + "ReplicationConfig": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "description": "Unique, AccessNames rules.", + "nullable": true + }, + "repositoryKey": { + "type": "integer", + "description": "The local int Repository.Key: a local (not remote, not virtual) repository.", + "format": "int32" + }, + "direction": { + "$ref": "#/components/schemas/ReplicationDirection" + }, + "peerUrl": { + "type": "string", + "description": "The peer server's base address (`https://other.example/`), not a repository feed.", + "nullable": true + }, + "peerRepository": { + "type": "string", + "description": "The peer's repository (`default` or its name); it must be of the same format.", + "nullable": true + }, + "enabled": { + "type": "boolean", + "description": "A disabled configuration is never run by the schedule or a deploy; a manual run is refused." + }, + "onDeploy": { + "type": "boolean", + "description": "Push only: a deploy to the local repository starts a run (after a short quiet period)." + }, + "scheduleMinutes": { + "type": "integer", + "description": "Run every this many minutes. Null: only when started (or on deploy).", + "format": "int32", + "nullable": true + }, + "propagateDeletes": { + "type": "boolean", + "description": "What was replicated and is later deleted at the source is deleted at the target too (only items this configuration copied)." + }, + "conflict": { + "$ref": "#/components/schemas/ReplicationConflict" + }, + "scheduleStart": { + "type": "string", + "description": "When the schedule was set or the configuration enabled; the first scheduled run is due this long after it.", + "format": "date-time", + "nullable": true + }, + "lastRun": { + "type": "string", + "description": "When the last run started (the schedule counts from the later of this and DateTime? ReplicationConfig.ScheduleStart).", + "format": "date-time", + "nullable": true + }, + "lastResult": { + "type": "string", + "description": "One line about the last run.", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "modified": { + "type": "string", + "format": "date-time" + } + }, + "description": "One replication relationship: a local repository and a repository of another BaGet server, copied in one direction. Not\r\nrepository-scoped (the administrator lists configurations across repositories). Its `RepositoryKey` is a Restrict foreign key, and\r\nso is `ConfigKey` of its runs and ledger: deleting the repository deletes its configurations, runs and ledger first (code, not cascade)." + }, + "ReplicationConfigView": { + "required": [ + "config", + "repository", + "format", + "hasApiKey", + "lastRun" + ], + "type": "object", + "properties": { + "config": { + "$ref": "#/components/schemas/ReplicationConfig" + }, + "repository": { + "type": "string", + "description": "The local repository's name, or null when it no longer exists.", + "nullable": true + }, + "format": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryFormat" + } + ] + }, + "hasApiKey": { + "type": "boolean", + "description": "Whether a key is stored." + }, + "lastRun": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationRun" + } + ] + } + }, + "description": "A configuration with the names the page shows; the API key is never part of it." + }, + "ReplicationConfigViewModel": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The configuration's key (route).", + "format": "int32" + }, + "form": { + "$ref": "#/components/schemas/ReplicationForm" + }, + "view": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationConfigView" + } + ] + }, + "runs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReplicationRun" + }, + "description": "The log, newest first." + }, + "job": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationJobStatus" + } + ] + }, + "test": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationTestResult" + } + ] + }, + "localItems": { + "type": "integer", + "description": "How many items the local repository holds, or null when it could not be listed.", + "format": "int32", + "nullable": true + }, + "running": { + "type": "boolean", + "description": "Whether a run is going here (the page refreshes itself)." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The local repositories a replication can name." + }, + "resumable": { + "$ref": "#/components/schemas/ReplicationRun" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What one replication's screen (`/admin/replication/{key}`) shows." + }, + "ReplicationConflict": { + "enum": [ + "TargetWins", + "SourceWins" + ], + "type": "string", + "description": "What happens when both sides hold the same item with different content." + }, + "ReplicationDirection": { + "enum": [ + "Push", + "Pull" + ], + "type": "string", + "description": "Which way a ReplicationConfig copies." + }, + "ReplicationForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "nullable": true + }, + "repository": { + "type": "string", + "nullable": true + }, + "direction": { + "$ref": "#/components/schemas/ReplicationDirection" + }, + "peerUrl": { + "type": "string", + "nullable": true + }, + "peerRepository": { + "type": "string", + "nullable": true + }, + "apiKey": { + "type": "string", + "description": "The peer's API key (write only).", + "nullable": true + }, + "clearApiKey": { + "type": "boolean", + "description": "Forget the stored key." + }, + "enabled": { + "type": "boolean" + }, + "onDeploy": { + "type": "boolean" + }, + "scheduleMinutes": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "propagateDeletes": { + "type": "boolean" + }, + "conflict": { + "$ref": "#/components/schemas/ReplicationConflict" + } + }, + "description": "What the replication form posts (`Form.*`): a ReplicationConfig as a person types it. The peer's API key is write\r\nonly: it is never filled back into a page; an empty field keeps the stored key." + }, + "ReplicationJobStatus": { + "type": "object", + "properties": { + "configKey": { + "type": "integer", + "format": "int32" + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "running": { + "type": "boolean", + "description": "True while the run is going." + }, + "refusal": { + "type": "string", + "description": "Why the job did not even begin a run (read-only server, disabled configuration, lease held elsewhere), or null.", + "nullable": true + } + }, + "description": "What the page knows of a replication started since the server began (in memory); the log table is the durable record." + }, + "ReplicationRun": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "configKey": { + "type": "integer", + "description": "The int ReplicationConfig.Key.", + "format": "int32" + }, + "status": { + "$ref": "#/components/schemas/ReplicationRunStatus" + }, + "trigger": { + "type": "string", + "description": "`manual`, `resume`, `schedule` or `deploy`.", + "nullable": true + }, + "actor": { + "type": "string", + "description": "The administrator, or `scheduler`.", + "nullable": true + }, + "resumedFrom": { + "type": "integer", + "description": "The interrupted or failed run this one continues, when started with Resume.", + "format": "int32", + "nullable": true + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "examined": { + "type": "integer", + "description": "Items the plan looked at (both sides listed).", + "format": "int32" + }, + "transferred": { + "type": "integer", + "description": "Items copied to the target.", + "format": "int32" + }, + "skipped": { + "type": "integer", + "description": "Items the target already had.", + "format": "int32" + }, + "deleted": { + "type": "integer", + "description": "Items deleted at the target because they were deleted at the source.", + "format": "int32" + }, + "conflicts": { + "type": "integer", + "description": "Items held differently on both sides that were left alone (target wins) or replaced (source wins).", + "format": "int32" + }, + "failures": { + "type": "integer", + "format": "int32" + }, + "bytes": { + "type": "integer", + "description": "Bytes of artifact content sent or received.", + "format": "int64" + }, + "error": { + "type": "string", + "description": "Why the run failed as a whole, or null.", + "nullable": true + }, + "detail": { + "type": "string", + "description": "The first failures and conflicts, one per line.", + "nullable": true + } + }, + "description": "One run of a configuration: the replication log." + }, + "ReplicationRunStatus": { + "enum": [ + "Running", + "Succeeded", + "Failed", + "Interrupted" + ], + "type": "string", + "description": "How a ReplicationRun ended." + }, + "ReplicationTestResult": { + "required": [ + "ok", + "message", + "elapsedMilliseconds", + "peerFormat", + "peerItems" + ], + "type": "object", + "properties": { + "ok": { + "type": "boolean", + "description": "Whether the peer answered as a BaGet server with this repository." + }, + "message": { + "type": "string", + "description": "A sentence for the administrator (never the key)." + }, + "elapsedMilliseconds": { + "type": "integer", + "description": "How long it took.", + "format": "int64" + }, + "peerFormat": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryFormat" + } + ] + }, + "peerItems": { + "type": "integer", + "description": "How many items it holds, when it answered.", + "format": "int32", + "nullable": true + } + }, + "description": "What Task<ReplicationTestResult> IReplicationAdministration.TestAsync(ReplicationInput input, CancellationToken cancellationToken) found." + }, + "ReplicationViewModel": { + "type": "object", + "properties": { + "form": { + "$ref": "#/components/schemas/ReplicationForm" + }, + "replications": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReplicationConfigView" + }, + "description": "Every replication." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The local repositories a replication can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the replications screen (`/admin/replication`) shows: every replication and the form that creates one." + }, + "ReportAbuseForm": { + "required": [ + "reason", + "details" + ], + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "One of string[] AbuseReport.Reasons.", + "nullable": true + }, + "details": { + "maxLength": 4000, + "minLength": 0, + "type": "string", + "description": "What the reporter saw.", + "nullable": true + }, + "reporterEmail": { + "maxLength": 256, + "minLength": 0, + "type": "string", + "description": "The address of the reporter, optional.", + "nullable": true + } + }, + "description": "What the reporter fills in. The field names (Reason, Details, ReporterEmail) are the contract of the form and of the JSON body." + }, + "ReportAbuseScreen": { + "required": [ + "id", + "version", + "canReport", + "submitted", + "form" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The package version.", + "nullable": true + }, + "canReport": { + "type": "boolean", + "description": "Reports are kept in the database, which Azure Table storage cannot do." + }, + "submitted": { + "type": "boolean", + "description": "True once the report was recorded." + }, + "form": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "description": "The report-abuse screen: the package it is about, what was typed, and whether the report was recorded." + }, + "RepositoriesViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name for the repository to create.", + "nullable": true + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositorySummary" + }, + "description": "The repositories." + }, + "canCreate": { + "type": "boolean", + "description": "Whether the database can hold more than the default repository." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "description": "Why the last action was refused.", + "nullable": true + }, + "format": { + "type": "string", + "description": "The format to keep selected after a refused creation.", + "nullable": true + }, + "filterFormat": { + "type": "string", + "description": "The format the list is narrowed to (`?format=`), or null.", + "nullable": true + }, + "filterKind": { + "type": "string", + "description": "The kind the list is narrowed to (`?kind=`), or null.", + "nullable": true + }, + "filterName": { + "type": "string", + "description": "The name fragment the list is narrowed to (`?q=`), or null.", + "nullable": true + }, + "allFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "Every format this server knows, for the list filter." + }, + "remoteFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "The formats a remote repository can be created for." + }, + "virtualFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "The formats a virtual repository can be created for." + }, + "otherFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "The formats other than NuGet that can be created here, with their form fields." + }, + "deployable": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The virtual repositories that have a deploy repository, so take uploads (a remote one takes none)." + }, + "feeds": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The feed address of each repository, by repository name." + }, + "baseUrls": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The base address of each repository (where its format's routes start, ends with a slash), by repository name." + }, + "links": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatLink" + } + }, + "description": "The links its format contributes for each repository (browse, upload...), without the upload link where it takes none, by repository name." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the repositories screen (`/admin/repositories`) shows: the repositories with their feed addresses, the list filter and\r\nthe create forms. The posted fields of the create forms (string? RepositoriesViewModel.Name, RemoteFormModel RepositoriesViewModel.Remote) live here too, so a refused\r\ncreation shows again what was typed (the typed upstream password excepted: it is never sent back)." + }, + "RepositoryAccessRow": { + "required": [ + "repository", + "explanation" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "explanation": { + "$ref": "#/components/schemas/AccessExplanation" + } + }, + "description": "One repository with what a user may do there and the grants behind it (the account and user pages)." + }, + "RepositoryAccessSummary": { + "required": [ + "repository", + "anonymousRead", + "project", + "modelAvailable", + "holders" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "anonymousRead": { + "type": "boolean", + "description": "The repository's anonymous-read switch." + }, + "project": { + "type": "string", + "description": "The name of the project the repository belongs to, if any.", + "nullable": true + }, + "modelAvailable": { + "type": "boolean", + "description": "False where there is no access model (Azure Table): everyone reads, any authenticated\r\n caller writes, subject to ownership." + }, + "holders": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccessReason" + }, + "description": "Every grant and project role that applies to the repository." + } + }, + "description": "Who holds what in one repository (Task<RepositoryAccessSummary> IAccessEvaluator.DescribeAsync(RepositoryInfo repository, CancellationToken cancellationToken))." + }, + "RepositoryCreateForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the repository to create.", + "nullable": true + }, + "format": { + "type": "string", + "description": "The format (`Npm`, `Maven`, `Docker`...); blank is NuGet where a format may be omitted.", + "nullable": true + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read the repository. Null: the default (a local or virtual repository is readable by anyone; a remote\r\none only when it has no credentials).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (creating a remote repository asks for it).", + "nullable": true + }, + "fields": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The format's own create fields (string FormatCreateField.Name to value) of a local repository of a format other than NuGet.", + "nullable": true + } + }, + "description": "The body of the create forms of the repositories screen (`POST /api/ui/admin/repositories` and its `create/...` handlers). Which fields\r\na handler reads is stated on its use case method; the others are ignored." + }, + "RepositoryDeleteViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The repository's name (route).", + "nullable": true + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositorySummary" + } + ] + }, + "referencedBy": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The virtual repositories that list this repository as a member (the deletion is refused while there are any)." + }, + "error": { + "type": "string", + "description": "Why the deletion was refused.", + "nullable": true + } + }, + "description": "What the delete-repository screen (`/admin/repositories/{name}/delete`) shows." + }, + "RepositoryEditRequest": { + "type": "object", + "properties": { + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read the repository." + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "previewPackageId": { + "type": "string", + "description": "The package id to resolve in the preview.", + "nullable": true + }, + "previewVersion": { + "type": "string", + "description": "The package version to resolve in the preview.", + "nullable": true + }, + "packageId": { + "type": "string", + "description": "The package id to purge from the cache.", + "nullable": true + }, + "packageVersion": { + "type": "string", + "description": "The version to purge (blank = every version).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (saving, testing and purging a remote repository ask for it).", + "nullable": true + }, + "member": { + "type": "string", + "description": "The member to add, remove or move.", + "nullable": true + }, + "direction": { + "type": "string", + "description": "`up` or `down`.", + "nullable": true + }, + "deploy": { + "type": "string", + "description": "The member that receives uploads (blank: none).", + "nullable": true + }, + "policy": { + "type": "string", + "description": "The versions a Maven repository accepts (`Releases`, `Snapshots`, `Both`).", + "nullable": true + }, + "redeploy": { + "type": "string", + "description": "Whether a Maven release may be redeployed (`Yes`/`No`).", + "nullable": true + }, + "snapshotBuilds": { + "type": "string", + "description": "How many snapshot builds a Maven repository keeps.", + "nullable": true + } + }, + "description": "The body of every action of the repository screen (`/api/ui/admin/repositories/{name}/...`), the JSON twin of what the page's forms post. Which fields\r\nan action reads is stated on its use case method; the others are ignored." + }, + "RepositoryEditViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The repository's name (route).", + "nullable": true + }, + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read the repository." + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositorySummary" + } + ] + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "remoteDetail": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteRepositoryDetail" + } + ] + }, + "mavenSettings": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenRepositorySettings" + } + ] + }, + "cache": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteCacheOverview" + } + ] + }, + "virtualDetail": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/VirtualRepositoryDetail" + } + ] + }, + "memberCandidates": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories that can still be added to a virtual repository." + }, + "referencedBy": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The virtual repositories that list this repository as a member." + }, + "previewPackageId": { + "type": "string", + "description": "The package id to resolve in the preview.", + "nullable": true + }, + "previewVersion": { + "type": "string", + "description": "The package version to resolve in the preview.", + "nullable": true + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResolutionPreview" + } + ] + }, + "testResult": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteConnectionResult" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "description": "Why the last action was refused.", + "nullable": true + }, + "packageId": { + "type": "string", + "description": "The package id to purge from the cache.", + "nullable": true + }, + "packageVersion": { + "type": "string", + "description": "The version to purge (blank = every version).", + "nullable": true + }, + "access": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryAccessSummary" + } + ] + }, + "browseScreen": { + "$ref": "#/components/schemas/ScreenRef" + }, + "feedUrl": { + "type": "string", + "description": "The repository's feed address." + }, + "mirrorRepository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteRepositoryDetail" + } + ] + }, + "mirrorActive": { + "type": "boolean", + "description": "Whether `Mirror:Enabled` makes the default repository fetch through RemoteRepositoryDetail? RepositoryEditViewModel.MirrorRepository." + }, + "packageWord": { + "type": "string", + "description": "The name of what a package is called in this repository's format (shown in the labels).", + "nullable": true + }, + "versionWord": { + "type": "string", + "description": "What the \"version\" of a package is called in this repository's format (a Docker image has a tag or a digest).", + "nullable": true + }, + "packageLabel": { + "type": "string", + "description": "The label of the field that names a package (a Docker image is an image name).", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the repository screen (`/admin/repositories/{name}`) shows: the repository, its access summary and, by kind, its\r\nupstream and cache (remote), members and preview (virtual) or Maven settings. The posted fields (anonymous read, upstream, preview\r\nand purge inputs) live here too, so a refused action shows again what was typed." + }, + "RepositoryFormat": { + "enum": [ + "NuGet", + "Npm", + "Maven", + "Docker" + ], + "type": "string", + "description": "The package format a Repository serves. Stored as its name, so a value may be appended\r\nbut never renumbered or renamed." + }, + "RepositoryFormatChoice": { + "required": [ + "format", + "displayName", + "createFields" + ], + "type": "object", + "properties": { + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "displayName": { + "type": "string", + "description": "Its name for people (`npm`, `Maven`)." + }, + "createFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatCreateField" + }, + "description": "What the administrator fills in to create a local repository of it, besides the name." + } + }, + "description": "A package format a repository can be created for, with the extra fields its create form asks (the JSON form of an IFormatModule)." + }, + "RepositoryInfo": { + "required": [ + "key", + "name", + "format", + "kind" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The int Repository.Key.", + "format": "int32" + }, + "name": { + "type": "string", + "description": "The string? Repository.Name." + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "kind": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "isDefault": { + "type": "boolean", + "description": "Whether this is the string Repository.DefaultName repository." + }, + "pathPrefix": { + "type": "string", + "description": "The path in front of this repository's routes, feeds and pages, without a leading slash: nothing for the\r\ndefault repository (served at `/`), else `r/{name}/`.", + "nullable": true + } + }, + "description": "What a request, job or command needs to know about the repository it works in: immutable, and small enough to\r\ncopy around." + }, + "RepositoryKind": { + "enum": [ + "Local", + "Remote", + "Virtual" + ], + "type": "string", + "description": "How a Repository gets its content. Stored as its name." + }, + "RepositoryPackages": { + "required": [ + "repository", + "packages" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnedPackage" + } + } + }, + "description": "The packages the user owns in one repository." + }, + "RepositorySummary": { + "required": [ + "key", + "name", + "format", + "kind", + "anonymousRead", + "created", + "packageCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The int Repository.Key.", + "format": "int32" + }, + "name": { + "type": "string", + "description": "The string? Repository.Name." + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "kind": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read it." + }, + "created": { + "type": "string", + "description": "When the repository was created (UTC).", + "format": "date-time" + }, + "packageCount": { + "type": "integer", + "description": "How many package versions it holds.", + "format": "int32" + }, + "isDefault": { + "type": "boolean", + "description": "Whether this is the string Repository.DefaultName repository, which can be neither renamed nor deleted." + } + }, + "description": "A repository as the administration pages list it." + }, + "ResetPasswordForm": { + "required": [ + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "userId": { + "type": "string", + "description": "The account named by the link.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The encoded reset token of the link.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The new password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The new password again. Never echoed.", + "nullable": true + } + }, + "description": "What the new-password form behind a reset link posts." + }, + "ResetPasswordViewModel": { + "required": [ + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "userId": { + "type": "string", + "description": "The account named by the link.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The encoded reset token of the link.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The new password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The new password again. Never echoed.", + "nullable": true + } + }, + "description": "The screen behind the link of a password reset email. A request binds ResetPasswordForm, never this type." + }, + "ResolutionOutcome": { + "enum": [ + "Stored", + "WouldFetch", + "NotFound", + "Unavailable", + "NotAsked", + "Offline" + ], + "type": "string", + "description": "What asking one member about a package version found." + }, + "ResolutionPreview": { + "required": [ + "packageId", + "version", + "steps", + "answers" + ], + "type": "object", + "properties": { + "packageId": { + "type": "string", + "description": "The package id asked about (`group:artifact` for Maven)." + }, + "version": { + "type": "string", + "description": "The version asked about, as written for the format (a NuGet or npm version in its normalized form; a Maven version as typed)." + }, + "steps": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ResolutionStep" + }, + "description": "The effective members in resolution order and what each found." + }, + "answers": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + } + }, + "description": "Where a package version would come from, member by member." + }, + "ResolutionStep": { + "required": [ + "member", + "outcome" + ], + "type": "object", + "properties": { + "member": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "outcome": { + "$ref": "#/components/schemas/ResolutionOutcome" + } + }, + "description": "One member's part in ResolutionPreview." + }, + "RetentionHoldForm": { + "required": [ + "holdRepository", + "holdName", + "holdVersion", + "reason" + ], + "type": "object", + "properties": { + "holdRepository": { + "type": "string", + "description": "The repository of the hold.", + "nullable": true + }, + "holdName": { + "type": "string", + "description": "The artifact name.", + "nullable": true + }, + "holdVersion": { + "type": "string", + "description": "The version; empty for every version.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "Why (a case number, a ticket).", + "nullable": true + } + }, + "description": "Placing a legal hold." + }, + "RetentionHoldRemoval": { + "required": [ + "key", + "password" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The hold's number.", + "format": "int32" + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Lifting a legal hold." + }, + "RetentionHoldsViewModel": { + "type": "object", + "properties": { + "repository": { + "type": "string", + "description": "Only the holds of this repository (query).", + "nullable": true + }, + "holdRepository": { + "type": "string", + "description": "The repository of the new hold.", + "nullable": true + }, + "holdName": { + "type": "string", + "description": "The artifact name of the new hold.", + "nullable": true + }, + "holdVersion": { + "type": "string", + "description": "The version of the new hold; empty for every version.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "Why (a case number, a ticket).", + "nullable": true + }, + "holds": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionHoldView" + }, + "description": "The holds." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories a hold can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the legal holds screen (`/admin/retention/holds`) shows." + }, + "RetentionHoldView": { + "required": [ + "key", + "repositoryKey", + "repository", + "name", + "version", + "reason", + "createdBy", + "created" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "format": "int32" + }, + "repository": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "reason": { + "type": "string", + "nullable": true + }, + "createdBy": { + "type": "string", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + } + }, + "description": "A legal hold with its repository's name." + }, + "RetentionJobState": { + "enum": [ + "Running", + "Succeeded", + "Failed" + ], + "type": "string" + }, + "RetentionJobStatus": { + "type": "object", + "properties": { + "policyKey": { + "type": "integer", + "format": "int32" + }, + "dryRun": { + "type": "boolean" + }, + "state": { + "$ref": "#/components/schemas/RetentionJobState" + }, + "actor": { + "type": "string", + "description": "The administrator, or `scheduler`.", + "nullable": true + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "report": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionReport" + } + ] + }, + "error": { + "type": "string", + "description": "Why the run failed as a whole, or null.", + "nullable": true + } + }, + "description": "The last run of a policy since the server started (in memory)." + }, + "RetentionOutcome": { + "enum": [ + "Planned", + "Deleted", + "Held", + "Failed" + ], + "type": "string", + "description": "What happened (or, in a dry run, would happen) to one selected version." + }, + "RetentionPolicy": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "description": "Unique, AccessNames rules.", + "nullable": true + }, + "repositoryKey": { + "type": "integer", + "description": "The int Repository.Key the policy applies to, or null when it applies to a project.", + "format": "int32", + "nullable": true + }, + "projectKey": { + "type": "integer", + "description": "The int Project.Key: the policy applies to every repository of the project. Exactly one of the two keys is set.", + "format": "int32", + "nullable": true + }, + "enabled": { + "type": "boolean", + "description": "A disabled policy is never run by the schedule and refuses a manual run (a dry run still reports)." + }, + "namePatterns": { + "type": "string", + "description": "Globs (AccessPatterns, one per line) naming the artifacts the policy looks at (package ids, npm names, Maven\r\n`group:artifact`, image names); empty means every artifact.", + "nullable": true + }, + "keepLast": { + "type": "integer", + "description": "Keep this many newest versions of each artifact (by publish time); older ones are selected. Null: rule off.", + "format": "int32", + "nullable": true + }, + "olderThanDays": { + "type": "integer", + "description": "Select versions published more than this many days ago. Null: rule off.", + "format": "int32", + "nullable": true + }, + "unusedDays": { + "type": "integer", + "description": "Select versions not downloaded for this many days (the publish time counts when never downloaded). Null: rule off.", + "format": "int32", + "nullable": true + }, + "prereleaseOnly": { + "type": "boolean", + "description": "The age and count rules look at prerelease versions (NuGet pre-release, npm prerelease, Maven snapshot) only." + }, + "cacheLimitBytes": { + "type": "integer", + "description": "Remote repositories only: when what the repository cached is larger than this many bytes, the least recently used versions are\r\nselected until it fits. Null: rule off.", + "format": "int64", + "nullable": true + }, + "untaggedAfterDays": { + "type": "integer", + "description": "Docker only: select manifests no tag, index or referrer relationship points at that were pushed more than this many days ago.\r\nNull: rule off.", + "format": "int32", + "nullable": true + }, + "collectGarbage": { + "type": "boolean", + "description": "Docker only: run the garbage collection (IOciGarbageCollector) after the rules, to free the blobs." + }, + "scheduleHours": { + "type": "integer", + "description": "Run every this many hours (a real run, by the background worker). Null: only when an administrator starts it.", + "format": "int32", + "nullable": true + }, + "scheduleStart": { + "type": "string", + "description": "When the schedule was set or the policy enabled; the first scheduled run is due this long after it.", + "format": "date-time", + "nullable": true + }, + "lastRun": { + "type": "string", + "description": "When the last real run started (the schedule counts from the later of this and DateTime? RetentionPolicy.ScheduleStart).", + "format": "date-time", + "nullable": true + }, + "lastResult": { + "type": "string", + "description": "One line about the last real run.", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "unusedSince": { + "type": "string", + "description": "Since when the unused rule has been watching the policy's scope (set when the rule is enabled or changed, or the repository,\r\nproject or name patterns change; null on rows that predate it, which fall back to DateTime RetentionPolicy.Created). A version never\r\ndownloaded counts as unused from the later of its publication and this time: downloads are recorded only while watched.", + "format": "date-time", + "nullable": true + }, + "modified": { + "type": "string", + "format": "date-time" + } + }, + "description": "A retention policy: which stored versions of one repository (or of every repository of a project) are deleted, and when.\r\nA version is deleted when any enabled rule selects it and no RetentionHold covers it. Not repository-scoped:\r\nthe administrator lists policies across repositories. `RepositoryKey` and `ProjectKey` are optional Restrict foreign keys;\r\ndeleting a repository or a project deletes its policies first." + }, + "RetentionPolicyBody": { + "required": [ + "form", + "password" + ], + "type": "object", + "properties": { + "form": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyForm" + } + ] + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Creating or saving a retention policy, or any write of it that asks the password." + }, + "RetentionPolicyForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "nullable": true + }, + "scopeKind": { + "type": "string", + "description": "`repository` or `project`.", + "nullable": true + }, + "scopeName": { + "type": "string", + "description": "The repository or project name.", + "nullable": true + }, + "enabled": { + "type": "boolean" + }, + "namePatterns": { + "type": "string", + "nullable": true + }, + "keepLast": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "olderThanDays": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "unusedDays": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "prereleaseOnly": { + "type": "boolean" + }, + "cacheLimitMb": { + "type": "integer", + "description": "The remote cache limit in MiB.", + "format": "int64", + "nullable": true + }, + "untaggedAfterDays": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "collectGarbage": { + "type": "boolean" + }, + "scheduleHours": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What the policy form posts (`Form.*`): the rules of a RetentionPolicy in the units a person types\r\n(the cache limit in MiB). RetentionPolicyInput RetentionPolicyForm.ToInput(int key) turns it into the administration's input." + }, + "RetentionPolicyView": { + "required": [ + "policy", + "repository", + "project", + "targets" + ], + "type": "object", + "properties": { + "policy": { + "$ref": "#/components/schemas/RetentionPolicy" + }, + "repository": { + "type": "string", + "description": "The repository name, when it applies to one.", + "nullable": true + }, + "project": { + "type": "string", + "description": "The project name, when it applies to a project.", + "nullable": true + }, + "targets": { + "type": "integer", + "description": "How many repositories it currently applies to.", + "format": "int32" + } + }, + "description": "A policy with the name of what it applies to." + }, + "RetentionPolicyViewModel": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The policy's key (route).", + "format": "int32" + }, + "form": { + "$ref": "#/components/schemas/RetentionPolicyForm" + }, + "view": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyView" + } + ] + }, + "status": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionJobStatus" + } + ] + }, + "running": { + "type": "boolean", + "description": "Whether a run is in progress (the page refreshes itself)." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories a policy can name." + }, + "projectNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of the projects a policy can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What one retention policy's screen (`/admin/retention/{key}`) shows." + }, + "RetentionReport": { + "type": "object", + "properties": { + "policyKey": { + "type": "integer", + "format": "int32" + }, + "policyName": { + "type": "string" + }, + "dryRun": { + "type": "boolean", + "description": "Whether nothing was changed." + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionRepositoryReport" + }, + "nullable": true + }, + "selected": { + "type": "integer", + "format": "int32" + }, + "deleted": { + "type": "integer", + "format": "int32" + }, + "held": { + "type": "integer", + "format": "int32" + }, + "failed": { + "type": "integer", + "format": "int32" + }, + "bytes": { + "type": "integer", + "format": "int64" + }, + "summary": { + "type": "string", + "description": "One line for the policy page, the job status and the audit log.", + "nullable": true + } + }, + "description": "The result of running (or dry-running) a policy over its repositories." + }, + "RetentionReportItem": { + "required": [ + "repository", + "name", + "version", + "published", + "lastDownloaded", + "size", + "rules", + "outcome", + "error" + ], + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "published": { + "type": "string", + "format": "date-time" + }, + "lastDownloaded": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "size": { + "type": "integer", + "format": "int64", + "nullable": true + }, + "rules": { + "type": "string" + }, + "outcome": { + "$ref": "#/components/schemas/RetentionOutcome" + }, + "error": { + "type": "string", + "nullable": true + } + }, + "description": "One version in a report." + }, + "RetentionRepositoryReport": { + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "examined": { + "type": "integer", + "description": "Versions looked at (matching the policy's name patterns).", + "format": "int32" + }, + "selected": { + "type": "integer", + "description": "Versions selected by a rule and not held (dry run: to be deleted).", + "format": "int32" + }, + "deleted": { + "type": "integer", + "description": "Versions deleted (always 0 in a dry run).", + "format": "int32" + }, + "held": { + "type": "integer", + "description": "Versions a rule selected that a legal hold kept.", + "format": "int32" + }, + "failed": { + "type": "integer", + "description": "Versions whose deletion failed.", + "format": "int32" + }, + "bytes": { + "type": "integer", + "description": "Bytes of the deleted versions (dry run: of the selected ones), as far as known.", + "format": "int64" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionReportItem" + }, + "nullable": true + }, + "itemsTruncated": { + "type": "boolean" + }, + "notes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Rules that did not apply, and similar remarks.", + "nullable": true + }, + "garbageCollection": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciGcReport" + } + ] + }, + "error": { + "type": "string", + "description": "Why the repository could not be processed, or null.", + "nullable": true + } + }, + "description": "The part of a RetentionReport that concerns one repository." + }, + "RetentionViewModel": { + "type": "object", + "properties": { + "form": { + "$ref": "#/components/schemas/RetentionPolicyForm" + }, + "policies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionPolicyView" + }, + "description": "Every policy." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories a policy can name." + }, + "projectNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of the projects a policy can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the retention policies screen (`/admin/retention`) shows: every policy and the form that creates one." + }, + "ScanArtifactForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image).", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version (Docker: the manifest digest).", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where the link back goes (a local address only).", + "nullable": true + } + }, + "description": "The body of the scan twin's POST: the artifact and version to scan, and where the link back goes." + }, + "ScanEngineStatus": { + "required": [ + "available", + "engine", + "reason" + ], + "type": "object", + "properties": { + "available": { + "type": "boolean", + "description": "Whether a scan can run." + }, + "engine": { + "type": "string", + "description": "What scans the repository's artifacts (`OSV.dev`, `OSV offline copy`, `Trivy`), or null.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "Why it cannot, or null. Safe to show.", + "nullable": true + } + }, + "description": "Whether the repository of the request can be scanned now, and by what." + }, + "ScanFinding": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "resultKey": { + "type": "integer", + "description": "The int ScanResult.Key. Required; deleting the result deletes its findings.", + "format": "int32" + }, + "vulnerabilityId": { + "type": "string", + "description": "The advisory id (`GHSA-…`, `CVE-…`), as the source names it.", + "nullable": true + }, + "component": { + "type": "string", + "description": "The component that is vulnerable: the artifact itself or one of its dependencies (package, OS package…).", + "nullable": true + }, + "componentVersion": { + "type": "string", + "description": "The version of string? ScanFinding.Component.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "0 low, 1 moderate, 2 high, 3 critical (the numbering of NuGet's vulnerability resource).", + "format": "int32" + }, + "summary": { + "type": "string", + "description": "A one-line description from the source, or null.", + "nullable": true + }, + "advisoryUrl": { + "type": "string", + "description": "Where the advisory is described (an absolute http(s) URL).", + "nullable": true + }, + "fixedVersion": { + "type": "string", + "description": "The first version that fixes it, when the source says.", + "nullable": true + } + }, + "description": "One vulnerability a scan found in an artifact or one of its components." + }, + "ScanningProjectRow": { + "required": [ + "project", + "hasPolicy" + ], + "type": "object", + "properties": { + "project": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "hasPolicy": { + "type": "boolean", + "description": "Whether it has a scanning policy of its own." + } + }, + "description": "One project of the scanning overview." + }, + "ScanningRepositoryRow": { + "required": [ + "repository", + "summary", + "policy" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "summary": { + "$ref": "#/components/schemas/ScanSummary" + }, + "policy": { + "$ref": "#/components/schemas/EffectiveScanPolicy" + } + }, + "description": "One repository of the scanning overview." + }, + "ScanningSettingsView": { + "required": [ + "enabled", + "scanOnDeploy", + "osvUrl", + "osvOfflinePath", + "rescanInterval" + ], + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether artifacts are scanned." + }, + "scanOnDeploy": { + "type": "boolean", + "description": "Whether a stored version is queued for a scan at once." + }, + "osvUrl": { + "type": "string", + "description": "The OSV API root." + }, + "osvOfflinePath": { + "type": "string", + "description": "The offline copy of the OSV data, or null.", + "nullable": true + }, + "rescanInterval": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": "string", + "description": "The age after which an artifact is scanned again (zero or negative: never)." + } + }, + "description": "The scanning options the overview shows." + }, + "ScanningViewModel": { + "type": "object", + "properties": { + "settings": { + "$ref": "#/components/schemas/ScanningSettingsView" + }, + "trivyConfigured": { + "type": "boolean", + "description": "Whether Trivy is configured (container images are scanned)." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanningRepositoryRow" + }, + "description": "The repositories that can hold artifacts (virtual ones hold none)." + }, + "projects": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanningProjectRow" + }, + "description": "The projects." + } + }, + "description": "What the vulnerability scanning overview (`/admin/scanning`) shows." + }, + "ScanPolicy": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The repository this policy is for, or null for a project policy.", + "format": "int32", + "nullable": true + }, + "projectKey": { + "type": "integer", + "description": "The project this policy is for, or null for a repository policy.", + "format": "int32", + "nullable": true + }, + "warnSeverity": { + "type": "integer", + "description": "Findings at or above this severity (0..3) are shown as a warning. Null: no warning.", + "format": "int32", + "nullable": true + }, + "blockDownloadSeverity": { + "type": "integer", + "description": "A version with a finding at or above this severity cannot be downloaded (403 with the reason). Null: never.", + "format": "int32", + "nullable": true + }, + "blockDeploySeverity": { + "type": "integer", + "description": "A deploy whose artifact or declared dependencies have a finding at or above this severity is refused (403). Null: never.", + "format": "int32", + "nullable": true + }, + "blockUnscanned": { + "type": "boolean", + "description": "Whether a version that has not been scanned (yet, or at all) cannot be downloaded." + }, + "modified": { + "type": "string", + "description": "When the policy was last saved (UTC).", + "format": "date-time" + }, + "modifiedBy": { + "type": "string", + "description": "The administrator who saved it, or null.", + "nullable": true + } + }, + "description": "What a repository (or a project's repositories) does about findings: a threshold severity per action, or none (null) for\r\nthe action. A repository's own policy wins over its project's. Exactly one of int? ScanPolicy.RepositoryKey and\r\nint? ScanPolicy.ProjectKey is set." + }, + "ScanPolicyBody": { + "required": [ + "warn", + "blockDownload", + "blockDeploy", + "blockUnscanned", + "password" + ], + "type": "object", + "properties": { + "warn": { + "type": "string", + "description": "Warn from this severity (0 to 3, or empty).", + "nullable": true + }, + "blockDownload": { + "type": "string", + "description": "Refuse downloads from this severity.", + "nullable": true + }, + "blockDeploy": { + "type": "string", + "description": "Refuse deploys from this severity.", + "nullable": true + }, + "blockUnscanned": { + "type": "boolean", + "description": "Refuse downloads of versions that were not scanned." + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Saving the scanning policy of a repository or project (empty values remove it)." + }, + "ScanPolicyScope": { + "enum": [ + "Repository", + "Project" + ], + "type": "string" + }, + "ScanPolicyValues": { + "required": [ + "warnSeverity", + "blockDownloadSeverity", + "blockDeploySeverity", + "blockUnscanned" + ], + "type": "object", + "properties": { + "warnSeverity": { + "type": "integer", + "description": "Show a warning from this severity (0 low … 3 critical).", + "format": "int32", + "nullable": true + }, + "blockDownloadSeverity": { + "type": "integer", + "description": "Refuse downloads from this severity.", + "format": "int32", + "nullable": true + }, + "blockDeploySeverity": { + "type": "integer", + "description": "Refuse deploys from this severity.", + "format": "int32", + "nullable": true + }, + "blockUnscanned": { + "type": "boolean", + "description": "Refuse downloads of versions that were not scanned." + }, + "isEmpty": { + "type": "boolean", + "description": "Whether nothing is enabled." + } + }, + "description": "The thresholds of a policy; null disables the action." + }, + "ScanProjectViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The project's name (route).", + "nullable": true + }, + "project": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectDetails" + } + ] + }, + "own": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicy" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the scanning policy of a project (`/admin/scanning/projects/{name}`) shows." + }, + "ScanRepositoryViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The repository's name (route).", + "nullable": true + }, + "minSeverity": { + "type": "integer", + "description": "The lowest severity listed (0 low ... 3 critical).", + "format": "int32" + }, + "pageNumber": { + "type": "integer", + "description": "The page of the list, from 1.", + "format": "int32" + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + }, + "summary": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanSummary" + } + ] + }, + "effective": { + "$ref": "#/components/schemas/EffectiveScanPolicy" + }, + "own": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicy" + } + ] + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanResult" + }, + "description": "The versions with findings on this page." + }, + "hasMore": { + "type": "boolean", + "description": "Whether there is another page." + }, + "job": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AdminJobStatus" + } + ] + }, + "packageLinks": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ScreenLink" + }, + "description": "The package screen of each finding's version (by int ScanResult.Key), when its format has one." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the scanning dashboard of one repository (`/admin/scanning/{name}`) shows." + }, + "ScanResult": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "name": { + "type": "string", + "description": "The artifact name (see the class remarks). At most `ScanLimits.NameLength` characters.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The artifact version. At most `ScanLimits.VersionLength` characters.", + "nullable": true + }, + "scanner": { + "type": "string", + "description": "The scanner that produced the findings: `osv` or `trivy`.", + "nullable": true + }, + "scannedAt": { + "type": "string", + "description": "When the last scan succeeded (UTC); null when none ever did (the artifact counts as unscanned).", + "format": "date-time", + "nullable": true + }, + "attempted": { + "type": "string", + "description": "When a scan was last attempted (UTC).", + "format": "date-time" + }, + "error": { + "type": "string", + "description": "The scrubbed reason the last attempt failed, or null. The findings of the last success stay while this is set.", + "nullable": true + }, + "highest": { + "type": "integer", + "description": "The highest severity among List<ScanFinding>? ScanResult.Findings (0 low … 3 critical), or -1 when there are none.", + "format": "int32" + }, + "findingCount": { + "type": "integer", + "description": "How many findings the last success recorded.", + "format": "int32" + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanFinding" + }, + "nullable": true + } + }, + "description": "What the last scans of one artifact version found, in one repository (table `ScanResults`). The artifact is named the way\r\nits format names it: NuGet package id (as stored), npm package name, Maven `group:artifact`, Docker image name; the\r\nversion is the package version, npm version, Maven version or the Docker manifest digest. A row exists once a scan was\r\nattempted; there is no foreign key to the artifact (it may be deleted, and each format keeps its own tables), so stale rows are\r\ndropped by the next sweep." + }, + "ScanSummary": { + "required": [ + "engine", + "artifacts", + "unscanned", + "failed", + "clean", + "bySeverity" + ], + "type": "object", + "properties": { + "engine": { + "$ref": "#/components/schemas/ScanEngineStatus" + }, + "artifacts": { + "type": "integer", + "description": "Artifacts stored in the repository.", + "format": "int32" + }, + "unscanned": { + "type": "integer", + "description": "Artifacts with no successful scan.", + "format": "int32" + }, + "failed": { + "type": "integer", + "description": "Of those, the ones whose last attempt failed.", + "format": "int32" + }, + "clean": { + "type": "integer", + "description": "Artifacts scanned without findings.", + "format": "int32" + }, + "bySeverity": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "description": "Artifacts by their highest finding: index 0 low … 3 critical." + } + }, + "description": "The repository dashboard numbers." + }, + "ScanViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image).", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version (Docker: the manifest digest).", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where the link back goes: the package page the user came from (a local address only).", + "nullable": true + }, + "message": { + "type": "string", + "description": "What happened, for the screen to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? ScanViewModel.Message reports a refusal." + }, + "result": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanResult" + } + ] + }, + "engine": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanEngineStatus" + } + ] + }, + "backUrl": { + "type": "string", + "description": "The address the link back leads to (the return address when it is local, else the home page)." + } + }, + "description": "What the Scan now screen (`/scan-artifact`) shows; filled by the screen's workflow." + }, + "ScreenLink": { + "required": [ + "screen", + "routeValues" + ], + "type": "object", + "properties": { + "screen": { + "$ref": "#/components/schemas/ScreenRef" + }, + "routeValues": { + "type": "object", + "description": "Route values; a null value (`repo` of the default repository) is kept." + } + }, + "description": "A screen as a client links to it: the screen (controller and action) and its route values; the view turns it into an address." + }, + "ScreenNext": { + "required": [ + "screen" + ], + "type": "object", + "properties": { + "screen": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScreenRef" + } + ] + }, + "routeValues": { + "type": "object", + "description": "Route and query values of the next screen (`repo`, `name`, `handler`).", + "nullable": true + }, + "message": { + "type": "string", + "description": "The outcome to show on the next screen (a flash message).", + "nullable": true + }, + "error": { + "type": "string", + "description": "The refusal to show on the next screen (a flash error).", + "nullable": true + }, + "localUrl": { + "type": "string", + "description": "Instead of a screen: a local address to continue at (`/packages`, or `~/` for the site root, which the view prefixes with the path\r\nbase). Always safe to follow: a use case only puts a validated local address here (LocalUrls).", + "nullable": true + }, + "fragment": { + "type": "string", + "description": "The URL fragment (`#id`) to leave the next screen at, or null.", + "nullable": true + } + }, + "description": "Where a finished action leads: the screen (controller and action, see ScreenCatalog), its route values and the message to show there." + }, + "ScreenRef": { + "required": [ + "controller", + "action" + ], + "type": "object", + "properties": { + "controller": { + "type": "string", + "description": "The controller name without the `Controller` suffix (`AdminUsers`)." + }, + "action": { + "type": "string", + "description": "The action that shows the screen (`Index`)." + } + }, + "description": "A screen of the web UI: the MVC controller (without the `Controller` suffix, as `asp-controller` writes it) and the action that\r\nanswers a plain `GET` for it (`AdminUsers` / `Index`). The Application projects have no MVC reference, so the UI project\r\nturns it into a link. ScreenCatalog lists every screen." + }, + "ScreenResultOfAbuseViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AbuseViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAccessUnavailableViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AccessUnavailableViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAccountAccessViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AccountAccessViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAccountPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AccountPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAdminOrganizationsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AdminOrganizationsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAdminPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AdminPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAdminSettingsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AdminSettingsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAntiforgeryTokenModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AntiforgeryTokenModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfApiCatalogViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ApiCatalogViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfApiKeysViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ApiKeysViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAuditViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AuditViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfClusterViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ClusterViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfConfirmEmailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ConfirmEmailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfContactOwnersViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ContactOwnersViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDatabaseCopyStatusView": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DatabaseCopyStatusView" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDeleteUserViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DeleteUserViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDockerImagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DockerImagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDockerImageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DockerImageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDockerManageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DockerManageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfEmptyScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/EmptyScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfForgotPasswordViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ForgotPasswordViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfFormatsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/FormatsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfGroupDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/GroupDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfGroupsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/GroupsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfIndexScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/IndexScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfLegalScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/LegalScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfLoginViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/LoginViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenArtifactsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenArtifactsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenArtifactViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenArtifactViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenManageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenManageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenUploadViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenUploadViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmManageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmManageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmPackageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmPackageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmUploadViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmUploadViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfOperationsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/OperationsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfOrganizationDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/OrganizationDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfOrganizationsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/OrganizationsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPackageManageScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PackageManageScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPackageScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PackageScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPermissionDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PermissionDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPermissionsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PermissionsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfProfileViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ProfileViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfProjectDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ProjectDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfProjectsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ProjectsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReauthenticateViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReauthenticateViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRecoveryCodeLoginViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RecoveryCodeLoginViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRegisterViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RegisterViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReplicationConfigViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReplicationConfigViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReplicationViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReplicationViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReportAbuseScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReportAbuseScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRepositoriesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RepositoriesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRepositoryDeleteViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RepositoryDeleteViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRepositoryEditViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RepositoryEditViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfResetPasswordViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ResetPasswordViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRetentionHoldsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RetentionHoldsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRetentionPolicyViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RetentionPolicyViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRetentionViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RetentionViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanningViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanningViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanProjectViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanProjectViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanRepositoryViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanRepositoryViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfSessionModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/SessionModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfSessionProvidersModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/SessionProvidersModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfSettingsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/SettingsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfStatisticsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/StatisticsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfTwoFactorLoginViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/TwoFactorLoginViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfTwoFactorViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/TwoFactorViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUploadViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UploadViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUserDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UserDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUserPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UserPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUsersViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UsersViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfValidationStatusViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ValidationStatusViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfValidationViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ValidationViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenStatus": { + "enum": [ + "Ok", + "Invalid", + "NotFound", + "Forbidden", + "SignIn", + "Next" + ], + "type": "string", + "description": "What a use case decided about a screen." + }, + "SearchResult": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The ID of the matched package.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The latest version of the matched pacakge. This is the full NuGet version after normalization,\r\nincluding any SemVer 2.0.0 build metadata.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description of the matched package.", + "nullable": true + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The authors of the matched package.", + "nullable": true + }, + "iconUrl": { + "type": "string", + "description": "The URL of the matched package's icon.", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "description": "The URL of the matched package's license.", + "nullable": true + }, + "packageTypes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchResultPackageType" + }, + "description": "The package types defined by the package author.", + "nullable": true + }, + "projectUrl": { + "type": "string", + "description": "The URL of the matched package's homepage.", + "nullable": true + }, + "registration": { + "type": "string", + "description": "The URL for the matched package's registration index.", + "nullable": true + }, + "summary": { + "type": "string", + "description": "The summary of the matched package.", + "nullable": true + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The tags of the matched package.", + "nullable": true + }, + "title": { + "type": "string", + "description": "The title of the matched package.", + "nullable": true + }, + "totalDownloads": { + "type": "integer", + "description": "The total downloads for all versions of the matched package.", + "format": "int64" + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchResultVersion" + }, + "description": "The versions of the matched package.", + "nullable": true + }, + "deprecation": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageDeprecation" + } + ] + }, + "vulnerabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageVulnerabilityMetadata" + }, + "description": "The latest version's known vulnerabilities, or null if it has none.", + "nullable": true + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The package's owners, or null if it has none.", + "nullable": true + }, + "verified": { + "type": "boolean", + "description": "Whether the package ID is reserved for its owners. Null if it has no owners.", + "nullable": true + } + }, + "description": "A package that matched a search query.\r\n\r\nSee https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result" + }, + "SearchResultPackageType": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the package type.", + "nullable": true + } + }, + "description": "A single package type from a SearchResult.\r\n\r\nSee https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result" + }, + "SearchResultVersion": { + "type": "object", + "properties": { + "@id": { + "type": "string", + "description": "The registration leaf URL for this single version of the matched package.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata.", + "nullable": true + }, + "downloads": { + "type": "integer", + "description": "The downloads for this single version of the matched package.", + "format": "int64" + } + }, + "description": "A single version from a SearchResult.\r\n\r\nSee https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result" + }, + "SearchSort": { + "enum": [ + "Relevance", + "TotalDownloads", + "LastUpdated" + ], + "type": "string", + "description": "How the web UI orders search results. The V3 search API has no sort parameter, so\r\nit always uses SearchSort.Relevance." + }, + "SemVerLevel": { + "enum": [ + "Unknown", + "SemVer2" + ], + "type": "string" + }, + "SessionCookieForm": { + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The username (password step).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password (password step).", + "nullable": true + }, + "ticket": { + "type": "string", + "description": "The `twoFactorTicket` of the password step (second step).", + "nullable": true + }, + "code": { + "type": "string", + "description": "A code of the authenticator app (second step).", + "nullable": true + }, + "recoveryCode": { + "type": "string", + "description": "A recovery code (second step).", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/cookie` (a same-origin client that signs in with the cookie): the password step (string? SessionCookieForm.UserName,\r\nstring? SessionCookieForm.Password), or, when the account has two-factor, the second step (string? SessionCookieForm.Ticket with string? SessionCookieForm.Code or string? SessionCookieForm.RecoveryCode)." + }, + "SessionExchangeForm": { + "required": [ + "exchangeToken" + ], + "type": "object", + "properties": { + "exchangeToken": { + "type": "string", + "description": "The `exchange_token` of the external sign-in's redirect.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/exchange`." + }, + "SessionModel": { + "type": "object", + "properties": { + "accessToken": { + "type": "string", + "description": "Authenticates requests to `/api/ui` (`Authorization: Bearer`); null while bool SessionModel.TwoFactorRequired.", + "nullable": true + }, + "expiresAt": { + "type": "string", + "description": "When the access token stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "refreshToken": { + "type": "string", + "description": "Exchanged for a new pair at `/api/ui/session/refresh`; each refresh returns a new one and the old one stays valid until it expires.", + "nullable": true + }, + "refreshExpiresAt": { + "type": "string", + "description": "When the refresh token stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The signed-in user's name.", + "nullable": true + }, + "twoFactorRequired": { + "type": "boolean", + "description": "The password was right but the account asks for a second factor: post the string? SessionModel.TwoFactorTicket and a code to `/api/ui/session/two-factor` or `/recovery-code`." + }, + "twoFactorTicket": { + "type": "string", + "description": "Proves the password step; valid for five minutes, and useless without a code.", + "nullable": true + }, + "twoFactorTicketExpiresAt": { + "type": "string", + "description": "When the ticket stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "exchangeToken": { + "type": "string", + "description": "External sign-in only: a single-use-in-practice token (60 seconds) to exchange for the real ones at `POST /api/ui/session/exchange`.", + "nullable": true + }, + "exchangeExpiresAt": { + "type": "string", + "description": "When the exchange token stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "notice": { + "type": "string", + "description": "Something to tell the user when there are no tokens yet (external sign-in: the account was created and awaits approval or a confirmed email address).", + "nullable": true + } + }, + "description": "What `/api/ui/session` answers: a pair of tokens, or the ticket for the second factor of a sign-in." + }, + "SessionProvidersModel": { + "type": "object", + "properties": { + "providers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalProviderInfo" + }, + "description": "The configured providers, empty when there is none." + } + }, + "description": "The external sign-in providers a client can offer (`GET /api/ui/session/providers`): one button each, started at `/api/ui/session/external/{id}`." + }, + "SessionRecoveryCodeForm": { + "required": [ + "ticket", + "recoveryCode" + ], + "type": "object", + "properties": { + "ticket": { + "type": "string", + "description": "The `twoFactorTicket` the password step answered.", + "nullable": true + }, + "recoveryCode": { + "type": "string", + "description": "A recovery code.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/recovery-code`: the ticket of the password step and one of the account's recovery codes (each works once)." + }, + "SessionRefreshForm": { + "required": [ + "refreshToken" + ], + "type": "object", + "properties": { + "refreshToken": { + "type": "string", + "description": "The `refreshToken` of the last answer.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/refresh`." + }, + "SessionSignInForm": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session`: the same credentials as the sign-in page." + }, + "SessionSignOutForm": { + "type": "object", + "properties": { + "refreshToken": { + "type": "string", + "description": "The refresh token to end the session with when the request carries no access token.", + "nullable": true + }, + "everywhere": { + "type": "boolean", + "description": "Also ends every other session of the account (cookie sessions and tokens) by changing its security stamp. Without it nothing is\r\nrevoked: the tokens are stateless, so the client simply forgets them, and they expire." + } + }, + "description": "The body of `POST /api/ui/session/sign-out`." + }, + "SessionTwoFactorForm": { + "required": [ + "ticket", + "code" + ], + "type": "object", + "properties": { + "ticket": { + "type": "string", + "description": "The `twoFactorTicket` the password step answered.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/two-factor`: the ticket of the password step and a code of the authenticator app." + }, + "SettingDescriptor": { + "required": [ + "key", + "section", + "group", + "kind", + "enumValues", + "isSensitive", + "requiresRestart", + "description" + ], + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The full key, such as \"Email:Smtp:Host\"." + }, + "section": { + "type": "string", + "description": "The first segment of the key, or an empty string for a top-level key." + }, + "group": { + "type": "string", + "description": "The options type's name without \"Options\", such as \"AzureBlobStorage\"." + }, + "kind": { + "$ref": "#/components/schemas/SettingKind" + }, + "enumValues": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The allowed names of an SettingKind.Enum, otherwise empty." + }, + "isSensitive": { + "type": "boolean", + "description": "The value is a credential: masked and write-only." + }, + "requiresRestart": { + "type": "boolean", + "description": "A change applies after a restart." + }, + "description": { + "type": "string", + "description": "The property's XML documentation summary, or an empty string." + }, + "exampleDependsOnKey": { + "type": "string", + "description": "The full key of the setting that selects Examples (see\r\nSettingExampleAttribute), or null.", + "nullable": true + }, + "examples": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Example values by the value of ExampleDependsOnKey (case-insensitive), or null.", + "nullable": true + } + }, + "description": "One configuration key the Settings page can show." + }, + "SettingKind": { + "enum": [ + "Boolean", + "Integer", + "Number", + "String", + "Enum", + "TimeSpan", + "StringList", + "ReadOnly" + ], + "type": "string", + "description": "The editable type of a setting." + }, + "SettingsSection": { + "required": [ + "key", + "id", + "settings" + ], + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The section's key; empty for the settings that sit at the top level." + }, + "id": { + "type": "string", + "description": "The stable DOM id (string AdminSettingsViewModel.SectionId(string key))." + }, + "settings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SettingState" + }, + "description": "The settings of the section; a sensitive one never carries its value." + } + }, + "description": "One section of the settings screen: its key (empty for the top-level keys), its DOM id and its settings." + }, + "SettingsSubmission": { + "required": [ + "section", + "password", + "fields" + ], + "type": "object", + "properties": { + "section": { + "type": "string", + "description": "The section being saved (the empty section holds the top-level keys).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + }, + "fields": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "The posted fields; a field may repeat." + } + }, + "description": "The fields of a submitted Settings form, per setting key (`v:<key>` the value, `reset:<key>`, `clear:<key>`; a checkbox posts\r\n`true` next to a hidden `false`, a list is one entry per line) and the section they belong to. The same shape whether it comes from the\r\npage's form or from a JSON body." + }, + "SettingState": { + "required": [ + "descriptor", + "effectiveValue", + "hasValue", + "isOverridden", + "shadowedBy", + "pendingRestart" + ], + "type": "object", + "properties": { + "descriptor": { + "$ref": "#/components/schemas/SettingDescriptor" + }, + "effectiveValue": { + "type": "string", + "description": "The value in effect, as text (a list one entry per line). Always null for a sensitive\r\nsetting: only HasValue says whether one is set.", + "nullable": true + }, + "hasValue": { + "type": "boolean", + "description": "The setting has a non-empty value." + }, + "isOverridden": { + "type": "boolean", + "description": "The setting is saved in the overrides file." + }, + "shadowedBy": { + "type": "string", + "description": "What overrides the saved value (\"environment variable\", \"command line\", ...), or null.\r\nWhile set, a saved value has no effect.", + "nullable": true + }, + "pendingRestart": { + "type": "boolean", + "description": "A restart-only setting whose value changed since startup." + } + }, + "description": "A setting as the Settings page shows it." + }, + "SettingsViewModel": { + "type": "object", + "properties": { + "email": { + "type": "string", + "description": "The account's email address.", + "nullable": true + }, + "emailConfirmed": { + "type": "boolean", + "description": "Whether the address is confirmed." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the account has a password (else it signs in through a provider)." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is configured to sign in again with." + }, + "canSendEmail": { + "type": "boolean", + "description": "Whether mail is configured." + }, + "externalLogins": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalLoginStatus" + }, + "description": "Every configured external provider with whether this account has linked a login at it (empty when there is none)." + }, + "message": { + "type": "string", + "description": "The success message to show.", + "nullable": true + }, + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "blockers": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DeletionBlockers" + } + ] + } + }, + "description": "What the account settings screen shows (change email, change password, delete the account)." + }, + "SignInProviderForm": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id (lower-case letters, digits and `-`, 1 to 32).", + "nullable": true + }, + "displayName": { + "type": "string", + "description": "The name on the sign-in button.", + "nullable": true + }, + "authority": { + "type": "string", + "description": "The issuer address.", + "nullable": true + }, + "clientId": { + "type": "string", + "description": "The client id.", + "nullable": true + }, + "clientSecret": { + "type": "string", + "description": "The client secret; blank keeps the saved one. Never sent back.", + "nullable": true + }, + "scopes": { + "type": "string", + "description": "Extra scopes, separated by spaces or semicolons.", + "nullable": true + }, + "parameters": { + "type": "string", + "description": "Extra authorization request parameters, one `name=value` per line.", + "nullable": true + }, + "userNameClaim": { + "type": "string", + "description": "The claim holding the user name.", + "nullable": true + }, + "emailClaim": { + "type": "string", + "description": "The claim holding the email address.", + "nullable": true + }, + "emailVerifiedClaim": { + "type": "string", + "description": "The claim saying the address is verified.", + "nullable": true + }, + "administratorClaim": { + "type": "string", + "description": "The claim that decides the administrator flag (the provider becomes authoritative for it).", + "nullable": true + }, + "administratorValue": { + "type": "string", + "description": "The value of that claim that makes a user an administrator.", + "nullable": true + }, + "groupClaim": { + "type": "string", + "description": "The claim holding the user's groups.", + "nullable": true + }, + "groupMappings": { + "type": "string", + "description": "Claim value to BaGet group, one `value=group` per line.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "What the \"Sign-in providers\" panel of the Settings screen posts to add or edit a named OpenID Connect provider (the body of\r\n`POST /api/ui/admin/settings/save-provider`). The id is the key and cannot change once created; a blank secret keeps the saved one.\r\nstring? SignInProviderForm.Parameters and string? SignInProviderForm.GroupMappings are one `name=value` per line." + }, + "SignInProviderView": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id." + }, + "displayName": { + "type": "string", + "description": "The name on the sign-in button.", + "nullable": true + }, + "authority": { + "type": "string", + "description": "The issuer address.", + "nullable": true + }, + "clientId": { + "type": "string", + "description": "The client id.", + "nullable": true + }, + "hasSecret": { + "type": "boolean", + "description": "Whether a client secret is set." + }, + "scopes": { + "type": "string", + "description": "Extra scopes.", + "nullable": true + }, + "parameters": { + "type": "string", + "description": "Extra request parameters, one `name=value` per line.", + "nullable": true + }, + "userNameClaim": { + "type": "string", + "description": "The claim holding the user name.", + "nullable": true + }, + "emailClaim": { + "type": "string", + "description": "The claim holding the email address.", + "nullable": true + }, + "emailVerifiedClaim": { + "type": "string", + "description": "The claim saying the address is verified.", + "nullable": true + }, + "administratorClaim": { + "type": "string", + "description": "The claim that decides the administrator flag.", + "nullable": true + }, + "administratorValue": { + "type": "string", + "description": "The value of that claim that makes a user an administrator.", + "nullable": true + }, + "groupClaim": { + "type": "string", + "description": "The claim holding the user's groups.", + "nullable": true + }, + "groupMappings": { + "type": "string", + "description": "Claim value to BaGet group, one `value=group` per line.", + "nullable": true + }, + "editable": { + "type": "boolean", + "description": "Whether the overrides file holds it, so this screen can edit or remove it; false when a configuration file or the environment sets it." + }, + "active": { + "type": "boolean", + "description": "Whether the running server has a handler for it (false: saved or removed since startup)." + }, + "pendingRestart": { + "type": "boolean", + "description": "Whether what is saved differs from what the running server uses, so a restart is needed." + } + }, + "description": "A named OpenID Connect provider as the Settings screen lists it. The client secret is never carried, only whether one is set." + }, + "SoleOwnedPackage": { + "required": [ + "repositoryKey", + "repositoryName", + "packageId" + ], + "type": "object", + "properties": { + "repositoryKey": { + "type": "integer", + "description": "The repository's key.", + "format": "int32" + }, + "repositoryName": { + "type": "string", + "description": "The repository's name (string Repository.DefaultName for the default)." + }, + "packageId": { + "type": "string", + "description": "The package ID.", + "nullable": true + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "label": { + "type": "string", + "description": "The ID for the default repository, `ID (name)` for any other, for messages that mix repositories.", + "nullable": true + } + }, + "description": "A package ID in one repository that only one user owns." + }, + "StatisticsViewModel": { + "required": [ + "statistics" + ], + "type": "object", + "properties": { + "statistics": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/FeedStatistics" + } + ] + } + }, + "description": "What the statistics page shows." + }, + "Stream": { + "type": "string", + "format": "binary", + "nullable": true + }, + "SubmissionForm": { + "required": [ + "submissionId", + "password" + ], + "type": "object", + "properties": { + "submissionId": { + "type": "string", + "description": "The submission.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (asked to release or reject).", + "nullable": true + } + }, + "description": "A decision on a stuck submission of the validation queue." + }, + "TargetDetails": { + "required": [ + "target", + "grants" + ], + "type": "object", + "properties": { + "target": { + "$ref": "#/components/schemas/TargetSummary" + }, + "grants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GrantInfo" + } + } + }, + "description": "A permission target with its grants." + }, + "TargetFramework": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "moniker": { + "type": "string", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + } + }, + "TargetSummary": { + "required": [ + "key", + "name", + "repositoryPatterns", + "includePatterns", + "excludePatterns", + "projectKey", + "projectName", + "isBuiltIn", + "grantCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + }, + "repositoryPatterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "includePatterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludePatterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "projectKey": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "projectName": { + "type": "string", + "nullable": true + }, + "isBuiltIn": { + "type": "boolean" + }, + "grantCount": { + "type": "integer", + "format": "int32" + } + }, + "description": "A permission target as the admin pages list it." + }, + "TelemetrySignalReport": { + "required": [ + "signal", + "state", + "lastSuccess", + "failingSince", + "lastError", + "dropped" + ], + "type": "object", + "properties": { + "signal": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/TelemetrySignalState" + }, + "lastSuccess": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "failingSince": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "lastError": { + "type": "string", + "nullable": true + }, + "dropped": { + "type": "integer", + "format": "int64" + } + }, + "description": "One signal's state. string? TelemetrySignalReport.LastError is already scrubbed (no headers, credentials or URL paths)." + }, + "TelemetrySignalState": { + "enum": [ + "Off", + "NotConfigured", + "Waiting", + "Ok", + "Failing" + ], + "type": "string", + "description": "What one telemetry signal is doing, as the Settings page shows it." + }, + "TelemetryTestOutcome": { + "required": [ + "ok", + "message", + "target" + ], + "type": "object", + "properties": { + "ok": { + "type": "boolean", + "description": "The collector accepted a test span." + }, + "message": { + "type": "string", + "description": "What happened." + }, + "target": { + "type": "string", + "description": "The endpoint that was tested, cut to scheme, host and port.", + "nullable": true + } + }, + "description": "The outcome of a connection test; string TelemetryTestOutcome.Message and string? TelemetryTestOutcome.Target are scrubbed." + }, + "TwoFactorCodeForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + } + }, + "description": "What the \"turn two-factor authentication on\" form posts." + }, + "TwoFactorLoginForm": { + "required": [ + "code" + ], + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the authenticator-code form posts." + }, + "TwoFactorLoginViewModel": { + "required": [ + "code" + ], + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The second step of signing in: an authenticator code. A request binds TwoFactorLoginForm, never this type." + }, + "TwoFactorViewModel": { + "type": "object", + "properties": { + "twoFactorEnabled": { + "type": "boolean", + "description": "Whether two-factor authentication is on." + }, + "sharedKey": { + "type": "string", + "description": "The key to type into an authenticator that cannot scan the QR code.", + "nullable": true + }, + "qrCodeSvg": { + "type": "string", + "description": "The QR code of the setup link, an SVG built from the user's own key.", + "nullable": true + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is configured to sign in again with." + }, + "recoveryCodesLeft": { + "type": "integer", + "description": "How many recovery codes are unused.", + "format": "int32" + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the account has a password (else it signs in through a provider)." + }, + "recoveryCodes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The new recovery codes. Shown once, when two-factor authentication is turned on." + }, + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "message": { + "type": "string", + "description": "The success message to show.", + "nullable": true + } + }, + "description": "What the two-factor authentication screen shows." + }, + "UnlinkExternalForm": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "description": "The id of the provider to unlink.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password, asked again.", + "nullable": true + } + }, + "description": "What unlinking an external provider posts." + }, + "UploadPreview": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The handle of the staged file; only the user who staged it can open it.", + "nullable": true + }, + "isSymbolPackage": { + "type": "boolean", + "description": "Whether the file is a symbol package (`.snupkg`, by its nuspec's package type)." + }, + "id": { + "type": "string", + "description": "The package ID, from the nuspec.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The normalized version, from the nuspec.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description.", + "nullable": true + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The authors." + }, + "license": { + "type": "string", + "description": "The license expression or license file the package declares, if any.", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "description": "The license URL, if any.", + "nullable": true + }, + "dependencyGroups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DependencyGroupModel" + }, + "description": "The dependencies by target framework." + }, + "readme": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/HtmlString" + } + ] + }, + "symbolFiles": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The PDBs of a symbol package." + }, + "targetPackageExists": { + "type": "boolean", + "description": "Whether the version a symbol package belongs to is on this server." + }, + "targetPackageMessage": { + "type": "string", + "description": "What to tell about a symbol package whose package is missing.", + "nullable": true + } + }, + "description": "What a staged NuGet upload contains, as the preview of the upload page shows it (read from the archive itself)." + }, + "UploadTokenRequest": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The handle of the staged upload (string? UploadPreview.Token)." + }, + "apiKey": { + "type": "string", + "description": "The API key of the uploader while accounts are off (otherwise the signed-in session or the key of the request authenticates).", + "nullable": true + }, + "acceptTerms": { + "type": "boolean", + "description": "The confirmation that the uploader may publish the package (required to publish, ignored when discarding)." + } + }, + "description": "What the second and third step of the NuGet upload send (publish and discard a staged upload): the handle of the staged file and, while accounts are\r\noff, the API key that authenticates the uploader. The key is read and never echoed in an answer." + }, + "UploadViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID a link arrived with, as \"upload a new version of this\" does. A hint for the page only: the ID and version that\r\nare published are read from the file, never from the request.", + "nullable": true + }, + "accountsEnabled": { + "type": "boolean", + "description": "Whether accounts are on (the uploader then signs in)." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server is read-only." + }, + "signedIn": { + "type": "boolean", + "description": "Whether the visitor is signed in." + }, + "needsApiKey": { + "type": "boolean", + "description": "With accounts off there is no user to own an upload, so the pusher proves itself with an API key." + }, + "nothingCanAuthenticate": { + "type": "boolean", + "description": "Nothing on this server can tell one caller from another (accounts off and no global API key): the browser upload is closed." + }, + "noApiKeyExplanation": { + "type": "string", + "description": "What the page says in that state, so the explanation and the refusal are one sentence.", + "nullable": true + }, + "canUpload": { + "type": "boolean", + "description": "Whether to render the form at all." + }, + "staged": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadPreview" + } + ] + }, + "message": { + "type": "string", + "description": "What happened, for the page to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? UploadViewModel.Message reports a failure." + }, + "published": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadPreview" + } + ] + }, + "retryToken": { + "type": "string", + "description": "The token of a staged upload whose API key was rejected, so the key can be entered again.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with (200, or the refusal's).", + "format": "int32" + } + }, + "description": "What the NuGet upload page (`/upload`) shows: the form, the preview of a staged file, or the outcome of a step." + }, + "UserAccountInfo": { + "required": [ + "userName", + "email", + "created", + "isAdministrator", + "pendingApproval" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address, or null.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When the account was created.", + "format": "date-time" + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether it is a server administrator." + }, + "pendingApproval": { + "type": "boolean", + "description": "Whether it waits for an administrator to enable it." + } + }, + "description": "The account an administrator looks at, without anything that signs in as it (no password hash, security stamp or tokens)." + }, + "UserChange": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The account the change applies to.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + }, + "q": { + "type": "string", + "description": "The list's user-name filter.", + "nullable": true + }, + "pageNumber": { + "type": "integer", + "description": "The list's page.", + "format": "int32", + "default": 1 + }, + "resetEmail": { + "type": "string", + "description": "For a password reset: the address to mail the new password to, if the administrator typed one.", + "nullable": true + } + }, + "description": "A change to one account from the Users screen, with the list's filter and page to come back to." + }, + "UserCreation": { + "required": [ + "newUserName", + "newEmail", + "newPassword", + "invite", + "password" + ], + "type": "object", + "properties": { + "newUserName": { + "type": "string", + "description": "The new account's name.", + "nullable": true + }, + "newEmail": { + "type": "string", + "description": "Its address, or null.", + "nullable": true + }, + "newPassword": { + "type": "string", + "description": "The password typed; empty means generate one (unless Invite).", + "nullable": true + }, + "invite": { + "type": "boolean", + "description": "Mail the user a link to choose their own password." + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + }, + "q": { + "type": "string", + "description": "The list's user-name filter.", + "nullable": true + }, + "pageNumber": { + "type": "integer", + "description": "The list's page.", + "format": "int32", + "default": 1 + } + }, + "description": "A new account from the Users screen." + }, + "UserDeletionForm": { + "required": [ + "soleOwned", + "password" + ], + "type": "object", + "properties": { + "soleOwned": { + "type": "string", + "description": "\"keep\" (default) or \"delete\": what to do with the package IDs only this user owns.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Deleting an account." + }, + "UserDetailViewModel": { + "type": "object", + "properties": { + "package": { + "type": "string", + "description": "A package ID to evaluate the effective permissions for; empty means each repository as a whole.", + "nullable": true + }, + "name": { + "type": "string", + "description": "The user name (route).", + "nullable": true + }, + "modelAvailable": { + "type": "boolean", + "description": "Whether the configured database has an access model (else the access sections are hidden)." + }, + "groups": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of the groups the account belongs to (the implicit built-ins excluded)." + }, + "projectRoles": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserProjectRole" + }, + "description": "The roles the account holds in projects, directly or through a group." + }, + "access": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryAccessRow" + }, + "description": "What the account may do in each NuGet repository, and why." + }, + "account": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserAccountInfo" + } + ] + }, + "keys": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserKeyRow" + }, + "description": "The account's API keys; the key and its hash are never shown." + }, + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Organization" + }, + "description": "The organizations the account belongs to." + }, + "ownedPackageIds": { + "type": "integer", + "description": "How many package IDs the account owns, in every repository.", + "format": "int32" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the user detail screen (`/admin/users/{name}`) shows: the account, its keys, organizations and access." + }, + "UserGroupForm": { + "required": [ + "group", + "password" + ], + "type": "object", + "properties": { + "group": { + "type": "string", + "description": "The group's name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Adding an account to a group or removing it." + }, + "UserKeyForm": { + "required": [ + "key", + "password" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The key's number (int UserKeyRow.Key).", + "format": "int32" + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Revoking one of an account's API keys." + }, + "UserKeyRow": { + "required": [ + "key", + "description", + "scopes", + "packageGlobPattern", + "created", + "expires", + "repositories" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The key's number (what revoking names).", + "format": "int32" + }, + "description": { + "type": "string", + "description": "The description the owner gave it.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "What it may do." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs it applies to.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When it was created.", + "format": "date-time" + }, + "expires": { + "type": "string", + "description": "When it expires, or null.", + "format": "date-time", + "nullable": true + }, + "repositories": { + "type": "string", + "description": "Where it may be used: the repositories it is limited to, or \"all repositories\"." + } + }, + "description": "One of an account's API keys as the administrator sees it; the key itself and its hash are never shown." + }, + "UserPackagesViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The user name, from the route.", + "nullable": true + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminPackageRow" + }, + "description": "The user's packages." + } + }, + "description": "What the user packages screen (`/admin/users/{name}/packages`) shows: the package IDs one user owns." + }, + "UserProjectRole": { + "required": [ + "project", + "role", + "via" + ], + "type": "object", + "properties": { + "project": { + "type": "string" + }, + "role": { + "$ref": "#/components/schemas/ProjectRole" + }, + "via": { + "type": "string" + } + }, + "description": "A role a user holds in a project, directly or through a group." + }, + "UserRow": { + "required": [ + "userName", + "email", + "created", + "isAdministrator", + "avatarUrl" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address, if any.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When the account was created.", + "format": "date-time" + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the user is an administrator." + }, + "avatarUrl": { + "type": "string", + "description": "The avatar's address, or null for the initial.", + "nullable": true + }, + "pendingApproval": { + "type": "boolean", + "description": "Whether the account waits for an administrator to enable it (`Accounts:RequireApproval`).", + "default": false + } + }, + "description": "A user as the Users page lists them." + }, + "UsersViewModel": { + "type": "object", + "properties": { + "q": { + "type": "string", + "description": "User-name filter (contains).", + "nullable": true + }, + "pageNumber": { + "type": "integer", + "description": "One-based page number (the `p` query value; not \"page\", which Razor Pages reserved for the page path).", + "format": "int32" + }, + "users": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserRow" + }, + "description": "The users on this page." + }, + "pendingCount": { + "type": "integer", + "description": "How many accounts, in all pages, wait for approval.", + "format": "int32" + }, + "pageCount": { + "type": "integer", + "description": "The number of pages for the current filter.", + "format": "int32" + }, + "currentUserName": { + "type": "string", + "description": "The signed in administrator's user name; their own row has no actions.", + "nullable": true + }, + "canEmailResetLink": { + "type": "boolean", + "description": "Whether a reset link can be mailed: SMTP is configured." + }, + "canInvite": { + "type": "boolean", + "description": "Whether an invitation (a reset link mailed to the new user) can be offered: SMTP is configured." + }, + "generatedPassword": { + "type": "string", + "description": "The password just generated. Only ever rendered by the response to the reset itself, never kept in TempData or a cookie.", + "nullable": true + }, + "generatedFor": { + "type": "string", + "description": "The user string? UsersViewModel.GeneratedPassword belongs to.", + "nullable": true + }, + "generatedForNewUser": { + "type": "boolean", + "description": "Whether string? UsersViewModel.GeneratedPassword is a new account's first password rather than a reset." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the Users screen (`/admin/users`) shows: the filtered, paged accounts and the state of the last action." + }, + "ValidationStatusViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID from the address.", + "nullable": true + }, + "submissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationSubmission" + }, + "description": "The newest submission of each version, newest version first." + } + }, + "description": "What the validation status screen (`/packages/{id}/validation`) shows; filled by the screen's workflow." + }, + "ValidationSubmission": { + "required": [ + "version", + "submissionId", + "status", + "steps" + ], + "type": "object", + "properties": { + "version": { + "type": "string" + }, + "submissionId": { + "type": "string", + "nullable": true + }, + "status": { + "type": "string" + }, + "steps": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageValidation" + } + } + }, + "description": "One version's newest validation submission and the verdict of every step." + }, + "ValidationSubmissionState": { + "enum": [ + "Pending", + "Quarantined" + ], + "type": "string", + "description": "Where a submission stands: still to run, or stopped without being indexed." + }, + "ValidationSubmissionSummary": { + "required": [ + "submissionId", + "repository", + "packageId", + "packageVersion", + "state", + "created", + "failureMessages" + ], + "type": "object", + "properties": { + "submissionId": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "packageId": { + "type": "string", + "nullable": true + }, + "packageVersion": { + "type": "string", + "nullable": true + }, + "state": { + "$ref": "#/components/schemas/ValidationSubmissionState" + }, + "created": { + "type": "string", + "format": "date-time" + }, + "failureMessages": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "description": "One submission awaiting validation or quarantined." + }, + "ValidationViewModel": { + "type": "object", + "properties": { + "isSupported": { + "type": "boolean", + "description": "Whether validation can be administered here." + }, + "submissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationSubmissionSummary" + }, + "description": "The pending and quarantined submissions." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the validation queue screen (`/admin/validation`) shows: pending and quarantined submissions." + }, + "VirtualMemberDetail": { + "required": [ + "name", + "repository" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The member's name, as stored." + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + }, + "exists": { + "type": "boolean", + "description": "Whether a repository of that name exists." + } + }, + "description": "One member of a virtual repository as the administration page lists it." + }, + "VirtualRepositoryDetail": { + "required": [ + "repository", + "members", + "deployRepository", + "deployTarget", + "effectiveMembers" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VirtualMemberDetail" + }, + "description": "Its direct members in resolution order." + }, + "deployRepository": { + "type": "string", + "description": "The name of the member that receives deployments, if any.", + "nullable": true + }, + "deployTarget": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + }, + "effectiveMembers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The local and remote repositories that answer, in order, nested virtual members expanded." + } + }, + "description": "A virtual repository as the administration pages edit it." + } + }, + "securitySchemes": { + "bearer": { + "type": "http", + "description": "An API key.", + "scheme": "bearer" + }, + "apiKey": { + "type": "apiKey", + "description": "An API key.", + "name": "X-NuGet-ApiKey", + "in": "header" + }, + "session": { + "type": "http", + "description": "A session token: the accessToken of POST /api/ui/session, refreshed with POST /api/ui/session/refresh. Only /api/ui accepts it.", + "scheme": "bearer", + "bearerFormat": "bgs.xxx" + } + } + }, + "security": [ + { + "bearer": [ ] + }, + { + "apiKey": [ ] + }, + { + "session": [ ] + } + ], + "tags": [ + { + "name": "AccountApi" + }, + { + "name": "AccountOrganizationsApi" + }, + { + "name": "AccountPackagesApi" + }, + { + "name": "AccountSettingsApi" + }, + { + "name": "AdminAuditApi" + }, + { + "name": "AdminGroupsApi" + }, + { + "name": "AdminOperationsApi" + }, + { + "name": "AdminOrganizationsApi" + }, + { + "name": "AdminPackagesApi" + }, + { + "name": "AdminPermissionsApi" + }, + { + "name": "AdminProjectsApi" + }, + { + "name": "AdminRepositoriesApi" + }, + { + "name": "AdminSettingsApi" + }, + { + "name": "AdminUsersApi" + }, + { + "name": "ContactOwnersApi" + }, + { + "name": "DockerManageApi" + }, + { + "name": "MavenManageApi" + }, + { + "name": "NpmManageApi" + }, + { + "name": "PackageManageApi" + }, + { + "name": "ProfileApi" + }, + { + "name": "ReplicationApi" + }, + { + "name": "RetentionApi" + }, + { + "name": "ScanArtifactApi" + }, + { + "name": "ScanningApi" + }, + { + "name": "SessionApi" + }, + { + "name": "ValidationStatusApi" + }, + { + "name": "ApiCatalogApi" + }, + { + "name": "DockerBrowseApi" + }, + { + "name": "IndexApi" + }, + { + "name": "LegalApi" + }, + { + "name": "MavenBrowseApi" + }, + { + "name": "NpmBrowseApi" + }, + { + "name": "PackageApi" + }, + { + "name": "ReportAbuseApi" + }, + { + "name": "StatisticsApi" + }, + { + "name": "UploadApi" + } + ] +} \ No newline at end of file diff --git a/samples/BaGet.Frontend.Angular/package-lock.json b/samples/BaGet.Frontend.Angular/package-lock.json new file mode 100644 index 000000000..a4d4c1ccb --- /dev/null +++ b/samples/BaGet.Frontend.Angular/package-lock.json @@ -0,0 +1,6151 @@ +{ + "name": "baget-frontend-angular", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "baget-frontend-angular", + "version": "0.0.0", + "dependencies": { + "@angular/common": "^22.2.0", + "@angular/compiler": "^22.2.0", + "@angular/core": "^22.2.0", + "@angular/forms": "^22.2.0", + "@angular/platform-browser": "^22.2.0", + "@angular/router": "^22.2.0", + "rxjs": "~7.8.0", + "tslib": "^2.3.0" + }, + "devDependencies": { + "@angular/build": "^22.2.4", + "@angular/cli": "^22.2.4", + "@angular/compiler-cli": "^22.2.0", + "openapi-typescript": "^7.0.0", + "prettier": "^3.8.1", + "typescript": "~6.0.2" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@angular-devkit/architect": { + "version": "0.2202.4", + "resolved": "https://registry.npmjs.org/@angular-devkit/architect/-/architect-0.2202.4.tgz", + "integrity": "sha512-hafew1tft3+bnv+DjAtLDEq/Yx5/UyAz/+M4VC5EWQQhcFCN81X47szTX3F9dNeiZIQb8d/WmCnmlbHz6CyupA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.2.4", + "rxjs": "7.8.2" + }, + "bin": { + "architect": "bin/cli.js" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular-devkit/core": { + "version": "22.2.4", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-22.2.4.tgz", + "integrity": "sha512-HDlsVK/qN7p5ttKgPvVLo87yrN0UcHR7OyQo1n/lvvMQcYrA0n01E+ix4t+q4C04ifpMbNQtrK0I1222OKi99w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "jsonc-parser": "3.3.1", + "picomatch": "4.0.7", + "rxjs": "7.8.2", + "source-map": "0.8.0" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "peerDependencies": { + "chokidar": "^5.0.0" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } + } + }, + "node_modules/@angular-devkit/schematics": { + "version": "22.2.4", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-22.2.4.tgz", + "integrity": "sha512-9pRNtcZN87yM7KQX+HTxGatrm86y30JxVwkF2WNG1pR0e9yeiYWc1KQ5hRS1Nq1LULoP95HApc+TBXqUXzF4Ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.2.4", + "jsonc-parser": "3.3.1", + "magic-string": "1.4.1", + "ora": "9.4.1", + "rxjs": "7.8.2" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular/build": { + "version": "22.2.4", + "resolved": "https://registry.npmjs.org/@angular/build/-/build-22.2.4.tgz", + "integrity": "sha512-Emb3pxRkvf749NQ5cz4ux2h9Cnbxx3FmcupdXIaoRxIyNXM8JxjFDCLZTe0yGGOWv5+hSaoR7XESOcN134vBPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "2.3.0", + "@angular-devkit/architect": "0.2202.4", + "@babel/core": "8.0.5", + "@inquirer/confirm": "6.3.2", + "@parcel/watcher": "2.6.0", + "@vitejs/plugin-basic-ssl": "2.3.0", + "beasties": "0.5.4", + "browserslist": "^4.26.0", + "chokidar": "5.0.0", + "esbuild": "0.28.2", + "https-proxy-agent": "9.1.0", + "jsonc-parser": "3.3.1", + "listr2": "11.1.0", + "magic-string": "1.4.1", + "mrmime": "2.0.1", + "oxc-parser": "0.150.0", + "parse5-html-rewriting-stream": "8.0.1", + "picomatch": "4.0.7", + "piscina": "5.3.2", + "rolldown": "1.2.8", + "sass": "1.104.1", + "sass-embedded": "1.104.1", + "semver": "7.8.5", + "source-map-support": "0.5.21", + "tinyglobby": "0.2.17", + "vite": "8.3.0", + "xxhash-wasm": "1.1.0" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "optionalDependencies": { + "lmdb": "3.5.6" + }, + "peerDependencies": { + "@angular/compiler": "^22.0.0", + "@angular/compiler-cli": "^22.0.0", + "@angular/core": "^22.0.0", + "@angular/localize": "^22.0.0", + "@angular/platform-browser": "^22.0.0", + "@angular/platform-server": "^22.0.0", + "@angular/service-worker": "^22.0.0", + "@angular/ssr": "^22.2.4", + "istanbul-lib-instrument": "^6.0.0", + "karma": "^6.4.0", + "less": "^4.2.0", + "ng-packagr": "^22.0.0", + "postcss": "^8.4.0", + "rollup": "^4.0.0", + "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0", + "tslib": "^2.3.0", + "typescript": ">=6.0 <6.1", + "vitest": "^4.0.8 || ^5.0.0" + }, + "peerDependenciesMeta": { + "@angular/core": { + "optional": true + }, + "@angular/localize": { + "optional": true + }, + "@angular/platform-browser": { + "optional": true + }, + "@angular/platform-server": { + "optional": true + }, + "@angular/service-worker": { + "optional": true + }, + "@angular/ssr": { + "optional": true + }, + "istanbul-lib-instrument": { + "optional": true + }, + "karma": { + "optional": true + }, + "less": { + "optional": true + }, + "ng-packagr": { + "optional": true + }, + "postcss": { + "optional": true + }, + "rollup": { + "optional": true + }, + "tailwindcss": { + "optional": true + }, + "vitest": { + "optional": true + } + } + }, + "node_modules/@angular/cli": { + "version": "22.2.4", + "resolved": "https://registry.npmjs.org/@angular/cli/-/cli-22.2.4.tgz", + "integrity": "sha512-luD9gNbMV7ME7mv9cUatVE+WF8Ecqa8v9Zo47YZK/6EPQUKdLxeosGWlHtrvBXElK1YehHItrUbawtZQmQwwlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/architect": "0.2202.4", + "@angular-devkit/core": "22.2.4", + "@angular-devkit/schematics": "22.2.4", + "@inquirer/prompts": "8.7.2", + "@listr2/prompt-adapter-inquirer": "4.2.7", + "@modelcontextprotocol/server": "2.3.1", + "@schematics/angular": "22.2.4", + "jsonc-parser": "3.3.1", + "listr2": "11.1.0", + "npm-package-arg": "14.0.0", + "parse5-html-rewriting-stream": "8.0.1", + "semver": "7.8.5", + "yargs": "18.1.0", + "zod": "4.6.6" + }, + "bin": { + "ng": "bin/ng.js" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular/common": { + "version": "22.2.3", + "resolved": "https://registry.npmjs.org/@angular/common/-/common-22.2.3.tgz", + "integrity": "sha512-sRzcvxzurbkCDVFJMguNVgsHds3NvDj5qbZ44NHjH7J9MBk5oZYXHppdHVm8AolBhCXAWvMk0vx+NO8Bt4rS7A==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@angular/core": "22.2.3", + "rxjs": "^6.5.3 || ^7.4.0" + } + }, + "node_modules/@angular/compiler": { + "version": "22.2.3", + "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-22.2.3.tgz", + "integrity": "sha512-GjDkmOBqW+6RJTeW5mlLRivf6Zy7Ed0auVh+DYD67d4UF4Sk17F1vIt8puF4CQ2PIezlHh7oOnermCBNHAOGkQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@angular/compiler-cli": { + "version": "22.2.3", + "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-22.2.3.tgz", + "integrity": "sha512-em7Ht0Dv7cN7vZgvl2fl1yscAs+zUG2Vr2YKpVZ/rOWuTL2JZyT1qIfKhC4wQoo/3lN8fiUIwQMpflSGzIEPng==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "8.0.1", + "@jridgewell/sourcemap-codec": "^1.4.14", + "chokidar": "^5.0.0", + "convert-source-map": "^1.5.1", + "reflect-metadata": "^0.2.0", + "semver": "^7.0.0", + "tslib": "^2.3.0", + "yargs": "^18.0.0" + }, + "bin": { + "ng-xi18n": "bundles/src/bin/ng_xi18n.js", + "ngc": "bundles/src/bin/ngc.js" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@angular/compiler": "22.2.3", + "typescript": ">=6.0 <6.1" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@angular/compiler-cli/node_modules/@babel/core": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-8.0.1.tgz", + "integrity": "sha512-5FgxM4dLQpMJHSiVATk8foW263dVHQHBVpXYiimNECVWG01f4nFyEbQixeT6Mwvg7TayREJ2gpKl3o2RoMdnqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^8.0.0", + "@babel/generator": "^8.0.0", + "@babel/helper-compilation-targets": "^8.0.0", + "@babel/helpers": "^8.0.0", + "@babel/parser": "^8.0.0", + "@babel/template": "^8.0.0", + "@babel/traverse": "^8.0.0", + "@babel/types": "^8.0.0", + "@types/gensync": "^1.0.5", + "convert-source-map": "^2.0.0", + "empathic": "^2.0.1", + "gensync": "^1.0.0-beta.2", + "import-meta-resolve": "^4.2.0", + "json5": "^2.2.3", + "obug": "^2.1.1", + "semver": "^7.7.3" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@angular/compiler-cli/node_modules/@babel/core/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@angular/core": { + "version": "22.2.3", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-22.2.3.tgz", + "integrity": "sha512-ponarFrAZsPutT+htRt3PEmkt2/IB7DyrBy2f48sxsIx3ZA6xw09i2HOEBo+VBphlN6B/ynK9q+o04HPhdJ+dQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@angular/compiler": "22.2.3", + "rxjs": "^6.5.3 || ^7.4.0", + "zone.js": "~0.15.0 || ~0.16.0" + }, + "peerDependenciesMeta": { + "@angular/compiler": { + "optional": true + }, + "zone.js": { + "optional": true + } + } + }, + "node_modules/@angular/forms": { + "version": "22.2.3", + "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-22.2.3.tgz", + "integrity": "sha512-TKP8FpeRCY/++vKWsY8GC1J2sNtEkdNNBPdgnMAMLTwheW5JzjwVatuQlbuZEx3WaAjbll1Ux3d+eHeqAVrtQg==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "tslib": "^2.3.0", + "zod": "^4.0.10" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@angular/common": "22.2.3", + "@angular/core": "22.2.3", + "@angular/platform-browser": "22.2.3", + "rxjs": "^6.5.3 || ^7.4.0" + } + }, + "node_modules/@angular/platform-browser": { + "version": "22.2.3", + "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-22.2.3.tgz", + "integrity": "sha512-eWZGsbG4bSrSg9UB/NE8wORGVrh1u+x6rirPGpMWqq/mTi6q+nS+pnPxAxmiEs8wmPH5nCz5b2pRKQeYUkhAGA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@angular/animations": "22.2.3", + "@angular/common": "22.2.3", + "@angular/core": "22.2.3" + }, + "peerDependenciesMeta": { + "@angular/animations": { + "optional": true + } + } + }, + "node_modules/@angular/router": { + "version": "22.2.3", + "resolved": "https://registry.npmjs.org/@angular/router/-/router-22.2.3.tgz", + "integrity": "sha512-h4C3iJ3OXM9HItErmTo9fFrFRDj1DSqbvweHAWl8eYJvyuhDD80gBNgdpN8/5gpt9K1HV+PXk0YbyjyQ0zMfPA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@angular/common": "22.2.3", + "@angular/core": "22.2.3", + "@angular/platform-browser": "22.2.3", + "rxjs": "^6.5.3 || ^7.4.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.6.tgz", + "integrity": "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^8.0.6", + "js-tokens": "^10.0.0" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-8.0.5.tgz", + "integrity": "sha512-YLsYoQMvL8l8WrGpN3Zj7O1wK5LEBN+cQtux7BcuHyxIXve724XG+zuJ1n3U1cUweRtTzQOA4IHbuQw3N34SZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/core": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-8.0.5.tgz", + "integrity": "sha512-2/oWkgTbBYoqioCWAE4XJobOrzwxTDa5/XjDP3tJ1BhDr/owcd9qnXBp4xc3/2G5X4bvXM04nrxbRJxFcXAxFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^8.0.0", + "@babel/generator": "^8.0.5", + "@babel/helper-compilation-targets": "^8.0.5", + "@babel/helpers": "^8.0.5", + "@babel/parser": "^8.0.5", + "@babel/template": "^8.0.0", + "@babel/traverse": "^8.0.5", + "@babel/types": "^8.0.5", + "@types/gensync": "^1.0.5", + "convert-source-map": "^2.0.0", + "empathic": "^2.0.1", + "gensync": "^1.0.0-beta.2", + "import-meta-resolve": "^4.2.0", + "json5": "^2.2.3", + "obug": "^2.1.1", + "verkit": "^0.3.2" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/generator": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.0.6.tgz", + "integrity": "sha512-/pcanjdRsonCexCuxgGD8fKnBLLzk2i9uM4kmcmGyyev2R5YDs+rafMYZ89RvaGY1mW8T7C5au0TyYaEeHBGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^8.0.6", + "@babel/types": "^8.0.6", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", + "jsesc": "^3.0.2" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-8.0.7.tgz", + "integrity": "sha512-ilAZCdOOlOVA7dQbaFNw2f/59p6GW33NxTopc3DvEE3efp3ZXTrGX/yZScaKw8/vd9bq31Ag0EcXiLw32bAgJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^8.0.5", + "@babel/helper-validator-option": "^8.0.0", + "browserslist": "^4.24.0", + "flru": "1.0.2", + "verkit": "^0.5.0" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/verkit": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/verkit/-/verkit-0.5.0.tgz", + "integrity": "sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/@babel/helper-globals": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.6.tgz", + "integrity": "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.8.tgz", + "integrity": "sha512-fVM+gSuKbdv9cpmyRNh5EvsDHUZCdxQH3FdnFKSkNYHpbsn95bbrxm+ES3MVeQjcqwi2O5ur/DjLfmTQaO60ng==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz", + "integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-8.0.0.tgz", + "integrity": "sha512-U4Dybxh4WESWHt5XhBeExi4DrY0/DNK1aHpQbsrQXCUbFHuMweT0TpLEWKvaraV2Y6fS+ZXunsZ8zIuZIgvF2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/helpers": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-8.0.8.tgz", + "integrity": "sha512-FBmhiDWs625wHg03OKiLQDeT6LOc2lWBbW97Yqs2iI1tZcucjpmYnO29NHsQ83XxKvredcvUymW/AAn2UtnakA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.8" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/parser": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.8.tgz", + "integrity": "sha512-Gq65JogAr0S2p0BzvfSJboyuiRnxDQApyOqHkKmkrvm+VlLK4gC3pKsiOKEdnhFBemrFbSnOu90mZZWDpiJnmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^8.0.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/template": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.0.0.tgz", + "integrity": "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^8.0.0", + "@babel/parser": "^8.0.0", + "@babel/types": "^8.0.0" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/traverse": { + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.0.7.tgz", + "integrity": "sha512-bVV0brinsTWgc6ptSIoQo3GbITtl0VZAqEUJbHHcyfDPEu+q/fEvlYEa+6H85HoK8IdksKBFtKJbJFZ6Kff+zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.0.6", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.0.7", + "@babel/template": "^8.0.0", + "@babel/types": "^8.0.6", + "obug": "^3.0.0" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/traverse/node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/@babel/types": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.8.tgz", + "integrity": "sha512-iXSSZAKQWmaeAwGtFw10v9fg5hUiUs0L+w+Z2K11kym3pDNK+SF0VcAQPsEFvWcTSZ7LMgClMXDBvTbH0IlICg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^8.0.8", + "@babel/helper-validator-identifier": "^8.0.6" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@bufbuild/protobuf": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.16.0.tgz", + "integrity": "sha512-FWa0sPlqYGJgpTs6OxBRcL/AW4JT0OIO+W1ajerluoTVh8CV0B7XM1qsNCRgnkSCkRCgOICKHRQlY17jrsm0+Q==", + "dev": true, + "license": "(Apache-2.0 AND BSD-3-Clause)" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@harperfast/extended-iterable": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@harperfast/extended-iterable/-/extended-iterable-1.0.5.tgz", + "integrity": "sha512-4ScXlphaKEa49RpHmqwATq9QI9aUTdWVYDlJkzxhsD7ShJP+pHCYLznMO9n/wREY8jPjRZ59wLJY6HM5yB5Gkw==", + "dev": true, + "license": "Apache-2.0", + "optional": true + }, + "node_modules/@inquirer/ansi": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.10.tgz", + "integrity": "sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/checkbox": { + "version": "5.2.8", + "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.2.8.tgz", + "integrity": "sha512-NY/S1EalQhlonqhwwsarrcnkH7s9ByQuvjWYdk1jB2Gb9EPQJjKkhCTWjM3yQ0UpHaLm1XbIL89b+32G8rhO5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.10", + "@inquirer/core": "^12.0.6", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/checkbox/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/confirm": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.3.2.tgz", + "integrity": "sha512-Xvr/0HggjddPtGppuqVmxhTw+Hr8PvsZ/k0HmOEaAqQEt80OITNkFWnsdNmyT0/eM4Ab+iJLx2R8rctlEyfSVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "12.0.6", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.0.6.tgz", + "integrity": "sha512-5yxn2LsJ8Tu4ei2a+yNkmFRhM/cb+JMEsEs/AW6CCOnBnpMy4IjYiPMFyHtYq8weOmlTyqqCx40y0DsD7OsEPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.10", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1", + "cli-width": "^4.1.0", + "fast-wrap-ansi": "^0.2.0", + "mute-stream": "^3.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/editor": { + "version": "5.3.6", + "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.3.6.tgz", + "integrity": "sha512-Z5SOeRC5VNkINfKN4rY8BSaYKb3GYi8iSEqZZRqogsE2GhBBToQ0Xw25SbI+4bcatLzU009mZ5d9EuJNiJuUCg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/external-editor": "^3.0.7", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/editor/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/expand": { + "version": "5.1.8", + "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.8.tgz", + "integrity": "sha512-dMEnTkpLqzM/sbILwL7QJgx9iX5hoEM8+bh6shgwd9mYJamdOnth7y2mMaFd08Glj9AXEFKllWcGYyBqnJsHrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/expand/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.7.tgz", + "integrity": "sha512-enNqTJpojgISCG+a5acjnfJ02hcRTFUBVm8uXiCY40PRPZtSzFnNLskOTU+kDUUEODYma90syxuea1rRtUFh0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^2.1.1", + "iconv-lite": "^0.7.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/figures": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.10.tgz", + "integrity": "sha512-51elrUJV3jZpvD0ygz8+U10Kc6+Lzqln+/tYmnbhy6jo5oXpE6hMCcv+OTBC0enwJXsb3JIuT3VtEinRNCSK2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/input": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.1.9.tgz", + "integrity": "sha512-2Vd5T7lTxfgJMpAd3aOu6bQpbUnCU7tBgvTQIZkP/7juJzmRmTM2t5XfOCuirFduWLTSJI/WZp32Cq1E01TVeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/input/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/number": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.2.6.tgz", + "integrity": "sha512-22LnGGCDm1M/pKXxxF8n6ppr/1IztdsxqeqeBRUMTTNnJTkjIBiAkewiDM4u/gjtazj/FvZS+nk9AbO/vEcBFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/number/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/password": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.2.5.tgz", + "integrity": "sha512-0v0wLQA4uhWbybmdH6oPl7ooxCiymNylkvi2gCSc+mA5ZQB6QoJLVhoHq12T82lhozpp9fpMJnJkC1nJrU/A+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.10", + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/password/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/prompts": { + "version": "8.7.2", + "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.7.2.tgz", + "integrity": "sha512-QoRB4wFIjgH5iOhSjoIKMkTvSHDuV+O3OITlIqAYO0oK5x364GJILXiMBvlPiE+klg7Xx9tq5XVqQHcGUDYYPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^5.2.5", + "@inquirer/confirm": "^6.3.2", + "@inquirer/editor": "^5.3.3", + "@inquirer/expand": "^5.1.5", + "@inquirer/input": "^5.1.6", + "@inquirer/number": "^4.2.3", + "@inquirer/password": "^5.2.2", + "@inquirer/rawlist": "^5.3.5", + "@inquirer/search": "^4.3.3", + "@inquirer/select": "^5.2.5" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/rawlist": { + "version": "5.3.8", + "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.3.8.tgz", + "integrity": "sha512-h+6Y4pPvYvuRbksn1kIBdD9tCYD+E468W5sIcVfLmoLP5IasnY0r33N+r+46ej/P8b2PCREjyKR+MnnfPGdTzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/rawlist/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/search": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.3.6.tgz", + "integrity": "sha512-JZj9ttkIvuaFQIc2oxsyqC1ad05WL02ku6W/INVKTCzNaVq1KkhP3AfTRC0m7OWlKZyw+EWwPBFZfYiG9jF6Yw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.6", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/search/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select": { + "version": "5.2.8", + "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.8.tgz", + "integrity": "sha512-BklkkAAOpjdCfuQw5fVGcDuhKxA7T1iBpn6b2JUvDDdkIsO3Ftlg+WnWUCVpkUBFagL2o036OFW+xL4lC9wIPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.10", + "@inquirer/core": "^12.0.6", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select/node_modules/@inquirer/type": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/type": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.1.1.tgz", + "integrity": "sha512-yJoHYrMnxIsJZCY+0Vb66Dy3he3kL3e2wOBKhoSwWWAzZAY82emlxwgprCtp6yRixvNRNq9ztfRWQYPNr3Go7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@listr2/prompt-adapter-inquirer": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/@listr2/prompt-adapter-inquirer/-/prompt-adapter-inquirer-4.2.7.tgz", + "integrity": "sha512-k180vxSv2KqmnDxoato6pCqEJsov4U5C0EVmldZkAdNeVBxY48A/LM6TCNPGIzDK/iZSfsZP0Mw+gbWc5hXLyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=22.13.0" + }, + "peerDependencies": { + "@inquirer/prompts": ">= 3 < 9", + "listr2": "11.1.0" + } + }, + "node_modules/@lmdb/lmdb-darwin-arm64": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/@lmdb/lmdb-darwin-arm64/-/lmdb-darwin-arm64-3.5.6.tgz", + "integrity": "sha512-mY5FG4TjPAkY4P0w+OhHaUka5mDh2TX2WKYIwuKzJ1zeW3VvRgxdam/lGJTquI+bthTx5CSHDW+BAQCnNAzkEA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lmdb/lmdb-darwin-x64": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/@lmdb/lmdb-darwin-x64/-/lmdb-darwin-x64-3.5.6.tgz", + "integrity": "sha512-foa+pwitysO8k+xhs7psBFfTKnVgR69NlZRRTHaFVDqphh7AdGpLeyRzKw/ofatr/sN6TiHRRW6mmop0ZrrppQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lmdb/lmdb-linux-arm": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/@lmdb/lmdb-linux-arm/-/lmdb-linux-arm-3.5.6.tgz", + "integrity": "sha512-QR4YRyR5h5Z8eGXrNQjiyo2NNDfqi3tCc9dQG5Is1blCt+qWw1ZoBWhlWAr5d+jshkifMIJjVHzHGKbkKzF8Tw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lmdb/lmdb-linux-arm64": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/@lmdb/lmdb-linux-arm64/-/lmdb-linux-arm64-3.5.6.tgz", + "integrity": "sha512-HmiyFFdJa38s1heCMSooSPaBSFTHJ3C+ERPp28xAPlDX1YiALJVOgbry065nXd8Y7KISWjnw05zpG1RX8IfftA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lmdb/lmdb-linux-x64": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/@lmdb/lmdb-linux-x64/-/lmdb-linux-x64-3.5.6.tgz", + "integrity": "sha512-ADzCuCF2cTNiX9kDScqcz1fjnAkxPpQNneV3KFTdV3wWtVlI2sTGzySoMTgDpinkMMFj1NTJlxA6XR8fwc4hlA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lmdb/lmdb-win32-arm64": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/@lmdb/lmdb-win32-arm64/-/lmdb-win32-arm64-3.5.6.tgz", + "integrity": "sha512-J7A9aEQsQiv0TYtBGL7NDIPp2lOS8nnl+zm4sWZm1xlsTTaQ4PgD096Adzdrk27rw3UxCkDXdCUa4ax41oztBQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@lmdb/lmdb-win32-x64": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/@lmdb/lmdb-win32-x64/-/lmdb-win32-x64-3.5.6.tgz", + "integrity": "sha512-1g7G0knRX2iV/voDu54yxrGqw5Dk0w2oIYb7dgJq8IkOi+m7wbD8Q3QpPFjh0C01G58S88dqGn03len6UPCXsg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz", + "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz", + "integrity": "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.3.1", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz", + "integrity": "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.4.tgz", + "integrity": "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.4.tgz", + "integrity": "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.4.tgz", + "integrity": "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.4.tgz", + "integrity": "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.4.tgz", + "integrity": "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@napi-rs/nice": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz", + "integrity": "sha512-xJIPs+bYuc9ASBl+cvGsKbGrJmS6fAKaSZCnT0lhahT5rhA2VVy9/EcIgd2JhtEuFOJNx7UHNn/qiTPTY4nrQw==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "optionalDependencies": { + "@napi-rs/nice-android-arm-eabi": "1.1.1", + "@napi-rs/nice-android-arm64": "1.1.1", + "@napi-rs/nice-darwin-arm64": "1.1.1", + "@napi-rs/nice-darwin-x64": "1.1.1", + "@napi-rs/nice-freebsd-x64": "1.1.1", + "@napi-rs/nice-linux-arm-gnueabihf": "1.1.1", + "@napi-rs/nice-linux-arm64-gnu": "1.1.1", + "@napi-rs/nice-linux-arm64-musl": "1.1.1", + "@napi-rs/nice-linux-ppc64-gnu": "1.1.1", + "@napi-rs/nice-linux-riscv64-gnu": "1.1.1", + "@napi-rs/nice-linux-s390x-gnu": "1.1.1", + "@napi-rs/nice-linux-x64-gnu": "1.1.1", + "@napi-rs/nice-linux-x64-musl": "1.1.1", + "@napi-rs/nice-openharmony-arm64": "1.1.1", + "@napi-rs/nice-win32-arm64-msvc": "1.1.1", + "@napi-rs/nice-win32-ia32-msvc": "1.1.1", + "@napi-rs/nice-win32-x64-msvc": "1.1.1" + } + }, + "node_modules/@napi-rs/nice-android-arm-eabi": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-android-arm-eabi/-/nice-android-arm-eabi-1.1.1.tgz", + "integrity": "sha512-kjirL3N6TnRPv5iuHw36wnucNqXAO46dzK9oPb0wj076R5Xm8PfUVA9nAFB5ZNMmfJQJVKACAPd/Z2KYMppthw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-android-arm64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-android-arm64/-/nice-android-arm64-1.1.1.tgz", + "integrity": "sha512-blG0i7dXgbInN5urONoUCNf+DUEAavRffrO7fZSeoRMJc5qD+BJeNcpr54msPF6qfDD6kzs9AQJogZvT2KD5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-darwin-arm64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-darwin-arm64/-/nice-darwin-arm64-1.1.1.tgz", + "integrity": "sha512-s/E7w45NaLqTGuOjC2p96pct4jRfo61xb9bU1unM/MJ/RFkKlJyJDx7OJI/O0ll/hrfpqKopuAFDV8yo0hfT7A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-darwin-x64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-darwin-x64/-/nice-darwin-x64-1.1.1.tgz", + "integrity": "sha512-dGoEBnVpsdcC+oHHmW1LRK5eiyzLwdgNQq3BmZIav+9/5WTZwBYX7r5ZkQC07Nxd3KHOCkgbHSh4wPkH1N1LiQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-freebsd-x64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-freebsd-x64/-/nice-freebsd-x64-1.1.1.tgz", + "integrity": "sha512-kHv4kEHAylMYmlNwcQcDtXjklYp4FCf0b05E+0h6nDHsZ+F0bDe04U/tXNOqrx5CmIAth4vwfkjjUmp4c4JktQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-arm-gnueabihf": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-arm-gnueabihf/-/nice-linux-arm-gnueabihf-1.1.1.tgz", + "integrity": "sha512-E1t7K0efyKXZDoZg1LzCOLxgolxV58HCkaEkEvIYQx12ht2pa8hoBo+4OB3qh7e+QiBlp1SRf+voWUZFxyhyqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-arm64-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-arm64-gnu/-/nice-linux-arm64-gnu-1.1.1.tgz", + "integrity": "sha512-CIKLA12DTIZlmTaaKhQP88R3Xao+gyJxNWEn04wZwC2wmRapNnxCUZkVwggInMJvtVElA+D4ZzOU5sX4jV+SmQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-arm64-musl": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-arm64-musl/-/nice-linux-arm64-musl-1.1.1.tgz", + "integrity": "sha512-+2Rzdb3nTIYZ0YJF43qf2twhqOCkiSrHx2Pg6DJaCPYhhaxbLcdlV8hCRMHghQ+EtZQWGNcS2xF4KxBhSGeutg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-ppc64-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-ppc64-gnu/-/nice-linux-ppc64-gnu-1.1.1.tgz", + "integrity": "sha512-4FS8oc0GeHpwvv4tKciKkw3Y4jKsL7FRhaOeiPei0X9T4Jd619wHNe4xCLmN2EMgZoeGg+Q7GY7BsvwKpL22Tg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-riscv64-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-riscv64-gnu/-/nice-linux-riscv64-gnu-1.1.1.tgz", + "integrity": "sha512-HU0nw9uD4FO/oGCCk409tCi5IzIZpH2agE6nN4fqpwVlCn5BOq0MS1dXGjXaG17JaAvrlpV5ZeyZwSon10XOXw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-s390x-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-s390x-gnu/-/nice-linux-s390x-gnu-1.1.1.tgz", + "integrity": "sha512-2YqKJWWl24EwrX0DzCQgPLKQBxYDdBxOHot1KWEq7aY2uYeX+Uvtv4I8xFVVygJDgf6/92h9N3Y43WPx8+PAgQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-x64-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-x64-gnu/-/nice-linux-x64-gnu-1.1.1.tgz", + "integrity": "sha512-/gaNz3R92t+dcrfCw/96pDopcmec7oCcAQ3l/M+Zxr82KT4DljD37CpgrnXV+pJC263JkW572pdbP3hP+KjcIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-linux-x64-musl": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-linux-x64-musl/-/nice-linux-x64-musl-1.1.1.tgz", + "integrity": "sha512-xScCGnyj/oppsNPMnevsBe3pvNaoK7FGvMjT35riz9YdhB2WtTG47ZlbxtOLpjeO9SqqQ2J2igCmz6IJOD5JYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-openharmony-arm64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-openharmony-arm64/-/nice-openharmony-arm64-1.1.1.tgz", + "integrity": "sha512-6uJPRVwVCLDeoOaNyeiW0gp2kFIM4r7PL2MczdZQHkFi9gVlgm+Vn+V6nTWRcu856mJ2WjYJiumEajfSm7arPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-win32-arm64-msvc": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-win32-arm64-msvc/-/nice-win32-arm64-msvc-1.1.1.tgz", + "integrity": "sha512-uoTb4eAvM5B2aj/z8j+Nv8OttPf2m+HVx3UjA5jcFxASvNhQriyCQF1OB1lHL43ZhW+VwZlgvjmP5qF3+59atA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-win32-ia32-msvc": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-win32-ia32-msvc/-/nice-win32-ia32-msvc-1.1.1.tgz", + "integrity": "sha512-CNQqlQT9MwuCsg1Vd/oKXiuH+TcsSPJmlAFc5frFyX/KkOh0UpBLEj7aoY656d5UKZQMQFP7vJNa1DNUNORvug==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/nice-win32-x64-msvc": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/nice-win32-x64-msvc/-/nice-win32-x64-msvc-1.1.1.tgz", + "integrity": "sha512-vB+4G/jBQCAh0jelMTY3+kgFy00Hlx2f2/1zjMoH821IbplbWZOkLiTYXQkygNTzQJTq5cvwBDgn2ppHD+bglQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@oxc-parser/binding-android-arm-eabi": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.150.0.tgz", + "integrity": "sha512-oQef2Zu4Prz1KLKznz3HqZzU9uVoA5PMoDZuuLmqms7hKmKSAPzlaMnLllJq3t+rgKmfJJ2siPrpZfFrW06btw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-android-arm64": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm64/-/binding-android-arm64-0.150.0.tgz", + "integrity": "sha512-B6ofpoFiAUwIZ0MJ2IgHPvZK8FAtL4qzSZRwOkAKIfxEobE1mQC8nDdiFZj7pUaJiVUVCsfkMsBJKedzO8rZvA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-arm64": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-arm64/-/binding-darwin-arm64-0.150.0.tgz", + "integrity": "sha512-J+9IHKzx/bSz1JetOfD4zKXSK9sOm4/a7+0qomJODcTL6JsRXGeV/ZdkAPSIDydfFmWzYCraMlQEosSZEyBYkQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-x64": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-x64/-/binding-darwin-x64-0.150.0.tgz", + "integrity": "sha512-v6IPfcAcSYrBWXV5Tce1DmxDMXLhEYpIIWiRFPJopgCVscZdLaV4MRQOUxvL3usQlw+yrwYOjBFB9IwBx+jUiQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-freebsd-x64": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-freebsd-x64/-/binding-freebsd-x64-0.150.0.tgz", + "integrity": "sha512-AoR/4jD02HET0KO0yNT4nbTE+XJUxiO9jB1X/ycEjUE3WrIJ3IjV/Vf+gskhWLcqqeXfvNnkDtBR7epllAm88A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-gnueabihf": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.150.0.tgz", + "integrity": "sha512-A/hycCFjLUrCmLoL5O/vBp40ohlaXO1Ta3v5hqYZxicYFs129wZmgZJggcW4mYGYbZebQLhup+N8JjeQl8qwyw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-musleabihf": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.150.0.tgz", + "integrity": "sha512-pbqahg1Pkz7J4RKmXm30s/iQu99hv64ayXCu8P4p75HcEH5azOdR4eGqiB6lFGkFR3mMpzaYsSKLkS8oJbjmeQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-gnu": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.150.0.tgz", + "integrity": "sha512-HV11aRbBQGwqv8bEo+K/6qr88uB4fEe1mhXncMhlVCrj+WpBSraxrUzHaPVmeQRU6x6x8v/3DuCbbo93rpp+fw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-musl": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.150.0.tgz", + "integrity": "sha512-k6pVkJqALwtEuP4zukVhGRhdIy4+ofChUIUUsAHHyqDZlNsknmel3JjbggrJiWGaes6h/dIcWmEXsKW4SmK9oQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-ppc64-gnu": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.150.0.tgz", + "integrity": "sha512-tEFg39mw/rHO5n8GK2DR4ZMFfsPQZtnQIPbsIpjoQRomJc/2tRfsCSmCT6gNit+NZGoeJG5aH9ATDH5bf0WnoQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-gnu": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.150.0.tgz", + "integrity": "sha512-0JO7IFkoek6HqV589Menx3hJySNXi6quRhO4tq2P7kpEHKEXoDATnoPVUpn5B7gDH2KLkdo751N0uIrGJFCTCw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-musl": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.150.0.tgz", + "integrity": "sha512-7XPzREnyAS5wHU9aB+49Uaqgoo1gVCklHc3DRlc3fJy2tXD/eAJFN1QFz/crj+Ulup5P1+axNREF+/RGaB/IRA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-s390x-gnu": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.150.0.tgz", + "integrity": "sha512-7n7ZxcbRWDFaTdyj8M8p0O9OfzoMKm8O6syBAIgcSutbOALq0Bb9G52Me+XH0anMLZV+NgXc726gqgG2q39vcQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-gnu": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.150.0.tgz", + "integrity": "sha512-Vx0GSA9ZCRTUiczoEQnIIyXkMvtEY8uc6IiwLQtMe5ci2sXPqjrry0Ek5fsPP1k2kCzkML3ow9UOOEgnEDi7Bw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-musl": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-musl/-/binding-linux-x64-musl-0.150.0.tgz", + "integrity": "sha512-ii4/9m3viDLssMnfXU7/Pni/3nYplApuGayceX4qsVGaqqQJCx3tHIH9M/HWIeSty5i8LjS21zPYT6lVIkwLxw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-openharmony-arm64": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-openharmony-arm64/-/binding-openharmony-arm64-0.150.0.tgz", + "integrity": "sha512-ZtoxX5rez36ZWkwtiEhjkCPnlTPoQ2I7lIL0IYZ1yjxMYohbvoOjBmUIZzrf9W/HouONq0omIfTeCWEY+R380w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-arm64-msvc": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.150.0.tgz", + "integrity": "sha512-VqeRb5JX/bKYBrff7TUDvJyKY0914UzuCkuXIGxJS4FUmvMNfqkCbc7Sq90iMz9DlmAtlggwaBYQ9eg3h3ltiw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-ia32-msvc": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.150.0.tgz", + "integrity": "sha512-EPqJfeZ4Pgg2BJSsCV8GozxV0FDltRzpVtGVa1r2noJu1iu+opOw3gtBWXwIo9odCT/MdFfyHxdy0/CRqs3OqA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-x64-msvc": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.150.0.tgz", + "integrity": "sha512-n5YMzbqwPQqozbkrexi0lNZrUz5cnPHalYpFWe6Dau7AmKIWNo+y24IwzDuZEQtEdUHuKhXmMMih/MPjOI+CMw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.150.0.tgz", + "integrity": "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" + } + }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@redocly/ajv": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/@redocly/ajv/-/ajv-8.11.2.tgz", + "integrity": "sha512-io1JpnwtIcvojV7QKDUSIuMN/ikdOUd1ReEnUnMKGfDVridQZ31J0MmIuqwuRjWDZfmvr+Q0MqCcfHM2gTivOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js-replace": "^1.0.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@redocly/config": { + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/@redocly/config/-/config-0.22.0.tgz", + "integrity": "sha512-gAy93Ddo01Z3bHuVdPWfCwzgfaYgMdaZPcfL7JZ7hWJoK9V0lXDbigTWkhiPFAaLWzbOJ+kbUQG1+XwIm0KRGQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@redocly/openapi-core": { + "version": "1.34.22", + "resolved": "https://registry.npmjs.org/@redocly/openapi-core/-/openapi-core-1.34.22.tgz", + "integrity": "sha512-dEyx4uHh6Pc6ZkdU9Xe8rA4h12Odq6QKU/fqseBn07xwVwskhHiF3KHhqmw5BR+jAiFTvKTmwCafFql/k1pSzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@redocly/ajv": "8.11.2", + "@redocly/config": "0.22.0", + "colorette": "1.4.0", + "https-proxy-agent": "7.0.6", + "js-levenshtein": "1.1.6", + "js-yaml": "4.3.2", + "minimatch": "5.1.9", + "pluralize": "8.0.0", + "yaml-ast-parser": "0.0.43" + }, + "engines": { + "node": ">=18.17.0", + "npm": ">=9.5.0" + } + }, + "node_modules/@redocly/openapi-core/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/@redocly/openapi-core/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz", + "integrity": "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.8.tgz", + "integrity": "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.8.tgz", + "integrity": "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.8.tgz", + "integrity": "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.8.tgz", + "integrity": "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.8.tgz", + "integrity": "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.8.tgz", + "integrity": "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.8.tgz", + "integrity": "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.8.tgz", + "integrity": "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.8.tgz", + "integrity": "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.8.tgz", + "integrity": "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.8.tgz", + "integrity": "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.8.tgz", + "integrity": "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.8.tgz", + "integrity": "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.8.tgz", + "integrity": "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@schematics/angular": { + "version": "22.2.4", + "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-22.2.4.tgz", + "integrity": "sha512-3yXpeDsn780rk/Pm+2QjoGpvS03doyuB2i8jUt/tNtDatIIVoXUJak3kjPOK3TVorOJX/fTNMjMxDwQzvec2+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.2.4", + "@angular-devkit/schematics": "22.2.4", + "jsonc-parser": "3.3.1", + "oxc-parser": "0.150.0", + "typescript": "6.0.3" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@types/gensync": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/gensync/-/gensync-1.0.5.tgz", + "integrity": "sha512-MbsRCT7mTikHwKZ0X+LVUTLRrZZRLipTuXEO9qOYO+zmjMVk81axyClMROf6uoPD9MRVu46bx8zoR0Ad9q3NAg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/jsesc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@types/jsesc/-/jsesc-2.5.1.tgz", + "integrity": "sha512-9VN+6yxLOPLOav+7PwjZbxiID2bVaeq0ED4qSQmdQTdjnXJSaCVKTR58t15oqH1H5t8Ng2ZX1SabJVoN9Q34bw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitejs/plugin-basic-ssl": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-basic-ssl/-/plugin-basic-ssl-2.3.0.tgz", + "integrity": "sha512-bdyo8rB3NnQbikdMpHaML9Z1OZPBu6fFOBo+OtxsBlvMJtysWskmBcnbIDhUqgC8tcxNv/a+BcV5U+2nQMm1OQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "peerDependencies": { + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/agent-base": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", + "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-colors": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", + "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.34", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz", + "integrity": "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/beasties": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/beasties/-/beasties-0.5.4.tgz", + "integrity": "sha512-8/lOOjT+PElYCnaUbmhgd3Uad5R1VTQ4Wg0k4rK8bX04m5WEqHNmnlLy3Q/lJ7dk25XA+72gayzc/skTfKKpcA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "css-select": "^7.0.0", + "css-what": "^8.0.0", + "dom-serializer": "^3.0.0", + "domhandler": "^6.0.0", + "htmlparser2": "^12.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.49", + "postcss-media-query-parser": "^0.2.3", + "postcss-safe-parser": "^7.0.1" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/boolbase": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz", + "integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001819", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz", + "integrity": "sha512-LFUqIIAwpzsIuevnKnsR9qnStBcgzPShTX61lBwN9uFkkf8o8zLiebEjbW8AYtZiF+1YKDWfdt/pWDtMuG8Xwg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/change-case": { + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/change-case/-/change-case-5.4.4.tgz", + "integrity": "sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/chardet": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz", + "integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==", + "dev": true, + "license": "MIT" + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.4.0.tgz", + "integrity": "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-6.1.1.tgz", + "integrity": "sha512-06p9vyLahLa4zkGcgsGxU6iEkSOiuI4fhCH6Emhe2lPAcoUv73n72DnODsnHA+5wwXGnV0n9M9/qOQJSjYhFhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "slice-ansi": "^9.0.0", + "string-width": "^8.2.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/colorette": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", + "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/colorjs.io": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz", + "integrity": "sha512-LY7OHnJZxHwT5UlzNa9bbhHHDbzB6yE5+3MIPwJEQKRvSCt/T4G7epsj+9j2BExUIIfXFIJGsIXUKdfrK9Q5tA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/color" + } + }, + "node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/css-select": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz", + "integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^2.0.0", + "css-what": "^8.0.0", + "domhandler": "^6.0.1", + "domutils": "^4.0.2", + "nth-check": "^3.0.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz", + "integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dom-serializer": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", + "integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^3.0.0", + "domhandler": "^6.0.0", + "entities": "^8.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz", + "integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/domhandler": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz", + "integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^3.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz", + "integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^3.0.0", + "domelementtype": "^3.0.0", + "domhandler": "^6.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.467", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.467.tgz", + "integrity": "sha512-Nw9X371rtZmYcBSnEijnCDONILjs93biCZO34juC7MBOmK8E+GFnyD4T/WvyrlJkppul7oxg6TwvtKst9SODTw==", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/empathic": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.1.0.tgz", + "integrity": "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", + "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-width": "^3.0.2" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/flru": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", + "integrity": "sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hosted-git-info": { + "version": "10.1.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-10.1.1.tgz", + "integrity": "sha512-DeOnSPAvOndYKfw075gt8yZzQ7S2hNztw34zBTfhIzLhmBTswIBg5/y+pqu/VD5cYWm5goAFTusDmUEmKZ0PEQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/htmlparser2": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-12.0.0.tgz", + "integrity": "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw==", + "dev": true, + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^3.0.0", + "domhandler": "^6.0.0", + "domutils": "^4.0.2", + "entities": "^8.0.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz", + "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/immutable": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.9.tgz", + "integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==", + "dev": true, + "license": "MIT" + }, + "node_modules/import-meta-resolve": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/index-to-position": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/index-to-position/-/index-to-position-1.2.0.tgz", + "integrity": "sha512-Yg7+ztRkqslMAS2iFaU+Oa4KTSidr63OsFGlOrJoW981kIYO3CGCS3wA95P1mUi/IVSJkn0D479KTJpVpvFNuw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", + "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/js-levenshtein": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/js-levenshtein/-/js-levenshtein-1.1.6.tgz", + "integrity": "sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/listr2": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-11.1.0.tgz", + "integrity": "sha512-xsuczF6mWkEo/E80QHaEokQzKmTy7m80KcLRnkUt9wrcePres2w7dbQi5zOsWtDUg8Dac4gPFyu4EJ/IvKwTOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cli-truncate": "^6.1.1", + "log-update": "^8.0.0", + "wrap-ansi": "^10.0.1" + }, + "engines": { + "node": ">=22.13.0" + } + }, + "node_modules/lmdb": { + "version": "3.5.6", + "resolved": "https://registry.npmjs.org/lmdb/-/lmdb-3.5.6.tgz", + "integrity": "sha512-j3uE8ReKNyUWDjhfEFSJqE/1DLtfTR5Z8yFzVHvBjAk37wNg7HdScjcv8ttPHRvrdgPQMPWxFFI0SsdBzI5lBw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@harperfast/extended-iterable": "^1.0.3", + "msgpackr": "^1.11.2", + "node-addon-api": "^6.1.0", + "node-gyp-build-optional-packages": "5.2.2", + "ordered-binary": "^1.5.3", + "weak-lru-cache": "^1.2.2" + }, + "bin": { + "download-lmdb-prebuilds": "bin/download-prebuilds.js" + }, + "optionalDependencies": { + "@lmdb/lmdb-darwin-arm64": "3.5.6", + "@lmdb/lmdb-darwin-x64": "3.5.6", + "@lmdb/lmdb-linux-arm": "3.5.6", + "@lmdb/lmdb-linux-arm64": "3.5.6", + "@lmdb/lmdb-linux-x64": "3.5.6", + "@lmdb/lmdb-win32-arm64": "3.5.6", + "@lmdb/lmdb-win32-x64": "3.5.6" + } + }, + "node_modules/lmdb/node_modules/node-addon-api": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", + "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/log-symbols": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-7.0.1.tgz", + "integrity": "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0", + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-8.0.0.tgz", + "integrity": "sha512-lddSgOt3bPASrylL54ZSpy8nBHns+vBVSoILlVOx+dei300pnLRN958rj/EdlVLKuWlSESU3qdnDZdAI7FXYGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.3.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^9.0.0", + "string-width": "^8.2.0", + "strip-ansi": "^7.2.0", + "wrap-ansi": "^10.0.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/magic-string": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.1.tgz", + "integrity": "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mrmime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", + "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/msgpackr": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-1.12.1.tgz", + "integrity": "sha512-4EUH9tQHnMmEgzW/MdAP0KIfa1T9AF+htl0ffe2n5vb2EKn9y2co8ccpgWko6S52Jy1PQZKwRnx5/KkYjtd9MQ==", + "dev": true, + "license": "MIT", + "optional": true, + "optionalDependencies": { + "msgpackr-extract": "^3.0.2" + } + }, + "node_modules/msgpackr-extract": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.4.tgz", + "integrity": "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "node-gyp-build-optional-packages": "5.2.2" + }, + "bin": { + "download-msgpackr-prebuilds": "bin/download-prebuilds.js" + }, + "optionalDependencies": { + "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" + } + }, + "node_modules/mute-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", + "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-gyp-build-optional-packages": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz", + "integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.1" + }, + "bin": { + "node-gyp-build-optional-packages": "bin.js", + "node-gyp-build-optional-packages-optional": "optional.js", + "node-gyp-build-optional-packages-test": "build-test.js" + } + }, + "node_modules/node-releases": { + "version": "2.0.60", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.60.tgz", + "integrity": "sha512-OmO8+GM1JUZqXET720VrJCwkjUCXmCMQm0Z3UDDRbfNLHS4NEAvY60j5jiFv0tkKw2PNNlqOLhahVmwJIOLDIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/npm-package-arg": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-14.0.0.tgz", + "integrity": "sha512-69XQh3k+dtGa1p+7RaR57IuG3rCko96xr/nUfN4yDYBXbTYICiWcOpsFKLN2GtGE9cyIljE+f1exnaYt9MvM+Q==", + "dev": true, + "license": "ISC", + "dependencies": { + "hosted-git-info": "^10.1.0", + "proc-log": "^7.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^8.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/nth-check": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz", + "integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^2.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/openapi-typescript": { + "version": "7.13.0", + "resolved": "https://registry.npmjs.org/openapi-typescript/-/openapi-typescript-7.13.0.tgz", + "integrity": "sha512-EFP392gcqXS7ntPvbhBzbF8TyBA+baIYEm791Hy5YkjDYKTnk/Tn5OQeKm5BIZvJihpp8Zzr4hzx0Irde1LNGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@redocly/openapi-core": "^1.34.6", + "ansi-colors": "^4.1.3", + "change-case": "^5.4.4", + "parse-json": "^8.3.0", + "supports-color": "^10.2.2", + "yargs-parser": "^21.1.1" + }, + "bin": { + "openapi-typescript": "bin/cli.js" + }, + "peerDependencies": { + "typescript": "^5.x" + } + }, + "node_modules/ora": { + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-9.4.1.tgz", + "integrity": "sha512-6VlU9MLXbjVQD04AZCMX28hVtA5bUoadvUqO76MUCVA0ilwJbMiHsITRPfyVm6p/BC0Av/BXMujx39WCe1LEqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.6.2", + "cli-cursor": "^5.0.0", + "cli-spinners": "^3.2.0", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^2.1.0", + "log-symbols": "^7.0.1", + "stdin-discarder": "^0.3.2", + "string-width": "^8.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ordered-binary": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/ordered-binary/-/ordered-binary-1.6.3.tgz", + "integrity": "sha512-Bc8LnA2x4ZHRQ9LjCm/NOdD3+CTQPhGNu8m7/6+ERtiB6Bb/fn7nCySwcmAC+5WCqwelpSAQgo1VX9BGpsC0tQ==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/oxc-parser": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/oxc-parser/-/oxc-parser-0.150.0.tgz", + "integrity": "sha512-zwajKw1GUa57IOdafIS7/yOObGF2NihwIfZfs5yJTRprMSkiwhWOc/k+n8bwnUPbHr2/XsjfBO8KyTPaW3VpWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "^0.150.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxc-parser/binding-android-arm-eabi": "0.150.0", + "@oxc-parser/binding-android-arm64": "0.150.0", + "@oxc-parser/binding-darwin-arm64": "0.150.0", + "@oxc-parser/binding-darwin-x64": "0.150.0", + "@oxc-parser/binding-freebsd-x64": "0.150.0", + "@oxc-parser/binding-linux-arm-gnueabihf": "0.150.0", + "@oxc-parser/binding-linux-arm-musleabihf": "0.150.0", + "@oxc-parser/binding-linux-arm64-gnu": "0.150.0", + "@oxc-parser/binding-linux-arm64-musl": "0.150.0", + "@oxc-parser/binding-linux-ppc64-gnu": "0.150.0", + "@oxc-parser/binding-linux-riscv64-gnu": "0.150.0", + "@oxc-parser/binding-linux-riscv64-musl": "0.150.0", + "@oxc-parser/binding-linux-s390x-gnu": "0.150.0", + "@oxc-parser/binding-linux-x64-gnu": "0.150.0", + "@oxc-parser/binding-linux-x64-musl": "0.150.0", + "@oxc-parser/binding-openharmony-arm64": "0.150.0", + "@oxc-parser/binding-win32-arm64-msvc": "0.150.0", + "@oxc-parser/binding-win32-ia32-msvc": "0.150.0", + "@oxc-parser/binding-win32-x64-msvc": "0.150.0" + } + }, + "node_modules/parse-json": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-8.3.0.tgz", + "integrity": "sha512-ybiGyvspI+fAoRQbIPRddCcSTV9/LsJbf0e/S85VLowVGzRmokfneg2kwVW/KU5rOXrPSbF1qAKPMgNTqqROQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.26.2", + "index-to-position": "^1.1.0", + "type-fest": "^4.39.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-json/node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/parse-json/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/parse-json/node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-html-rewriting-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5-html-rewriting-stream/-/parse5-html-rewriting-stream-8.0.1.tgz", + "integrity": "sha512-NaRku2aMpUN1Sh1Gyk1KWUh2A7EJx2c6qYzvwsPtqhoHoaURshdrceYK3LunVCm3WHhm6FS7Vcczbvdh3/UIVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0", + "parse5": "^8.0.0", + "parse5-sax-parser": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-sax-parser": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/parse5-sax-parser/-/parse5-sax-parser-8.0.0.tgz", + "integrity": "sha512-/dQ8UzHZwnrzs3EvDj6IkKrD/jIZyTlB+8XrHJvcjNgRdmWruNdN9i9RK/JtxakmlUdPwKubKPTCqvbTgzGhrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/piscina": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/piscina/-/piscina-5.3.2.tgz", + "integrity": "sha512-vv7l/mM7B9WgrhDaudIqv1x6v4LOBRYYmpWGdWushhpbCmVHp11sUB2v4hj1CAeTGXVxuZFz6xOU1RalAiPKfQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.x" + }, + "optionalDependencies": { + "@napi-rs/nice": "^1.0.4" + } + }, + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-media-query-parser": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/postcss-media-query-parser/-/postcss-media-query-parser-0.2.3.tgz", + "integrity": "sha512-3sOlxmbKcSHMjlUXQZKQ06jOswE7oVkXPxmZdoB1r5l0q6gTFTQSHxNxOrCccElbW7dxNytifNEo8qidX2Vsig==", + "dev": true, + "license": "MIT" + }, + "node_modules/postcss-safe-parser": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/postcss-safe-parser/-/postcss-safe-parser-7.1.0.tgz", + "integrity": "sha512-1WzZxRLaAFwEh6Do+zyGpjWV3nGJNxxhuh7Ubu/q1ICImMgZJnLwhoaEpRbG4pJppp2Y1ncL9ffA2f+LhrefQg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss-safe-parser" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/prettier": { + "version": "3.9.10", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", + "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/proc-log": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-7.0.0.tgz", + "integrity": "sha512-FYgfaA69XZ93zaXLoMNQ+ViDXGGBgR8aLh03txzcFhV+9xOXx7+8DLCULrKKpR9+GsH9ZfHm82aSUPpozX0Ztg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/proxy-agent-negotiate": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz", + "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + } + }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/rolldown": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz", + "integrity": "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.149.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.8", + "@rolldown/binding-android-arm64": "1.2.8", + "@rolldown/binding-darwin-arm64": "1.2.8", + "@rolldown/binding-darwin-x64": "1.2.8", + "@rolldown/binding-freebsd-x64": "1.2.8", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.8", + "@rolldown/binding-linux-arm64-gnu": "1.2.8", + "@rolldown/binding-linux-arm64-musl": "1.2.8", + "@rolldown/binding-linux-ppc64-gnu": "1.2.8", + "@rolldown/binding-linux-s390x-gnu": "1.2.8", + "@rolldown/binding-linux-x64-gnu": "1.2.8", + "@rolldown/binding-linux-x64-musl": "1.2.8", + "@rolldown/binding-openharmony-arm64": "1.2.8", + "@rolldown/binding-win32-arm64-msvc": "1.2.8", + "@rolldown/binding-win32-x64-msvc": "1.2.8" + } + }, + "node_modules/rolldown/node_modules/@oxc-project/types": { + "version": "0.149.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.149.0.tgz", + "integrity": "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/sass": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.104.1.tgz", + "integrity": "sha512-yDA+1aIG3EHgN4V/BvuhCvu61FF6hEd4e+9DxikUm9U0CAGuvdIZ/UYy7qbOxjhbbWQraoyLlMuzdRGOSV5Bmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "immutable": "^5.1.5", + "source-map-js": ">=0.6.2 <2.0.0" + }, + "bin": { + "sass": "sass.js" + }, + "engines": { + "node": ">=20.19.0" + }, + "optionalDependencies": { + "@parcel/watcher": "^2.4.1" + } + }, + "node_modules/sass-embedded": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded/-/sass-embedded-1.104.1.tgz", + "integrity": "sha512-7LxbtPJ1MWKVbhzOnGx1sHTkHTcHVJ9hbgVsU29p/8gY1VeXt19fcJFr5xsx2f6zfrrR3FeOcYMt0uYDLAxpgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bufbuild/protobuf": "^2.5.0", + "colorjs.io": "^0.7.0", + "immutable": "^5.1.5", + "rxjs": "^7.4.0", + "supports-color": "^8.1.1", + "sync-child-process": "^1.0.2", + "varint": "^6.0.0" + }, + "bin": { + "sass": "dist/bin/sass.js" + }, + "engines": { + "node": ">=20.19.0" + }, + "optionalDependencies": { + "sass-embedded-all-unknown": "1.104.1", + "sass-embedded-android-arm": "1.104.1", + "sass-embedded-android-arm64": "1.104.1", + "sass-embedded-android-riscv64": "1.104.1", + "sass-embedded-android-x64": "1.104.1", + "sass-embedded-darwin-arm64": "1.104.1", + "sass-embedded-darwin-x64": "1.104.1", + "sass-embedded-linux-arm": "1.104.1", + "sass-embedded-linux-arm64": "1.104.1", + "sass-embedded-linux-musl-arm": "1.104.1", + "sass-embedded-linux-musl-arm64": "1.104.1", + "sass-embedded-linux-musl-riscv64": "1.104.1", + "sass-embedded-linux-musl-x64": "1.104.1", + "sass-embedded-linux-riscv64": "1.104.1", + "sass-embedded-linux-x64": "1.104.1", + "sass-embedded-unknown-all": "1.104.1", + "sass-embedded-win32-arm64": "1.104.1", + "sass-embedded-win32-x64": "1.104.1" + } + }, + "node_modules/sass-embedded-all-unknown": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-all-unknown/-/sass-embedded-all-unknown-1.104.1.tgz", + "integrity": "sha512-toyMCyUKkT6DsYlHuKZGjd8T6WltaW4TGX07F7HnF4tNJM5m/8VaVsd74zrq3QSPqGE9JjxIDK4NrNc/QY9pkA==", + "cpu": [ + "!arm", + "!arm64", + "!riscv64", + "!x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "sass": "1.104.1" + } + }, + "node_modules/sass-embedded-android-arm": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-android-arm/-/sass-embedded-android-arm-1.104.1.tgz", + "integrity": "sha512-g/XPAJYAzSSQZFP4xCdGD0HLKB4mf24cJ/+5Nls8rMool3jNkBv9+AFO4EV0b+RxN8rLcEsMccH1CR64yIFYcQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-android-arm64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-android-arm64/-/sass-embedded-android-arm64-1.104.1.tgz", + "integrity": "sha512-yW3BVW4YFpN2vu2cVQ+Pz5JrRTvoIz36aCdo+J/Mo1A9gEN8eVPV/AL7aeZ803YdKgIitd3qw3pY4wpmT6TXNg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-android-riscv64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-android-riscv64/-/sass-embedded-android-riscv64-1.104.1.tgz", + "integrity": "sha512-ZYY8oMKQS7Q/6FBoC8w3T16O3MucDe3xv8iKym41Nht5uvLCGGpm4fC4OF5nlv7wQkJv8oactYddGG3Wd0Rqkg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-android-x64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-android-x64/-/sass-embedded-android-x64-1.104.1.tgz", + "integrity": "sha512-5WZKC4lSfjMIjzZdQUlYQUAV+UiatBhD8w28U7cYLLj4/dMgEPOBd4g3VMv0BwpgH2JOaycMS42dXq29W2bcDg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-darwin-arm64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-darwin-arm64/-/sass-embedded-darwin-arm64-1.104.1.tgz", + "integrity": "sha512-oatuHzn0NsEg0d9Dcze6CuWUPvuETtMxRK4cv0eRAg7p6R0vHnv5GZRyWG6gEy3nc/ha/L+GtTasWVU82f4jrQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-darwin-x64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-darwin-x64/-/sass-embedded-darwin-x64-1.104.1.tgz", + "integrity": "sha512-gql/5sHGzUTVwuHfM3QLCDeb6NYwen+LLj22gz81C2NKHF/4nUtDyh4N+fURWdT7J0/EhtMOd0+FLML3sGNP7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-arm": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-arm/-/sass-embedded-linux-arm-1.104.1.tgz", + "integrity": "sha512-WfmshPJOp9vUKxgp8wZ2ncaKBbyrlW9J51M2aUQHWECjMNxTULnGOHWSmD7FViXv4zwn1Co5FIFQUipW7RCxtA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-arm64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-arm64/-/sass-embedded-linux-arm64-1.104.1.tgz", + "integrity": "sha512-sVWUKXNTu8sP3X95Df0xo/t49Ce5IseTIMqXHxhFBKVmx7gf7kBWNLK0wH5ym+4khc+B5nNJPgq4IxpelG8tMQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-musl-arm": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-arm/-/sass-embedded-linux-musl-arm-1.104.1.tgz", + "integrity": "sha512-k0cQ/CxBzFVYiQEObg6CpF6CUglkdEhi/DZgZXQbwC27kbGGY+fatmIs/cFPJL2z1ulACwoAr86RQUFzYvw5eg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-musl-arm64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-arm64/-/sass-embedded-linux-musl-arm64-1.104.1.tgz", + "integrity": "sha512-H7b+LzZ/w8pwNExInM8HDHraqvxCMdUc5ZRGU/aSJJhZ9HjeRKBjF3GxaisVHnx7o18j1l4VQ5cLBL9tTmNzZw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-musl-riscv64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-riscv64/-/sass-embedded-linux-musl-riscv64-1.104.1.tgz", + "integrity": "sha512-9DYdn4wfrkidjxJVtEd2iCx8HKdZe+uF82GDmrYEZhgu4NjVE6a4fQyW7OLwzn3erZMHKBaObBOH1d37DnXI1A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-musl-x64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-x64/-/sass-embedded-linux-musl-x64-1.104.1.tgz", + "integrity": "sha512-5xz+nAr01b6yaRdrGVgE7lNvm1lGFjwNdUvnz+teidvHCbD5oTcbhrRVrnDoLHHvq5n3Jve9TzWaaHhezaEfHA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-riscv64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-riscv64/-/sass-embedded-linux-riscv64-1.104.1.tgz", + "integrity": "sha512-oWryPJWTXK5adtlz/FD7wd2kS4I0CEgp6mWLUVb4oMFURMLz9bA9fO87D7lc4SV++lds7T51PU1kykCbOvNHMg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-linux-x64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-linux-x64/-/sass-embedded-linux-x64-1.104.1.tgz", + "integrity": "sha512-j/sX/yKTx/wJKepC5/ISlR6kPeSuHKThf76D2za5i2VnbHg0MN19jQq3WMorowR3kRghqt6azs3awogG+e7IRA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-unknown-all": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-unknown-all/-/sass-embedded-unknown-all-1.104.1.tgz", + "integrity": "sha512-RaMsYZB5mRioL4qhoI7T5mmNb2OunakbPTJW2cuu3MeIULnGoxo7Wd5QKFxeQvF7sSQL57RuaQ+q9pH+/pQ9Fg==", + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "!android", + "!darwin", + "!linux", + "!win32" + ], + "dependencies": { + "sass": "1.104.1" + } + }, + "node_modules/sass-embedded-win32-arm64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-win32-arm64/-/sass-embedded-win32-arm64-1.104.1.tgz", + "integrity": "sha512-fS6DL7lcnTPclqGLF4xRt8egZlFY9cU23d57ufbWqaUbCFu9JTu0+8qB4jMxfx1la6byi3GoSTfbnNOLfWv8sw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded-win32-x64": { + "version": "1.104.1", + "resolved": "https://registry.npmjs.org/sass-embedded-win32-x64/-/sass-embedded-win32-x64-1.104.1.tgz", + "integrity": "sha512-/c4N2A93Ckms6DuRFVftKYISuI1tyC8gmlVJ8WaWFzgCBN/Swq2rARJIBUNeuxlmxjmYXfd3+2f/u887K63wbA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/sass-embedded/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slice-ansi": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-9.0.1.tgz", + "integrity": "sha512-aBY19bn/XA+hKOKX0qL7Z0UfdBsbQvc9hn993U8ALUjzxCvDcuZqLoRXjGJrUARWAlwMnsRVD9sw2AFNOYvalA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.3", + "is-fullwidth-code-point": "^5.1.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/source-map": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0.tgz", + "integrity": "sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stdin-discarder": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.3.2.tgz", + "integrity": "sha512-eCPu1qRxPVkl5605OTWF8Wz40b4Mf45NY5LQmVPQ599knfs5QhASUm9GbJ5BDMDOXgrnh0wyEdvzmL//YMlw0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/sync-child-process": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/sync-child-process/-/sync-child-process-1.1.1.tgz", + "integrity": "sha512-54zMOnH5qgjdKW8SGpCx3daSP+v+TtTfOxgPdhUE3P0hytMMpknZfP67S4JeRcx5IQRWJERz6890yO4dkTywww==", + "dev": true, + "license": "MIT", + "dependencies": { + "sync-message-port": "^1.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/sync-message-port": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/sync-message-port/-/sync-message-port-1.2.0.tgz", + "integrity": "sha512-gAQ9qrUN/UCypHtGFbbe7Rc/f9bzO88IwrG8TDo/aMKAApKyD6E3W4Cm0EfhfBb6Z6SKt59tTCTfD+n1xmAvMg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js-replace": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uri-js-replace/-/uri-js-replace-1.0.2.tgz", + "integrity": "sha512-VeBBt/nMxedczht3KDL2yBBMJqIxpCQLMZp3UJ1otcWwUHdQW4IiyHpJivExzSK+FdxTowRfGL4FmwDqH9+S8Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/validate-npm-package-name": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-8.0.0.tgz", + "integrity": "sha512-SCv6OOV6Xj2/3cXy3dGmADluJTNcL3o7hZAglNPTe+WYuEuvxgJzxPrSDLZhF+CwyQOubqgecjMmTJGMVLWjYQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/varint": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/varint/-/varint-6.0.0.tgz", + "integrity": "sha512-cXEIW6cfr15lFv563k4GuVuW/fiwjknytD37jIOLSdSWuOI6WnO/oKwmP2FQTU2l01LP8/M5TSAJpzUaGe3uWg==", + "dev": true, + "license": "MIT" + }, + "node_modules/verkit": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/verkit/-/verkit-0.3.2.tgz", + "integrity": "sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/vite": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz", + "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.6", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/weak-lru-cache": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/weak-lru-cache/-/weak-lru-cache-1.2.2.tgz", + "integrity": "sha512-DEAoo25RfSYMuTGc9vPJzZcZullwIqRDSI9LOy+fkCJPi6hykCnfKaXTuPBDuXAUcqHXyOgFtHNp/kB2FjYHbw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/wrap-ansi": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-10.0.2.tgz", + "integrity": "sha512-6OLRNZqRntVGBm26ghZ5eZhCuWWyOkRCSn8XsOIuq5stpCE/tjLbdozd93naILZig0lmD8ANfRwnhn0DLeXGlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.3", + "string-width": "^8.2.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/xxhash-wasm": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz", + "integrity": "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==", + "dev": true, + "license": "MIT" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yaml-ast-parser": { + "version": "0.0.43", + "resolved": "https://registry.npmjs.org/yaml-ast-parser/-/yaml-ast-parser-0.0.43.tgz", + "integrity": "sha512-2PTINUwsRqSd+s8XxKaJWQlUuEMHJQyEuh2edBbW8KNJz0SJPwUSD2zRWqezFEdN7IzAgeuYHFUCF7o8zRdZ0A==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/yargs": { + "version": "18.1.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.1.0.tgz", + "integrity": "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs/node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yoctocolors": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", + "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.6.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.6.tgz", + "integrity": "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/samples/BaGet.Frontend.Angular/package.json b/samples/BaGet.Frontend.Angular/package.json new file mode 100644 index 000000000..121166cbc --- /dev/null +++ b/samples/BaGet.Frontend.Angular/package.json @@ -0,0 +1,31 @@ +{ + "name": "baget-frontend-angular", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "gen:api": "openapi-typescript openapi/ui.json -o src/app/api/schema.d.ts", + "smoke": "node scripts/smoke.mjs" + }, + "private": true, + "packageManager": "npm@10.9.9", + "dependencies": { + "@angular/common": "^22.2.0", + "@angular/compiler": "^22.2.0", + "@angular/core": "^22.2.0", + "@angular/forms": "^22.2.0", + "@angular/platform-browser": "^22.2.0", + "@angular/router": "^22.2.0", + "rxjs": "~7.8.0", + "tslib": "^2.3.0" + }, + "devDependencies": { + "@angular/build": "^22.2.4", + "@angular/cli": "^22.2.4", + "@angular/compiler-cli": "^22.2.0", + "prettier": "^3.8.1", + "typescript": "~6.0.2", + "openapi-typescript": "^7.0.0" + } +} diff --git a/samples/BaGet.Frontend.Angular/public/favicon.ico b/samples/BaGet.Frontend.Angular/public/favicon.ico new file mode 100644 index 000000000..d23a8b45a Binary files /dev/null and b/samples/BaGet.Frontend.Angular/public/favicon.ico differ diff --git a/samples/BaGet.Frontend.Angular/scripts/smoke.mjs b/samples/BaGet.Frontend.Angular/scripts/smoke.mjs new file mode 100644 index 000000000..a71e8a0ab --- /dev/null +++ b/samples/BaGet.Frontend.Angular/scripts/smoke.mjs @@ -0,0 +1,66 @@ +// Smoke test against a running BaGet: signs in, lists packages, reads the admin users list, refreshes, signs out. +// BAGET_URL=http://localhost:6060 BAGET_USER=Admin BAGET_PASSWORD='Admin1234!' node scripts/smoke.mjs +// BAGET_ORIGIN (default http://localhost:4200) is sent as the Origin header like a browser would, so it must be in Cors:AllowedOrigins. +const base = (process.env.BAGET_URL ?? 'http://localhost:6060').replace(/\/+$/, ''); +const userName = process.env.BAGET_USER ?? 'Admin'; +const password = process.env.BAGET_PASSWORD ?? 'Admin1234!'; +const origin = process.env.BAGET_ORIGIN ?? 'http://localhost:4200'; + +let failures = 0; +const check = (name, ok, detail = '') => { + console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ` - ${detail}` : ''}`); + if (!ok) failures++; +}; + +async function call(method, path, { body, token } = {}) { + const response = await fetch(base + path, { + method, + headers: { + Origin: origin, + ...(body ? { 'Content-Type': 'application/json' } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }); + const text = await response.text(); + let json = null; + try { json = text ? JSON.parse(text) : null; } catch { /* not JSON */ } + return { status: response.status, json, headers: response.headers }; +} + +// 1. Wrong password: 401 and a ScreenResult, not a token. +const bad = await call('POST', '/api/ui/session', { body: { userName, password: password + 'x' } }); +check('wrong password is refused', bad.status === 401 && !bad.json?.model?.accessToken, `HTTP ${bad.status} ${bad.json?.status}`); + +// 2. Sign in. +const signIn = await call('POST', '/api/ui/session', { body: { userName, password } }); +const session = signIn.json?.model; +check('sign-in answers tokens', signIn.status === 200 && !!session?.accessToken && !!session?.refreshToken, `HTTP ${signIn.status} ${signIn.json?.status}`); +check('CORS allows the origin on the session endpoint', signIn.headers.get('access-control-allow-origin') === origin, String(signIn.headers.get('access-control-allow-origin'))); +if (!session?.accessToken) { + console.log(JSON.stringify(signIn.json)); + process.exit(1); +} + +// 3. Packages (anonymous screen, also fine with a token). +const packages = await call('GET', '/api/ui/packages', { token: session.accessToken }); +check('packages list', packages.status === 200 && packages.json?.status === 'Ok' && Array.isArray(packages.json?.model?.packages), `${packages.json?.model?.packages?.length ?? '?'} package(s)`); + +// 4. Admin screen with the session. +const users = await call('GET', '/api/ui/admin/users', { token: session.accessToken }); +check('admin users with the administrator session', users.status === 200 && users.json?.model?.users?.some((u) => u.userName?.toLowerCase() === userName.toLowerCase()), `HTTP ${users.status}`); +const anonymous = await call('GET', '/api/ui/admin/users'); +check('admin users without a session is 401', anonymous.status === 401 && anonymous.json?.status === 'SignIn', `HTTP ${anonymous.status} ${anonymous.json?.status}`); + +// 5. Refresh gives a new pair. +const refreshed = await call('POST', '/api/ui/session/refresh', { body: { refreshToken: session.refreshToken } }); +check('refresh answers a new pair', refreshed.status === 200 && !!refreshed.json?.model?.accessToken, `HTTP ${refreshed.status}`); + +// 6. Sign out, then a garbage access token is 401. +const out = await call('POST', '/api/ui/session/sign-out', { body: { refreshToken: session.refreshToken }, token: session.accessToken }); +check('sign-out', out.status === 200, `HTTP ${out.status}`); +const garbage = await call('GET', '/api/ui/admin/users', { token: 'bgs.not-a-token' }); +check('an invalid token is 401', garbage.status === 401, `HTTP ${garbage.status}`); + +console.log(failures ? `${failures} check(s) failed` : 'all checks passed'); +process.exit(failures ? 1 : 0); diff --git a/samples/BaGet.Frontend.Angular/src/app/api/api-client.ts b/samples/BaGet.Frontend.Angular/src/app/api/api-client.ts new file mode 100644 index 000000000..4a17c221a --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/api/api-client.ts @@ -0,0 +1,81 @@ +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { Injectable, inject } from '@angular/core'; +import { Observable, catchError, of } from 'rxjs'; +import { environment } from '../../environments/environment'; +import type { ApiPath, CallOptions, HttpMethod, Operation, ResponseOf, ScreenResult, ScreenStatus } from './api-types'; + +/** + * Thin typed wrapper over HttpClient. The path, the method, the query/path values, the body and the answer are all checked against + * the generated types, so a renamed field or a removed route is a compile error after `npm run gen:api`. + * + * It never throws for an HTTP error: every error status of `/api/ui` still carries a `ScreenResult` (400 Invalid with the + * model and errors, 401 SignIn, 403 Forbidden, 404 NotFound), and anything else (503 problem details, network down) is turned + * into a synthetic one, so a screen only switches on `status`. + */ +@Injectable({ providedIn: 'root' }) +export class ApiClient { + private readonly http = inject(HttpClient); + private readonly base = environment.apiBaseUrl.replace(/\/+$/, ''); + + /** The server origin, for the browser navigations that are not XHR (the external sign-in). */ + get baseUrl(): string { + return this.base; + } + + get

(path: P, options: CallOptions> = {}): Observable>> { + return this.call(path, 'get', options); + } + + post

(path: P, options: CallOptions> = {}): Observable>> { + return this.call(path, 'post', options); + } + + /** True when `url` is a request to this API (the interceptor adds the token to those only: never to another origin). */ + isApiUrl(url: string): boolean { + return url.startsWith(this.base + '/api/ui/'); + } + + private call

( + path: P, + method: M, + options: CallOptions>, + ): Observable>> { + const { url, params } = this.buildUrl(path, options); + const request = method === 'get' ? this.http.get(url, { params }) : this.http.post(url, options.body ?? {}, { params }); + return request.pipe(catchError((error: unknown) => of(this.toScreenResult(error)))) as Observable>>; + } + + /** Fills `{name}` from the path values; what is left of `query` is the query string. */ + private buildUrl(path: string, options: CallOptions): { url: string; params: Record } { + const values: Record = { ...(options.path ?? {}) }; + const url = path.replace(/\{(\w+)\}/g, (_match, name: string) => encodeURIComponent(String(values[name] ?? ''))); + const params: Record = {}; + for (const [name, value] of Object.entries(options.query ?? {})) { + if (value !== undefined && value !== null && value !== '') { + params[name] = String(value); + } + } + return { url: this.base + url, params }; + } + + private toScreenResult(error: unknown): ScreenResult { + if (!(error instanceof HttpErrorResponse)) { + return failure('Invalid', 'Unexpected error.'); + } + const body: unknown = error.error; + if (body && typeof body === 'object' && 'status' in body && typeof (body as { status: unknown }).status === 'string') { + return body as ScreenResult; + } + // Problem details (503 while read-only, 400 from model binding) or no body at all (network error, status 0). + const problem = body && typeof body === 'object' ? (body as { title?: string; detail?: string }) : {}; + const message = + problem.detail ?? problem.title ?? (error.status === 0 ? 'The server cannot be reached.' : `The request failed (${error.status}).`); + const status: ScreenStatus = + error.status === 401 ? 'SignIn' : error.status === 403 ? 'Forbidden' : error.status === 404 ? 'NotFound' : 'Invalid'; + return { ...failure(status, message), statusCode: error.status }; + } +} + +function failure(status: ScreenStatus, message: string): ScreenResult { + return { status, errors: { '': [message] } }; +} diff --git a/samples/BaGet.Frontend.Angular/src/app/api/api-types.ts b/samples/BaGet.Frontend.Angular/src/app/api/api-types.ts new file mode 100644 index 000000000..919f982d6 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/api/api-types.ts @@ -0,0 +1,36 @@ +import type { components, paths } from './schema'; + +/** Types derived from the generated OpenAPI types (`schema.d.ts`, `npm run gen:api`): nothing here is written per endpoint. */ +export type Schemas = components['schemas']; +export type ApiPath = keyof paths; +export type HttpMethod = 'get' | 'post'; + +/** The operation object of a path and method (`never` when the path has no such method). */ +export type Operation

= paths[P] extends { [K in M]: infer O } ? O : never; + +/** The 200 JSON answer: a `ScreenResult` for every twin. */ +export type ResponseOf = O extends { responses: { 200: { content: { 'application/json': infer R } } } } ? R : never; +export type BodyOf = O extends { requestBody?: { content: { 'application/json': infer B } } } ? NonNullable : never; +export type QueryOf = O extends { parameters: { query?: infer Q } } ? NonNullable : never; +export type PathParamsOf = O extends { parameters: { path?: infer Q } } ? NonNullable : never; + +/** Request options of one operation: path values, query values and the JSON body, all typed from the document. */ +export interface CallOptions { + path?: Partial>; + query?: Partial>; + body?: BodyOf; +} + +/** `'Ok' | 'Invalid' | 'NotFound' | 'Forbidden' | 'SignIn' | 'Next'`: the document describes the enum by name, as the wire carries it. */ +export type ScreenStatus = Schemas['ScreenStatus']; +export type ScreenNext = Schemas['ScreenNext']; +export type SessionModel = Schemas['SessionModel']; + +/** The shape every `ScreenResult` shares, whatever `T` is (the generated types have one per model). */ +export interface ScreenResult { + status?: ScreenStatus; + model?: T; + errors?: { [field: string]: string[] } | null; + next?: ScreenNext; + statusCode?: number | null; +} diff --git a/samples/BaGet.Frontend.Angular/src/app/api/field-errors.ts b/samples/BaGet.Frontend.Angular/src/app/api/field-errors.ts new file mode 100644 index 000000000..41aeca3ea --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/api/field-errors.ts @@ -0,0 +1,24 @@ +import { Component, input } from '@angular/core'; +import { AbstractControl } from '@angular/forms'; + +/** The messages of one control: the server's (`ScreenResult.errors`, see `applyServerErrors`) and the client-side `required`. */ +@Component({ + selector: 'app-field-errors', + template: ` + @if (control().touched || control().hasError('server')) { + @if (control().hasError('required')) { + Required. + } + @for (message of serverMessages(); track message) { + {{ message }} + } + } + `, +}) +export class FieldErrors { + readonly control = input.required(); + + protected serverMessages(): string[] { + return (this.control().getError('server') as string[] | null) ?? []; + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/api/schema.d.ts b/samples/BaGet.Frontend.Angular/src/app/api/schema.d.ts new file mode 100644 index 000000000..5b3aebba9 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/api/schema.d.ts @@ -0,0 +1,29135 @@ +/** + * This file was auto-generated by openapi-typescript. + * Do not make direct changes to the file. + */ + +export interface paths { + "/api/ui/account/login": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The sign-in form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Signs in. Success sets the session cookie and continues at `next.localUrl` (the local return URL, else the site root), or at the second-factor screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["LoginForm"]; + "text/json": (null) | components["schemas"]["LoginForm"]; + "application/*+json": (null) | components["schemas"]["LoginForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/loginwith2fa": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The authenticator code form (back to sign-in without the half-signed-in cookie). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + rememberMe?: boolean; + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Completes the sign-in with an authenticator code. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["TwoFactorLoginForm"]; + "text/json": (null) | components["schemas"]["TwoFactorLoginForm"]; + "application/*+json": (null) | components["schemas"]["TwoFactorLoginForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/loginwithrecoverycode": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The recovery code form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Completes the sign-in with a recovery code (each works once). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RecoveryCodeLoginForm"]; + "text/json": (null) | components["schemas"]["RecoveryCodeLoginForm"]; + "application/*+json": (null) | components["schemas"]["RecoveryCodeLoginForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/logout": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The sign-out screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + put?: never; + /** + * Signs the user out. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/register": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The registration form (404 while `Accounts:AllowRegistration` is off). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Creates an account (and signs it in when no confirmation or approval is pending). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RegisterForm"]; + "text/json": (null) | components["schemas"]["RegisterForm"]; + "application/*+json": (null) | components["schemas"]["RegisterForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/confirmemail": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The target of the links in confirmation emails (a GET that confirms the address, like the page). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + userId?: string; + code?: string; + email?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/forgotpassword": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The "forgot password" form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Asks for a reset link. The answer is the same whether or not an account matches. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "text/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "application/*+json": (null) | components["schemas"]["ForgotPasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/resetpassword": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The new-password form behind the link of a reset email. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + userId?: string; + code?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Sets the new password from the link; success continues at the sign-in screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ResetPasswordForm"]; + "text/json": (null) | components["schemas"]["ResetPasswordForm"]; + "application/*+json": (null) | components["schemas"]["ResetPasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/reauthenticate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The "confirm it is you" screen (the button that starts the provider's sign-in is browser-only). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The organizations of the user. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations/create": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Create an organization. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["CreateOrganizationForm"]; + "text/json": (null) | components["schemas"]["CreateOrganizationForm"]; + "application/*+json": (null) | components["schemas"]["CreateOrganizationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Add a member (organization administrators only; 403 otherwise). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["AddOrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["AddOrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["AddOrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Remove a member (an administrator removes anyone; any member may leave; 403 otherwise). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RemoveOrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["RemoveOrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["RemoveOrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The package IDs the user owns, per repository. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/access": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * What the user may do in each repository (optionally for one package ID). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + package?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/profile": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The user's own profile: continues at `next.localUrl` (`~/profiles/{name}`). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Account settings. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/change-password": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Change the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ChangePasswordForm"]; + "text/json": (null) | components["schemas"]["ChangePasswordForm"]; + "application/*+json": (null) | components["schemas"]["ChangePasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/change-email": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Change the email address (asks the password again). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ChangeEmailForm"]; + "text/json": (null) | components["schemas"]["ChangeEmailForm"]; + "application/*+json": (null) | components["schemas"]["ChangeEmailForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/unlink-external": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unlinks the account's login at an external provider (asks the password again; refused when it is the only way to sign in). Linking is browser-only: it redirects to the provider. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UnlinkExternalForm"]; + "text/json": (null) | components["schemas"]["UnlinkExternalForm"]; + "application/*+json": (null) | components["schemas"]["UnlinkExternalForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Delete the account (asks the password again). Success signs the user out. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "text/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "application/*+json": (null) | components["schemas"]["PasswordConfirmationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Two-factor authentication (the setup key and QR code while it is off). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor/enable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Turn two-factor authentication on with a code from the authenticator; the answer carries the recovery codes, once. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["TwoFactorCodeForm"]; + "text/json": (null) | components["schemas"]["TwoFactorCodeForm"]; + "application/*+json": (null) | components["schemas"]["TwoFactorCodeForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor/disable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Turn two-factor authentication off (asks the password again). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "text/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "application/*+json": (null) | components["schemas"]["PasswordConfirmationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor/reset": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Reset the authenticator (asks the password again). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "text/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "application/*+json": (null) | components["schemas"]["PasswordConfirmationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/apikeys": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The user's API keys (never their values) and the new-key form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/apikeys/create": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Creates a key. The answer carries its value (`createdKey`) once. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ApiKeyForm"]; + "text/json": (null) | components["schemas"]["ApiKeyForm"]; + "application/*+json": (null) | components["schemas"]["ApiKeyForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/apikeys/revoke/{key}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Revokes a key. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/audit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the entries that match the filter. */ + get: { + parameters: { + query?: { + actor?: string; + subject?: string; + from?: string; + to?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the groups. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a group and points at it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupCreation"]; + "text/json": (null) | components["schemas"]["GroupCreation"]; + "application/*+json": (null) | components["schemas"]["GroupCreation"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one group, with the member search for q. */ + get: { + parameters: { + query?: { + q?: string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/rename": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Renames the group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupRename"]; + "text/json": (null) | components["schemas"]["GroupRename"]; + "application/*+json": (null) | components["schemas"]["GroupRename"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds a user to the group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupMemberChange"]; + "text/json": (null) | components["schemas"]["GroupMemberChange"]; + "application/*+json": (null) | components["schemas"]["GroupMemberChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a user from the group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupMemberChange"]; + "text/json": (null) | components["schemas"]["GroupMemberChange"]; + "application/*+json": (null) | components["schemas"]["GroupMemberChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the group with the grants and project roles that name it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/operations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the operations and their status. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Starts an operation on a repository. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OperationForm"]; + "text/json": (null) | components["schemas"]["OperationForm"]; + "application/*+json": (null) | components["schemas"]["OperationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the pending and quarantined submissions. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation/retry": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Validates the submission again. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SubmissionForm"]; + "text/json": (null) | components["schemas"]["SubmissionForm"]; + "application/*+json": (null) | components["schemas"]["SubmissionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation/release": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Indexes the quarantined package although validation failed. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SubmissionForm"]; + "text/json": (null) | components["schemas"]["SubmissionForm"]; + "application/*+json": (null) | components["schemas"]["SubmissionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation/reject": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the quarantined package. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SubmissionForm"]; + "text/json": (null) | components["schemas"]["SubmissionForm"]; + "application/*+json": (null) | components["schemas"]["SubmissionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/abuse": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the abuse reports (the unresolved ones unless all). */ + get: { + parameters: { + query?: { + all?: boolean; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/abuse/resolve": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Marks a report resolved. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["AbuseForm"]; + "text/json": (null) | components["schemas"]["AbuseForm"]; + "application/*+json": (null) | components["schemas"]["AbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/abuse/reopen": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Reopens a resolved report. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["AbuseForm"]; + "text/json": (null) | components["schemas"]["AbuseForm"]; + "application/*+json": (null) | components["schemas"]["AbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/cluster": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The cluster status; `?refresh=true` runs the health checks again. */ + get: { + parameters: { + query?: { + refresh?: boolean; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/formats": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The package formats this server can host. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/access-unavailable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Why the access screens are not available: the configured database has no access model. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the organizations. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one organization. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/rename": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Renames the organization. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationRenameForm"]; + "text/json": (null) | components["schemas"]["OrganizationRenameForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationRenameForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the organization (refused while it owns packages). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds a user to the organization. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/set-admin": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Makes a member an administrator of the organization, or not. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a member from the organization. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the ownerless IDs of every repository, pageNumber being one-based. */ + get: { + parameters: { + query?: { + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/admin/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the ownerless IDs of every repository, pageNumber being one-based. */ + get: { + parameters: { + query?: { + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the permission targets. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a target and points at it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Previews the form patterns without saving anything. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/restore-built-ins": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Re-creates the built-in groups and targets that are missing (the upgrade defaults). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one target. principalType and principalName pre-fill the grant form. */ + get: { + parameters: { + query?: { + testPackage?: string; + principalType?: components["schemas"]["PrincipalType"]; + principalName?: string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Previews the form patterns (and the test package) without saving anything. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/save": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Replaces the target's patterns. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/set-grant": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Gives a principal the ticked actions through the target, replacing an earlier grant to it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GrantForm"]; + "text/json": (null) | components["schemas"]["GrantForm"]; + "application/*+json": (null) | components["schemas"]["GrantForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/remove-grant": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a principal's grant. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PrincipalRemoval"]; + "text/json": (null) | components["schemas"]["PrincipalRemoval"]; + "application/*+json": (null) | components["schemas"]["PrincipalRemoval"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the target and its grants. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the projects the caller may open. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a project (server administrators only) and points at it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectCreation"]; + "text/json": (null) | components["schemas"]["ProjectCreation"]; + "application/*+json": (null) | components["schemas"]["ProjectCreation"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one project. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/set-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Gives a user or group a role in the project, replacing an earlier one. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectMemberForm"]; + "text/json": (null) | components["schemas"]["ProjectMemberForm"]; + "application/*+json": (null) | components["schemas"]["ProjectMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Takes a user or group out of the project. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PrincipalRemoval"]; + "text/json": (null) | components["schemas"]["PrincipalRemoval"]; + "application/*+json": (null) | components["schemas"]["PrincipalRemoval"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/assign-repository": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Puts a repository in the project (server administrators only); it leaves any project it was in. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "text/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "application/*+json": (null) | components["schemas"]["ProjectRepositoryForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/unassign-repository": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Takes a repository out of the project (server administrators only). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "text/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "application/*+json": (null) | components["schemas"]["ProjectRepositoryForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/create-target": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a permission target that applies only to the project's repositories. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectTargetForm"]; + "text/json": (null) | components["schemas"]["ProjectTargetForm"]; + "application/*+json": (null) | components["schemas"]["ProjectTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Previews the new target's patterns without saving anything. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectTargetForm"]; + "text/json": (null) | components["schemas"]["ProjectTargetForm"]; + "application/*+json": (null) | components["schemas"]["ProjectTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the project (server administrators only) with its members and targets; the repositories stay. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the repositories (narrowed by format, kind, q) and describes the create forms. */ + get: { + parameters: { + query?: { + format?: string; + kind?: string; + q?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a local NuGet repository (`name`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/create/format": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a local repository of a format other than NuGet (`name`, `format`, `fields`, `anonymousRead`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/create/virtual": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a virtual repository with no members (`name`, `format`, `anonymousRead`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/create/remote": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a remote repository (`name`, `format`, `remote`, `anonymousRead`, `password`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one repository. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + put?: never; + /** Saves the repository (`anonymousRead`; a remote one also `remote` and `password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/maven-settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the policy of a local Maven repository (`policy`, `redeploy`, `snapshotBuilds`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/test": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Asks a remote repository's upstream with the unsaved `remote` values and saves nothing (`password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/purge": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes everything a remote repository cached (`password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/purge-package": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes one cached package of a remote repository (`packageId`, `packageVersion`, `password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds a member at the end of a virtual repository (`member`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a member of a virtual repository (`member`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/move-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Moves a member of a virtual repository up or down (`member`, `direction`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/deploy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Sets the member of a virtual repository that receives uploads (`deploy`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Shows where a package version would come from in a virtual repository (`previewPackageId`, `previewVersion`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows what deleting the repository does. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deletes the repository (refused while it holds packages or is a member of a virtual repository). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the settings; section is the id of the section to show. */ + get: { + parameters: { + query?: { + section?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Saves the settings of one section: the body names the section, the password and the fields (`v:<key>` values, `reset:<key>`, + * `clear:<key>`, `copyData`), each an array of strings. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SettingsSubmission"]; + "text/json": (null) | components["schemas"]["SettingsSubmission"]; + "application/*+json": (null) | components["schemas"]["SettingsSubmission"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/copy-status": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The progress of the database copy. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/save-provider": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds or changes a named OpenID Connect provider (password in the body; takes effect after a restart; a blank secret keeps the saved one). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SignInProviderForm"]; + "text/json": (null) | components["schemas"]["SignInProviderForm"]; + "application/*+json": (null) | components["schemas"]["SignInProviderForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/remove-provider": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a named OpenID Connect provider saved on this screen (takes effect after a restart). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RemoveSignInProviderForm"]; + "text/json": (null) | components["schemas"]["RemoveSignInProviderForm"]; + "application/*+json": (null) | components["schemas"]["RemoveSignInProviderForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/set-log-level": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Sets the lowest level logged for one source. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["LogLevelForm"]; + "text/json": (null) | components["schemas"]["LogLevelForm"]; + "application/*+json": (null) | components["schemas"]["LogLevelForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/remove-log-level": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a per-source level saved on this screen. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["LogLevelForm"]; + "text/json": (null) | components["schemas"]["LogLevelForm"]; + "application/*+json": (null) | components["schemas"]["LogLevelForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/test-telemetry": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Sends one test span to the posted, unsaved telemetry endpoint (`v:Telemetry:Otlp:*` fields) and answers the outcome; nothing is saved. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SettingsSubmission"]; + "text/json": (null) | components["schemas"]["SettingsSubmission"]; + "application/*+json": (null) | components["schemas"]["SettingsSubmission"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the users, filtered by q (user name contains), one page of them. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/approve": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Enables a self-registered account that waits for approval. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/promote": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Makes a user an administrator. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/demote": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a user's administrator flag. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/reset-password": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Replaces a user's password with a generated one, which the answer carries once (`generatedPassword`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/send-reset-link": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Mails a user a password reset link. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/create": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates an account (typed, generated or invited password). A generated password is in the answer once. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserCreation"]; + "text/json": (null) | components["schemas"]["UserCreation"]; + "application/*+json": (null) | components["schemas"]["UserCreation"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one account. package is a package ID to evaluate the effective permissions for. */ + get: { + parameters: { + query?: { + package?: string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/approve": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Enables the account when it waits for approval. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/revoke-key": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Revokes one of the account's API keys. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserKeyForm"]; + "text/json": (null) | components["schemas"]["UserKeyForm"]; + "application/*+json": (null) | components["schemas"]["UserKeyForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/add-group": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds the account to a group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserGroupForm"]; + "text/json": (null) | components["schemas"]["UserGroupForm"]; + "application/*+json": (null) | components["schemas"]["UserGroupForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/remove-group": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes the account from a group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserGroupForm"]; + "text/json": (null) | components["schemas"]["UserGroupForm"]; + "application/*+json": (null) | components["schemas"]["UserGroupForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows what deleting the account does. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deletes the account after the administrator's password. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserDeletionForm"]; + "text/json": (null) | components["schemas"]["UserDeletionForm"]; + "application/*+json": (null) | components["schemas"]["UserDeletionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the package IDs one user owns. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/admin/users/{name}/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the package IDs one user owns. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/contact-owners": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The form's state; 404 when the package has no owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Sends the message to the owners (400 with the field errors when the message is missing or too long). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ContactOwnersForm"]; + "text/json": (null) | components["schemas"]["ContactOwnersForm"]; + "application/*+json": (null) | components["schemas"]["ContactOwnersForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/contact-owners": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The form's state; 404 when the package has no owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Sends the message to the owners (400 with the field errors when the message is missing or too long). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ContactOwnersForm"]; + "text/json": (null) | components["schemas"]["ContactOwnersForm"]; + "application/*+json": (null) | components["schemas"]["ContactOwnersForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/delete-tag/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a tag, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/delete-tag/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a tag, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/delete-manifest/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a manifest with its tags, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/delete-manifest/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a manifest with its tags, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/prune/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes the layers no manifest uses, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/prune/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes the layers no manifest uses, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/delete-image/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole image, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/delete-image/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole image, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/delete-file": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one file of the chosen version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-file": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one file of the chosen version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/delete-version": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-version": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/delete-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole artifact, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole artifact, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/cleanup": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes old snapshot builds of a version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/cleanup": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes old snapshot builds of a version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/add-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/add-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/remove-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/remove-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/set-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Points a dist-tag at a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/set-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Points a dist-tag at a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/remove-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a dist-tag. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/remove-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a dist-tag. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/deprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/deprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/undeprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/undeprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/unpublish/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes one version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/unpublish/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes one version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/unpublish-all/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes every version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/unpublish-all/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes every version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/unlist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unlists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/unlist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unlists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/relist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Relists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/relist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Relists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a version as the server is configured to (unlist or permanent). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a version as the server is configured to (unlist or permanent). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/hard-delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes a version (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "text/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes a version (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "text/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/hard-delete-all": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes every version and the owners (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "text/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "application/*+json": (null) | components["schemas"]["PackageManagePasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete-all": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes every version and the owners (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "text/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "application/*+json": (null) | components["schemas"]["PackageManagePasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/deprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/deprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/undeprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/undeprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/add-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds a vulnerability to a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/add-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds a vulnerability to a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/remove-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a vulnerability from a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/remove-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a vulnerability from a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/set-verified": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Marks or unmarks the ID as verified (administrators). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "text/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/set-verified": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Marks or unmarks the ID as verified (administrators). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "text/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/delete-symbols": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the PDBs recorded for a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/delete-symbols": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the PDBs recorded for a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/resolve-report": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Resolves an abuse report. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageReportForm"]; + "text/json": (null) | components["schemas"]["PackageManageReportForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageReportForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/resolve-report": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Resolves an abuse report. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageReportForm"]; + "text/json": (null) | components["schemas"]["PackageManageReportForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageReportForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/profiles/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The profile named name; 404 when neither a user nor an organization has it. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/profiles/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The profile named name; 404 when neither a user nor an organization has it. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the replications and the form that creates one. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a replication and opens it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ReplicationBody"]; + "text/json": (null) | components["schemas"]["ReplicationBody"]; + "application/*+json": (null) | components["schemas"]["ReplicationBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one replication with its log. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/save": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the settings. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ReplicationBody"]; + "text/json": (null) | components["schemas"]["ReplicationBody"]; + "application/*+json": (null) | components["schemas"]["ReplicationBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/test": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Tests the connection with the typed settings; saves nothing. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ReplicationBody"]; + "text/json": (null) | components["schemas"]["ReplicationBody"]; + "application/*+json": (null) | components["schemas"]["ReplicationBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/run": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a run. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/resume": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a run that continues the last interrupted or failed one. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/stop": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Asks the running replication to stop; it ends as interrupted and can be resumed. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the configuration with its log. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the policies and the form that creates one. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a policy and opens it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "text/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "application/*+json": (null) | components["schemas"]["RetentionPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one policy, its last run and report. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/save": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the rules. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "text/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "application/*+json": (null) | components["schemas"]["RetentionPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/dry-run": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a dry run: the report of what a run would delete. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/run": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a run that deletes. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the policy (what it deleted stays deleted). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/holds": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the legal holds (of `?repository=` only, when given). */ + get: { + parameters: { + query?: { + repository?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/holds/add": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Places a hold. */ + post: { + parameters: { + query?: { + repository?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionHoldForm"]; + "text/json": (null) | components["schemas"]["RetentionHoldForm"]; + "application/*+json": (null) | components["schemas"]["RetentionHoldForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/holds/remove": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Lifts a hold. */ + post: { + parameters: { + query?: { + repository?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionHoldRemoval"]; + "text/json": (null) | components["schemas"]["RetentionHoldRemoval"]; + "application/*+json": (null) | components["schemas"]["RetentionHoldRemoval"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/scan-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Shows the form (and the stored result) of the version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + name?: string; + version?: string; + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Scans the version now (or queues it, for an image) and shows the outcome. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanArtifactForm"]; + "text/json": (null) | components["schemas"]["ScanArtifactForm"]; + "application/*+json": (null) | components["schemas"]["ScanArtifactForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/scan-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Shows the form (and the stored result) of the version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + name?: string; + version?: string; + returnUrl?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Scans the version now (or queues it, for an image) and shows the outcome. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanArtifactForm"]; + "text/json": (null) | components["schemas"]["ScanArtifactForm"]; + "application/*+json": (null) | components["schemas"]["ScanArtifactForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The overview of every repository and project. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The dashboard of a repository: `?min=` is the lowest severity listed (0 to 3), `?p=` the page. */ + get: { + parameters: { + query?: { + min?: number | string; + p?: number | string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/{name}/policy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the repository policy; empty values remove it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanPolicyBody"]; + "text/json": (null) | components["schemas"]["ScanPolicyBody"]; + "application/*+json": (null) | components["schemas"]["ScanPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/{name}/scan": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a scan of every artifact of the repository in the background. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/projects/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The scanning policy of a project. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/projects/{name}/policy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the project policy; empty values remove it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanPolicyBody"]; + "text/json": (null) | components["schemas"]["ScanPolicyBody"]; + "application/*+json": (null) | components["schemas"]["ScanPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Signs in with the user name and password. Answers the tokens, or `twoFactorRequired` with a short-lived `twoFactorTicket` for + * `/session/two-factor` or `/session/recovery-code`. 401 for wrong credentials, 403 for a locked, unapproved or unconfirmed account. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionSignInForm"]; + "text/json": (null) | components["schemas"]["SessionSignInForm"]; + "application/*+json": (null) | components["schemas"]["SessionSignInForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/two-factor": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Completes a sign-in with a code of the authenticator app. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionTwoFactorForm"]; + "text/json": (null) | components["schemas"]["SessionTwoFactorForm"]; + "application/*+json": (null) | components["schemas"]["SessionTwoFactorForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/recovery-code": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Completes a sign-in with a recovery code (each works once). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionRecoveryCodeForm"]; + "text/json": (null) | components["schemas"]["SessionRecoveryCodeForm"]; + "application/*+json": (null) | components["schemas"]["SessionRecoveryCodeForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/refresh": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Exchanges the refresh token for a new pair of tokens (the authentication time is kept; the session ends `Accounts:SessionMaxLifetime` after the sign-in). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionRefreshForm"]; + "text/json": (null) | components["schemas"]["SessionRefreshForm"]; + "application/*+json": (null) | components["schemas"]["SessionRefreshForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/exchange": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Exchanges the 60-second `exchange_token` of an external sign-in's redirect for the tokens (or the two-factor ticket). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionExchangeForm"]; + "text/json": (null) | components["schemas"]["SessionExchangeForm"]; + "application/*+json": (null) | components["schemas"]["SessionExchangeForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/sign-out": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Ends the session: the client forgets its tokens. With `everywhere` the account's security stamp changes and every token and cookie + * session of the account stops working. The caller is the access token, or the refresh token in the body. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionSignOutForm"]; + "text/json": (null) | components["schemas"]["SessionSignOutForm"]; + "application/*+json": (null) | components["schemas"]["SessionSignOutForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/cookie": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Signs in with the cookie (same origin only; needs the antiforgery token of `GET /api/ui/antiforgery` fetched while signed out, so a cross-site page cannot + * sign a visitor in): the rules of `POST /session`, the second factor in the same endpoint (`ticket` with `code` or `recoveryCode`), but the answer holds no tokens. + * Fetch the antiforgery token again afterwards: it is bound to the signed-in user. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionCookieForm"]; + "text/json": (null) | components["schemas"]["SessionCookieForm"]; + "application/*+json": (null) | components["schemas"]["SessionCookieForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/cookie/sign-out": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Signs the cookie session out (same origin; send the cookie with the antiforgery header). 401 for anything but a cookie session. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/providers": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The external sign-in providers a client can offer before anyone is signed in (the sign-in screen's model is interactive-only): their ids, to put in + * `/session/external/{id}`, and the names for the buttons. An empty list when none is configured. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/antiforgery": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The antiforgery request token for a same-origin client that uses the cookie session: send it in the `X-XSRF-TOKEN` header (every method). It + * is bound to the signed-in user, so fetch it again after signing in or out. Also sets the antiforgery cookie. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/resend-confirmation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Mails a new confirmation link to an account whose address is not confirmed. The answer is the same whether or not an account matches or the mail was allowed + * (one per account per ten minutes, and per client); 404 without outgoing mail. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "text/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "application/*+json": (null) | components["schemas"]["ForgotPasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/external/{provider}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Starts the sign-in with the external provider (a browser navigation, not a fetch). The result comes back in the URL fragment of + * returnUrl, which must lie under `Frontend:SpaBasePath` of this server, or be an address of an origin listed in `Cors:AllowedOrigins`. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path: { + provider: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/external-callback": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The provider's answer: redirects to returnUrl with, in the URL fragment, `exchange_token` (+ `exchange_expires_at`, `user_name`), to exchange within + * a minute at `POST /api/ui/session/exchange`, or `notice` (account created, not usable yet) or `error`. No token of the session itself is ever put in a URL. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/validation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The submissions of the ID. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/validation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The submissions of the ID. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/api": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The operations of the REST API. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-images": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The image list with a search box and the client commands. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-images": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The image list with a search box and the client commands. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-images/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One image: tags, manifests, and with `digest` one manifest in full. */ + get: { + parameters: { + query?: { + digest?: string; + artifactType?: string; + }; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-images/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One image: tags, manifests, and with `digest` one manifest in full. */ + get: { + parameters: { + query?: { + digest?: string; + artifactType?: string; + }; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/home": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The front page of the repository, or the results when the query asks for something. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/home": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The front page of the repository, or the results when the query asks for something. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One page of the package list. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One page of the package list. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/privacy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The Privacy Policy. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/terms": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The Terms of Use. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-artifacts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The artifact list with a search box and the client configuration. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-artifacts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The artifact list with a search box and the client configuration. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-artifacts/{group}/{artifact}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + version: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deploys the chosen files under the given coordinates. */ + post: { + parameters: { + query?: { + groupId?: string; + artifactId?: string; + version?: string; + packaging?: string; + classifier?: string; + apiKey?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + file?: components["schemas"]["IFormFile"]; + } & { + pom?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deploys the chosen files under the given coordinates. */ + post: { + parameters: { + query?: { + groupId?: string; + artifactId?: string; + version?: string; + packaging?: string; + classifier?: string; + apiKey?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + file?: components["schemas"]["IFormFile"]; + } & { + pom?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The package list with a search box. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The package list with a search box. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One package: readme, versions, dist-tags, install commands. */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One package: readme, versions, dist-tags, install commands. */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Publishes the chosen tarball with the dist-tag tag (default `latest`). */ + post: { + parameters: { + query?: { + tag?: string; + apiKey?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Publishes the chosen tarball with the dist-tag tag (default `latest`). */ + post: { + parameters: { + query?: { + tag?: string; + apiKey?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/{version}/report-abuse": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The empty form. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + put?: never; + /** Records the report. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["ReportAbuseForm"]; + "text/json": components["schemas"]["ReportAbuseForm"]; + "application/*+json": components["schemas"]["ReportAbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/{version}/report-abuse": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The empty form. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + put?: never; + /** Records the report. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["ReportAbuseForm"]; + "text/json": components["schemas"]["ReportAbuseForm"]; + "application/*+json": components["schemas"]["ReportAbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/stats": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The feed's statistics. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/stats": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The feed's statistics. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Step one: the form. */ + get: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Step one: the form. */ + get: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload/stage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Stages the chosen file and describes what it contains. */ + post: { + parameters: { + query?: { + id?: string; + apiKey?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload/stage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Stages the chosen file and describes what it contains. */ + post: { + parameters: { + query?: { + id?: string; + apiKey?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload/submit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Publishes the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload/submit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Publishes the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload/cancel": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Discards the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload/cancel": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Discards the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-artifacts/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; +} +export type webhooks = Record; +export interface components { + schemas: { + /** @description A decision on an abuse report. */ + AbuseForm: { + /** + * Format: int32 + * @description The report's number. + */ + key: number; + /** @description Whether the list to come back to shows the resolved reports too. */ + all: boolean; + }; + /** @description An abuse report with the name of its repository. */ + AbuseReportSummary: { + /** Format: int32 */ + key: number; + repository: string; + packageId: string | null; + packageVersion: string | null; + reason: string | null; + details: string | null; + reporterEmail: string | null; + /** Format: date-time */ + created: string; + /** Format: date-time */ + resolved: string | null; + isResolved?: boolean; + }; + /** @description What the abuse reports screen (`/admin/abuse`) shows: the reports of every repository. */ + AbuseViewModel: { + /** @description Show the resolved reports too. */ + all?: boolean; + /** @description Whether reports are stored with the configured database. */ + isSupported?: boolean; + /** @description The reports, newest first. */ + items?: components["schemas"]["AbuseReportSummary"][]; + message?: string | null; + error?: string | null; + }; + /** + * @description What a permission grants. Independent flags: AccessAction.Deploy does not imply AccessAction.Read, as in + * Artifactory. Package ownership (IPackageAuthorizationService) is a second, separate requirement + * for the actions that change an existing package ID. + * @enum {string} + */ + AccessAction: "None" | "Read" | "Annotate" | "Deploy" | "Delete" | "Manage" | "All"; + /** @description One change to the access model. */ + AccessAuditEntry: { + /** Format: int32 */ + key?: number; + /** Format: date-time */ + created?: string; + /** @description The user name that made the change; null for the server itself. */ + actor?: string | null; + /** @description What happened, such as `group.create` or `grant.set`. */ + action?: string | null; + /** @description What it happened to (a group, target or repository name). */ + subject?: string | null; + /** @description JSON with the details (never credentials). */ + details?: string | null; + }; + /** @description What a caller may do in a repository, and why (Task<AccessExplanation> IAccessEvaluator.ExplainAsync(BaGetPrincipal? principal, RepositoryInfo repository, string? packageId, CancellationToken cancellationToken)). */ + AccessExplanation: { + actions: components["schemas"]["AccessAction"]; + /** + * @description A rule that grants everything or bypasses the model (administrator, global API key, no + * access model), instead of Reasons; null when the grants decide. + */ + override: string | null; + /** @description The grants and project roles that apply to the caller. */ + reasons: components["schemas"]["AccessReason"][]; + }; + /** @description One grant or project role behind an access decision, for the admin pages that explain it. */ + AccessReason: { + /** @description Where it comes from, such as `Permission target 'Anyone reads every repository'`. */ + source: string; + principalType: components["schemas"]["PrincipalType"]; + /** @description The principal's id (user id, group or organization key). */ + principalId: string; + /** @description The principal in words (a user name, `group Developers`, `organization Contoso`). */ + principal: string; + granted: components["schemas"]["AccessAction"]; + effective: components["schemas"]["AccessAction"]; + /** @description The package filter of the target, such as `Contoso.* except Contoso.Internal.*`; null for all. */ + packages: string | null; + /** @description Why AccessAction AccessReason.Effective differs from AccessAction AccessReason.Granted, if it does. */ + note: string | null; + }; + /** @description What the "access control unavailable" screen (`/admin/access-unavailable`) says: why, as the JSON carries it (the page has fixed text). */ + AccessUnavailableViewModel: { + /** @description Why the access screens are not available. */ + reason: string; + }; + /** @description The "My access" screen: the signed-in user's own effective permissions. */ + AccountAccessViewModel: { + /** @description A package ID to evaluate the grants for; empty means the repository as a whole. */ + package?: string | null; + /** @description The repositories where the user holds some action. */ + rows?: components["schemas"]["RepositoryAccessRow"][]; + /** @description The projects the user administers. */ + administeredProjects?: string[]; + /** @description Whether the configured database has an access model at all. */ + modelAvailable?: boolean; + }; + /** @description One API key as the screen lists it: never the key itself or its hash (only the creation response shows a new key, once). */ + AccountApiKey: { + /** + * Format: int32 + * @description The key's id (the number the revoke button posts). + */ + key?: number; + /** @description What the key is for. */ + description?: string | null; + /** @description What the key may do. */ + scopes?: string[]; + /** @description The package IDs the key applies to. */ + packageGlobPattern?: string | null; + /** + * Format: date-time + * @description When it was created. + */ + created?: string; + /** + * Format: date-time + * @description When it expires; null = never. + */ + expires?: string | null; + }; + /** @description One organization with its members. */ + AccountOrganization: { + /** @description The organization's name. */ + name?: string | null; + /** @description Whether the current user administers it. */ + isAdmin?: boolean; + /** @description The members, by user name. */ + members?: components["schemas"]["AccountOrganizationMember"][] | null; + }; + /** @description One member of an organization (a flat record, so the screen's JSON names its fields). */ + AccountOrganizationMember: { + /** @description The member's user name. */ + userName: string; + /** @description Whether the member administers the organization. */ + isAdmin: boolean; + }; + /** @description The "My packages" screen: the packages the user owns in each repository. */ + AccountPackagesViewModel: { + /** @description The owned packages of each repository that has any, `default` first. */ + groups?: components["schemas"]["RepositoryPackages"][]; + /** @description Whether the user owns nothing in any repository. */ + isEmpty?: boolean; + /** @description Whether the list needs repository headings: more than the default repository holds packages of the user. */ + showRepositoryNames?: boolean; + }; + /** @description What the "add a member" form posts. */ + AddOrganizationMemberForm: { + /** @description The organization. */ + organization?: string | null; + /** @description The user to add. */ + userName?: string | null; + /** @description Whether the new member administers the organization. */ + isAdmin?: boolean; + }; + /** @description What deleting a user as an administrator would remove or change. */ + AdminDeletionPreview: { + /** + * Format: int32 + * @description How many API keys go. + */ + apiKeys: number; + /** @description Package IDs the user owns directly. */ + directPackageIds: string[]; + /** @description The subset nobody else owns, in every repository. */ + soleOwnedPackages: components["schemas"]["SoleOwnedPackage"][]; + /** @description What happens to each organization the user belongs to. */ + organizations: components["schemas"]["OrganizationOutcome"][]; + }; + /** @enum {string} */ + AdminJobState: "Running" | "Succeeded" | "Failed"; + /** @description The last run of an operation on a repository. In memory: a restart forgets it. */ + AdminJobStatus: { + operation?: string; + repository?: string; + state?: components["schemas"]["AdminJobState"]; + actor?: string | null; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + /** @description The result on success, the exception type and message on failure. */ + message?: string | null; + }; + /** @description What the organizations screen (`/admin/organizations`) lists: every organization with its members and packages. */ + AdminOrganizationsViewModel: { + /** @description The organizations, by name. */ + organizations?: components["schemas"]["OrganizationSummary"][]; + }; + /** @description A package ID as the administrator pages list it. */ + AdminPackageRow: { + package: components["schemas"]["OwnedPackage"]; + /** @description The names of its owners; empty for an ownerless ID. */ + owners: string[]; + /** + * @description The repository the ID is in; ownership and versions are per repository. + * @default default + */ + repositoryName: string; + }; + /** @description What the ownerless packages screen (`/admin/packages`) shows: the package IDs nobody owns, in every repository. */ + AdminPackagesViewModel: { + /** + * Format: int32 + * @description One-based page number (the `p` query value). + */ + pageNumber?: number; + /** @description The ownerless IDs on this page. */ + packages?: components["schemas"]["AdminPackageRow"][]; + /** @description Whether a Repository column is worth showing: some listed ID is outside the default repository. */ + showRepository?: boolean; + /** + * Format: int32 + * @description The number of pages. + */ + pageCount?: number; + }; + /** @description What the server settings screen (`/admin/settings`) shows: every registered setting by section and the state of the last save. */ + AdminSettingsViewModel: { + /** @description The same sections as IReadOnlyList<IGrouping<string, SettingState>> AdminSettingsViewModel.Sections, each with its key and DOM id, as the JSON carries them. */ + sectionList?: components["schemas"]["SettingsSection"][] | null; + /** @description The file the settings are saved to. */ + overridesPath?: string | null; + /** @description The keys changed since startup that only apply after a restart. */ + pendingRestart?: string[]; + /** @description Why the last save was refused. */ + errors?: string[]; + /** @description The section the IReadOnlyList<string> AdminSettingsViewModel.Errors belong to. */ + errorSection?: string | null; + /** @description The per-source log levels (`Serilog:MinimumLevel:Override`) shown under the Serilog section. */ + logLevels?: components["schemas"]["LogLevelOverride"][]; + /** @description The level names offered for a source. */ + logLevelNames?: string[] | null; + /** @description The named OpenID Connect providers (`Accounts:OpenIdConnectProviders`) shown in the "Sign-in providers" panel of the Accounts section. No secret is carried. */ + signInProviders?: components["schemas"]["SignInProviderView"][]; + /** @description Why the overrides file could not be read, or null. */ + loadError?: string | null; + /** @description The state of each telemetry signal for the Telemetry section, or null when the host exports no telemetry. */ + telemetrySignals?: components["schemas"]["TelemetrySignalReport"][] | null; + /** + * @description True when this host exports telemetry (registers ITelemetryDiagnostics). When false the Telemetry + * section stays editable (the settings file may be shared with a host that does export) but a note says it has no effect here. + */ + hostExportsTelemetry?: boolean; + telemetryTest?: (null) | components["schemas"]["TelemetryTestOutcome"]; + /** + * @description Whether the running database is relational, so a change of database can copy the data (the "Copy all data" option of the + * Database section). + */ + canCopyDatabase?: boolean; + /** @description The `Database:Type` values a copy can target; the option is hidden for any other type. */ + copyTargetTypes?: string[]; + copyStatus?: components["schemas"]["DatabaseCopyStatus"]; + /** + * @description The DOM id (slug) of the section shown; every other section is rendered `hidden`. Chosen by the workflow: the failed + * section, else the Telemetry section after "Test connection", else the `?section=` value, else the first section. The URL + * fragment is only known to the browser, so the page's script applies it on load unless bool AdminSettingsViewModel.SelectionLocked. + */ + selectedId?: string; + /** @description True when the server picked the section for a reason the URL fragment must not override (a failed save, a connection test). */ + selectionLocked?: boolean; + message?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What `GET /api/ui/antiforgery` answers: the request token to send with a cookie session. */ + AntiforgeryTokenModel: { + /** @description The header to send the token in (`X-XSRF-TOKEN`). */ + headerName?: string | null; + /** @description The request token. It is bound to the signed-in user: ask again after signing in or out. */ + requestToken?: string | null; + }; + /** @description What the REST API page shows (also the model of its JSON twin). */ + ApiCatalogViewModel: { + /** @description Every operation, ordered by path. */ + endpoints: components["schemas"]["ApiEndpointSummary"][]; + /** @description The address of the API on this server. */ + apiBase: string; + /** @description The header that carries the password of the owner. */ + confirmHeader: string; + /** @description Where the OpenAPI document is. */ + openApiUrl?: string | null; + }; + /** @description One operation of the REST API as the page (and the JSON twin) lists it: flat, with no reflection objects. */ + ApiEndpointSummary: { + /** @description The HTTP method. */ + method: string; + /** @description The path template (`/api/v1/groups/{name}`). */ + path: string; + /** @description What the operation does. */ + summary: string; + uiScreen: components["schemas"]["ScreenRef"]; + /** @description Whether the owner's password is asked (the confirmation header). */ + confirm: boolean; + }; + /** @description What the new-key form posts (and the body of `POST /api/ui/account/apikeys`). */ + ApiKeyForm: { + /** @description The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it. */ + password?: string | null; + /** @description What the key is for. */ + description?: string | null; + /** @description The scopes of the new key. */ + scopes?: string[]; + /** @description The package IDs the key applies to. */ + packageGlobPattern?: string; + /** + * Format: int32 + * @description Days until the key expires; none = never. + */ + expiresInDays?: number | null; + /** @description The keys of the repositories the new key is limited to; none (the default) means every repository. */ + repositoryKeys?: number[]; + }; + /** + * @description The API keys screen: the new-key form's fields it repeats and the user's keys. A request binds ApiKeyForm, never this type, + * so the outputs cannot be set from outside. + */ + ApiKeysViewModel: { + /** + * @description The repositories offered in the picker: those the user can read. Empty (picker hidden) where the server holds + * the default repository only. + */ + repositories?: components["schemas"]["RepositoryInfo"][]; + /** @description The user's keys. */ + keys?: components["schemas"]["AccountApiKey"][]; + /** @description The names of the repositories each key (by key id) is limited to. */ + keyRepositories?: { + [key: string]: string[]; + }; + /** @description The key just created. Shown once: only its hash is kept. */ + createdKey?: string | null; + /** + * @description The scopes the new-key form offers: the package scopes, plus string ApiKeyScopes.Admin (the REST API under + * `/api/v1`) for an administrator. + */ + allScopes?: string[]; + /** @description The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it. */ + password?: string | null; + /** @description What the key is for. */ + description?: string | null; + /** @description The scopes of the new key. */ + scopes?: string[]; + /** @description The package IDs the key applies to. */ + packageGlobPattern?: string; + /** + * Format: int32 + * @description Days until the key expires; none = never. + */ + expiresInDays?: number | null; + /** @description The keys of the repositories the new key is limited to; none (the default) means every repository. */ + repositoryKeys?: number[]; + }; + /** @description What the access audit screen (`/admin/audit`) shows: the filter and the matching entries. */ + AuditViewModel: { + /** @description The user name that made the change. */ + actorFilter?: string | null; + /** @description Part of what the change was done to (a group, target, project or repository name). */ + subject?: string | null; + /** @description First day, `yyyy-MM-dd`. */ + from?: string | null; + /** @description Last day, `yyyy-MM-dd`. */ + to?: string | null; + /** @description The matching entries. */ + entries?: components["schemas"]["AccessAuditEntry"][]; + /** @description Why the filter was not applied, if a date could not be read. */ + filterError?: string | null; + }; + /** @description What the change-email form posts. */ + ChangeEmailForm: { + /** @description The new address. */ + newEmail?: string | null; + /** @description The password, asked again (an account without one needs a fresh provider sign-in instead). */ + password?: string | null; + }; + /** @description What the change-password form posts (the body of `POST /api/ui/account/settings/change-password`). */ + ChangePasswordForm: { + /** @description The current password (an account without one sets its first after signing in again with its provider). */ + currentPassword?: string | null; + /** @description The new password. */ + newPassword?: string | null; + /** @description The new password again. */ + confirmPassword?: string | null; + }; + /** @description What the cluster page shows. */ + ClusterStatus: { + /** @description Whether this node is in a cluster. */ + enabled: boolean; + /** @description This node's name. */ + thisNode: string; + /** @description The store, without credentials. */ + backend: string | null; + /** @description Whether the store answered. */ + backendReachable: boolean; + /** @description The nodes with a recent heartbeat, this one included. */ + nodes: components["schemas"]["NodeInfo"][]; + /** @description The job leases held now. */ + leases: components["schemas"]["LeaseInfo"][]; + /** @description Why the cluster is read-only, or null. */ + gateReason: string | null; + readiness: components["schemas"]["ReadinessReport"]; + }; + /** @description What the cluster screen (`/admin/cluster`) shows: nodes, leases, shared state and health. */ + ClusterViewModel: { + status?: components["schemas"]["ClusterStatus"]; + }; + /** @description The result of following the link of a confirmation email. */ + ConfirmEmailViewModel: { + /** @description Whether the link was valid. */ + succeeded?: boolean; + /** @description Whether the link changed the address of an existing account. */ + emailChanged?: boolean; + /** @description Whether the account still waits for an administrator (`Accounts:RequireApproval`) after the confirmation. */ + pendingApproval?: boolean; + }; + /** + * @description The fields of the contact-owners form as the screen receives them (a page's form post or the JSON body of the twin). It carries no + * validation attributes: the use case validates by itself (ContactOwnersViewModel holds the rules), so a page's model + * binding does not report the same error a second time. + */ + ContactOwnersForm: { + /** @description The message to send to the owners. */ + message?: string | null; + /** @description Whether the sender also gets a copy. */ + copyToSelf?: boolean; + }; + /** + * @description The contact-owners screen (`/packages/{id}/contact-owners`): the two form fields (string? ContactOwnersViewModel.Message, + * bool ContactOwnersViewModel.CopyToSelf, bound on POST) and what the screen shows; filled by the screen's workflow. + */ + ContactOwnersViewModel: { + /** @description The message to send to the owners. */ + message: string | null; + /** @description Whether the sender also gets a copy. */ + copyToSelf?: boolean; + /** @description The package ID as stored, which is the only text that reaches the subject. */ + packageId?: string | null; + /** @description Whether the message was sent. */ + sent?: boolean; + /** @description Why the message was not sent, or null. */ + error?: string | null; + /** @description Replies come to the sender's address, so there must be one, and it must be confirmed: an unconfirmed address could be anyone's. */ + senderHasEmail?: boolean; + }; + /** @description What the "create an organization" form posts. */ + CreateOrganizationForm: { + /** @description The organization's name. */ + name?: string | null; + }; + /** + * @description The stage a database copy is in. + * @enum {string} + */ + DatabaseCopyPhase: "Idle" | "Queued" | "Checking" | "Migrating" | "Copying" | "Verifying" | "SavingSettings" | "RollingBack" | "Succeeded" | "Failed"; + /** @description A snapshot of the copy's progress, as shown by the Settings page. Holds no connection string. */ + DatabaseCopyStatus: { + phase: components["schemas"]["DatabaseCopyPhase"]; + /** @description The table being copied, or null. */ + table: string | null; + /** + * Format: int64 + * @description Rows of Table copied so far. + */ + tableRowsCopied: number; + /** + * Format: int64 + * @description Rows of Table in the source. + */ + tableRowsTotal: number; + /** + * Format: int32 + * @description Tables completed. + */ + tablesDone: number; + /** + * Format: int32 + * @description Tables to copy. + */ + tablesTotal: number; + /** + * Format: int64 + * @description Rows copied over all tables. + */ + rowsCopied: number; + /** + * Format: int64 + * @description Rows to copy over all tables. + */ + rowsTotal: number; + /** @description Why the copy was refused or failed. */ + errors: string[]; + /** @description A one-line summary of the current state. */ + message: string | null; + /** @description A copy is queued or running. */ + isActive?: boolean; + /** @description The copy ended, either way. */ + isFinished?: boolean; + /** @description The copy succeeded: the settings are saved and the process must restart to use them. */ + restartRequired?: boolean; + }; + /** + * @description The progress of the database copy as the Settings page polls it (`?handler=CopyStatus`): the properties are those the page's script reads + * (`phase` as the phase name, `active`, `finished`, `succeeded`, `restartRequired` ...). Holds no connection string. + */ + DatabaseCopyStatusView: { + /** @description The stage, by name. */ + phase: string; + /** @description A copy is queued or running. */ + active: boolean; + /** @description The copy ended, either way. */ + finished: boolean; + /** @description The copy succeeded. */ + succeeded: boolean; + /** @description The settings are saved and the process must restart to use them. */ + restartRequired: boolean; + /** @description The table being copied, or null. */ + table: string | null; + /** + * Format: int64 + * @description Rows of the table copied so far. + */ + tableRowsCopied: number; + /** + * Format: int64 + * @description Rows of the table in the source. + */ + tableRowsTotal: number; + /** + * Format: int32 + * @description Tables completed. + */ + tablesDone: number; + /** + * Format: int32 + * @description Tables to copy. + */ + tablesTotal: number; + /** + * Format: int64 + * @description Rows copied over all tables. + */ + rowsCopied: number; + /** + * Format: int64 + * @description Rows to copy over all tables. + */ + rowsTotal: number; + /** @description A one-line summary of the current state. */ + message: string | null; + /** @description Why the copy was refused or failed. */ + errors: string[]; + }; + /** @description What the delete-user screen (`/admin/users/{name}/delete`) shows: what the deletion would remove or change. */ + DeleteUserViewModel: { + /** @description The user to delete (route). */ + name?: string | null; + /** @description "keep" (default) or "delete": what to do with the IDs only this user owns. */ + soleOwned?: string; + preview?: (null) | components["schemas"]["AdminDeletionPreview"]; + /** @description Whether the user is the server's only administrator. */ + lastAdministrator?: boolean; + /** @description Read-only mode: the account may go, but package files are not deleted. */ + isReadOnlyMode?: boolean; + /** @description Why the deletion was refused. */ + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What stops a user from deleting their account. */ + DeletionBlockers: { + /** + * @description Package IDs the user is the only direct owner of, in any repository (ownership is per repository, so the same + * ID in two repositories counts once each). Same rule as + * Task<OwnerChangeResult> PackageOwnershipService.RemoveOwnerAsync(string? packageId, string ownerName, CancellationToken cancellationToken): an owned ID keeps an owner. + */ + lastOwnerPackageIds: string[]; + /** + * @description Organizations the user is the last administrator of while others still belong to it, or + * that own packages and so cannot be left without anyone to run them. Same rule as + * Task<bool> PackageOwnershipService.RemoveMemberAsync(string organizationName, string userId, CancellationToken cancellationToken). + */ + organizations: string[]; + /** + * @description The user is the server's only administrator, so deleting them would leave nobody able to + * change the settings. + * @default false + */ + lastAdministrator: boolean; + /** @description Per-repository detail of IReadOnlyList<string?> DeletionBlockers.LastOwnerPackageIds; never null. */ + lastOwnerPackages?: components["schemas"]["SoleOwnedPackage"][] | null; + /** @description Whether anything blocks the deletion. */ + any?: boolean; + }; + DependencyGroupModel: { + name?: string | null; + dependencies?: components["schemas"]["DependencyModel"][] | null; + }; + DependencyModel: { + packageId?: string | null; + versionSpec?: string | null; + }; + /** @description What the Docker front page (`/docker-images`) shows: this page of images and the commands for the client. */ + DockerImagesViewModel: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The page, from 1. + */ + pageIndex?: number; + result?: components["schemas"]["OciImagePage"]; + /** @description The registry host as a Docker client writes it (`host:port`). */ + host?: string; + /** @description Whether the registry is reached over plain http (the Docker daemon then needs it as an insecure registry). */ + isHttp?: boolean; + /** @description The repository's name, the first path segment of every image reference. */ + repositoryName?: string; + /** @description Whether the repository caches an upstream registry (it takes no pushes). */ + isRemote?: boolean; + /** @description Whether the repository merges other repositories (a push goes to its deploy repository). */ + isVirtual?: boolean; + /** @description Whether another page follows. */ + hasNext?: boolean; + commandTabs?: components["schemas"]["InstallSnippet"][]; + }; + /** @description What the page of one Docker image (`/docker-images/{image}`, `?digest=` for a manifest) shows. */ + DockerImageViewModel: { + /** @description The image name from the address (it may contain slashes). */ + image?: string | null; + /** @description The manifest to show in full (`?digest=`), or null for the overview. */ + digest?: string | null; + /** @description Narrows the referrers to one artifact type (`?artifactType=`); empty keeps them all. */ + artifactType?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with: 200, or 404 when the image or manifest does not exist (the page then explains). + */ + statusCode?: number; + info?: (null) | components["schemas"]["OciImageInfo"]; + selected?: (null) | components["schemas"]["OciManifestDetail"]; + /** @description The manifests whose `subject` is the chosen manifest (signatures, SBOMs). Empty without a selection. */ + referrers?: components["schemas"]["OciDescriptor"][]; + /** @description The registry host as a Docker client writes it. */ + host?: string; + /** @description The repository's name. */ + repositoryName?: string; + /** @description Whether the repository caches an upstream registry (it takes no pushes). */ + isRemote?: boolean; + /** @description Whether the signed-in user holds Delete on the image, so the manage page is offered. */ + canManage?: boolean; + pullTabs?: components["schemas"]["InstallSnippet"][]; + /** @description The address of the registry API for the image (what a script calls). */ + registryUrl?: string; + }; + /** @description The form of the Docker management handlers; every one asks for the caller's password. */ + DockerManageForm: { + /** @description The tag to delete (`DeleteTag`). */ + tag?: string | null; + /** @description The manifest digest to delete (`DeleteManifest`). */ + digest?: string | null; + /** @description The caller's password. */ + password?: string | null; + }; + /** @description What the Docker image management screen (`/docker-manage/{**image}`) shows; filled by the screen's workflow. */ + DockerManageViewModel: { + /** @description The image name from the address (it may contain slashes). */ + image?: string | null; + info?: (null) | components["schemas"]["OciImageInfo"]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether string? DockerManageViewModel.Message reports a refusal. */ + failed?: boolean; + /** @description Whether the user has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + }; + /** @description The policy in force for a repository: its own, else its project's, else none. */ + EffectiveScanPolicy: { + values: components["schemas"]["ScanPolicyValues"]; + from: (null) | components["schemas"]["ScanPolicyScope"]; + /** @description The repository or project name it is stored for, or null. */ + name: string | null; + }; + /** @description The model of a screen that shows nothing but itself (the sign-out button), or of an action that only continues elsewhere. */ + EmptyScreen: Record; + /** @description A configured external provider as the account settings list it for one user. */ + ExternalLoginStatus: { + /** @description The provider id. */ + id: string; + /** @description The provider's name. */ + displayName: string; + /** @description Whether the account has a linked login at this provider. */ + linked: boolean; + }; + /** @description An external sign-in provider as a screen offers it (one button per provider). */ + ExternalProviderInfo: { + /** @description The provider id: the value a form or `/api/ui/session/external/{provider}` names it by. */ + id: string; + /** @description The name on the button. */ + displayName: string; + }; + FeedStatistics: { + /** Format: int32 */ + packageIds?: number; + /** Format: int32 */ + packageVersions?: number; + /** Format: int64 */ + downloads?: number; + /** @description The most downloaded package IDs, all versions together. */ + topPackages?: components["schemas"]["PackageDownloads"][] | null; + /** @description The most recently published versions. */ + recentVersions?: components["schemas"]["PackageDownloads"][] | null; + }; + /** @description What the "forgot password" form posts. */ + ForgotPasswordForm: { + /** @description The user name or email address. */ + identifier: string | null; + }; + /** @description The "forgot password" screen. A request binds ForgotPasswordForm, never this type. */ + ForgotPasswordViewModel: { + /** @description Whether the request was answered (always the same answer, see the use case). */ + sent?: boolean; + /** @description The user name or email address. */ + identifier: string | null; + }; + /** @description An input of the create form a format contributes. */ + FormatCreateField: { + /** @description The key in the dictionary string? IFormatModule.CreateSettings(IReadOnlyDictionary<string, string?> fields) receives. */ + name: string; + /** @description The visible label. */ + label: string; + /** @description One line of explanation, or null. */ + help?: string | null; + /** + * @description Whether an empty value is refused by the form. + * @default false + */ + required: boolean; + /** @description For a choice: the allowed values; null for free text. */ + options?: string[] | null; + }; + /** @description A link a format contributes to the administration of a repository: to one of its screens or to a path under its base. */ + FormatLink: { + /** @description A stable identifier (`browse`, `upload`); becomes the CSS class `repository-{id}`. */ + id?: string | null; + /** @description The visible text. */ + label?: string | null; + /** @description The MVC controller (without the suffix) of the screen it opens; null for a path link. */ + controller?: string | null; + /** @description The action of that controller that shows the screen; null for a path link. */ + action?: string | null; + /** @description A path under the repository base; null for a screen link. */ + path?: string | null; + /** @description Shown only for repositories that take uploads (not a remote one, nor a virtual one without a deploy repository). */ + needsUploads?: boolean; + }; + /** @description One format with what it offers, as the formats screen lists it. */ + FormatRow: { + module: components["schemas"]["IFormatModule"]; + /** + * Format: int32 + * @description How many repositories use it. + */ + repositories: number; + /** @description The capabilities its services implement. */ + capabilities: string[]; + }; + /** @description What the formats screen (`/admin/formats`) lists: the package formats this server can host. */ + FormatsViewModel: { + /** @description The formats. */ + rows?: components["schemas"]["FormatRow"][]; + }; + /** @description The frameworks of one package, as the package page's Frameworks tab shows them. */ + FrameworkGroup: { + /** @description The family (.NET, .NET Core, .NET Standard, .NET Framework, Other). */ + name?: string | null; + /** @description Frameworks the package ships assets for. */ + declared?: string[] | null; + /** @description Frameworks the package works with without declaring them. */ + computed?: string[] | null; + }; + /** @description Giving a principal the ticked actions through a permission target, replacing an earlier grant to it. */ + GrantForm: { + principalType: (null) | components["schemas"]["PrincipalType"]; + /** @description The principal's name. */ + principalName: string | null; + /** @description The ticked AccessAction names (`Read`, `Annotate`, `Deploy`, `Delete`, `Manage`); none removes the grant. */ + actions: string[] | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** @description A grant, with the target and principal in words. */ + GrantInfo: { + target: string; + principalType: components["schemas"]["PrincipalType"]; + principalId: string; + principal: string; + actions: components["schemas"]["AccessAction"]; + }; + /** @description A new group. */ + GroupCreation: { + /** @description The group's name. */ + name: string | null; + /** @description What the group is for, or null. */ + description: string | null; + }; + /** @description A group with its members and the grants naming it. */ + GroupDetails: { + group: components["schemas"]["GroupSummary"]; + members: components["schemas"]["GroupMemberInfo"][]; + grants: components["schemas"]["GrantInfo"][]; + }; + /** @description What the group screen (`/admin/groups/{name}`) shows: the group, its members and the member search. */ + GroupDetailViewModel: { + /** @description The group name (route). */ + name?: string | null; + /** @description User-name search for the member picker (contains). */ + q?: string | null; + group?: (null) | components["schemas"]["GroupDetails"]; + /** @description The users found by string? GroupDetailViewModel.Q, not yet members. */ + found?: components["schemas"]["GroupMemberInfo"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Adding a user to a group or removing them. */ + GroupMemberChange: { + /** @description The user's id (string GroupMemberInfo.UserId). */ + userId: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** @description A member of a group. */ + GroupMemberInfo: { + userId: string; + userName: string; + }; + /** @description Renaming a group. */ + GroupRename: { + /** @description The new name. */ + newName: string | null; + }; + /** @description A group as the admin pages list it. */ + GroupSummary: { + /** Format: int32 */ + key: number; + name: string; + description: string | null; + isBuiltIn: boolean; + /** Format: int32 */ + memberCount: number; + }; + /** @description What the groups screen (`/admin/groups`) shows: the groups and the new-group form. */ + GroupsViewModel: { + /** @description The new group name. */ + name?: string | null; + /** @description The new group description. */ + description?: string | null; + /** @description The groups. */ + groups?: components["schemas"]["GroupSummary"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description One probe of the readiness check. */ + HealthProbe: { + /** @description `database`, `storage` or `cluster`. */ + name: string; + /** @description Whether it answered. */ + healthy: boolean; + /** @description A short, credential-free note (the exception type when it failed). */ + detail: string | null; + /** + * @description The probe is reported but a failure does not make the node unready (the shared store: a node keeps serving without it). + * @default false + */ + informational: boolean; + }; + HtmlString: { + value: string | null; + }; + /** + * @description A long-running maintenance operation an administrator can start from the web UI for one repository + * (what the `catalog rebuild` and `import downloads` commands do). Registered as a singleton. + */ + IAdminOperation: { + /** @description The stable id used in forms and status (`catalog-rebuild`). */ + name?: string | null; + title?: string | null; + description?: string | null; + /** + * @description Whether the operation deletes data, so the Operations page asks the administrator's password again before it starts it (as the + * other destructive pages do). Default: no. + */ + requiresConfirmation?: boolean; + }; + /** + * @description One package format (NuGet, npm, later Maven and OCI) as the common code sees it: what its repositories are called and where + * they live, which kinds a repository of it can have, the UI it contributes, and how its artifacts are counted and purged. + * A module only describes the format; what it does per request is a set of services registered beside it + * (IFormatIndexer, IFormatSearchProvider, IFormatRetentionHooks, + * IFormatScanner, looked up with T? FormatServices.GetFormatService<T>(IServiceProvider provider, RepositoryFormat format)) and the format's own controllers, + * whose routes go through `BaGetEndpointBuilder.MapRoute` with the module's RepositoryFormat IFormatModule.Format. + */ + IFormatModule: { + format?: components["schemas"]["RepositoryFormat"]; + /** @description The name shown to people: `NuGet`, `npm`. */ + displayName?: string | null; + /** + * @description The path segment (or segments, without slashes at the ends) every route of the format starts with, after the repository + * base: `npm`. Empty for NuGet, whose routes were there first. + */ + routePrefix?: string | null; + /** + * @description The address a client is configured with, relative to the repository base (`r/{repo}/`, or the root for the default + * repository): `v3/index.json` for NuGet, `npm/` for npm. + */ + feedPath?: string | null; + /** + * @description The kinds of repository that can be created through IRepositoryService without a dedicated administration + * service (a virtual repository is created with its members by IVirtualRepositoryAdministration and is not + * listed here). Kinds not listed are refused for this format. + */ + creatableKinds?: components["schemas"]["RepositoryKind"][] | null; + /** + * @description Whether virtual repositories of this format exist (Task<RepositoryInfo> IVirtualRepositoryAdministration.CreateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null, bool anonymousRead = true, RepositoryFormat format = RepositoryFormat.NuGet)): the format's + * reads then merge the members, and a write goes to the deploy repository. False for a format that has not implemented the + * merge. + */ + supportsVirtual?: boolean; + /** + * @description Whether the format stores blobs too large to buffer (Docker layers) and so needs a store that is an + * IStreamingStorageService. A repository of such a format is refused at creation when the configured store + * cannot stream (IStreamingStorageService StreamingStorage.Require(IStorageService? storage, string purpose)). + */ + requiresStreamingStorage?: boolean; + /** + * @description The top-level storage folders the format writes below a repository's string RepositoryStorage.Prefix(RepositoryInfo repository) + * (`packages`, `symbols`…). Two modules may not claim the same folder, nor string RepositoryStorage.ReposFolder: + * FormatRegistry refuses the registration, since a collision would let one format read another's files. + */ + storageFolders?: string[] | null; + /** + * @description What the administrator fills in to create a repository of this format, on top of the name. Empty when a name is all that + * is needed. + */ + createFields?: components["schemas"]["FormatCreateField"][] | null; + }; + /** Format: binary */ + IFormFile: string; + /** @description What the front page and the package list show: the search that was asked for and its results. */ + IndexScreen: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The 1-based page of results. + */ + pageIndex?: number; + /** @description The package type filter, `any` for none. */ + packageType?: string; + /** @description The target framework filter, `any` for none. */ + framework?: string; + /** @description Whether prerelease versions are included. */ + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + /** @description The orders the search provider can apply on the server; with only the default there is nothing to choose. */ + supportedSorts?: components["schemas"]["SearchSort"][]; + /** @description True for the front page: the repository's root with no search. Everything else lists packages. */ + isHome?: boolean; + totals?: (null) | components["schemas"]["FeedStatistics"]; + /** @description The page of results (empty on the front page). */ + packages?: components["schemas"]["SearchResult"][]; + /** @description When each listed package ID was last published, by ID; empty when unsupported. */ + lastUpdated?: { + [key: string]: string; + }; + }; + /** @description One tab of the "install / configure / push" commands of a package, artifact or image page (one tool per tab). */ + InstallSnippet: { + /** @description The tool the tab is for. */ + name?: string | null; + /** @description A shell prompt shown before the first line; not part of the copied text. */ + prefix?: string | null; + /** @description The lines to copy. */ + lines?: string[] | null; + }; + JsonObject: Record; + /** @description A lease as stored: the holder's node, a token that tells two holders of one node apart, and when it was taken. */ + LeaseInfo: { + /** @description The job's name. */ + job: string; + /** @description The holder. */ + node: string; + /** + * Format: date-time + * @description When it was acquired (UTC). + */ + since: string; + }; + /** @description What a legal page (Terms of Use, Privacy Policy) shows: its heading and the operator's Markdown rendered to safe HTML. */ + LegalScreen: { + /** @description The heading and page title. */ + title: string; + /** @description The operator's Markdown file as HTML (raw HTML in the source is escaped, script links neutralised: HtmlString? ReadmeMarkdown.ToSafeHtml(string? markdown)). */ + contentHtml: string; + }; + /** @description What the sign-in form posts (and the body of `POST /api/ui/account/login`). */ + LoginForm: { + /** @description The user name. */ + userName: string | null; + /** @description The password. Never echoed: a screen's model leaves it empty. */ + password: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** + * @description The sign-in screen: the form fields it repeats and what it shows. A request never binds this type (the form is LoginForm), so + * the outputs cannot be set from outside; string? LoginForm.Password is always empty. + */ + LoginViewModel: { + /** @description Whether the registration link is shown. */ + allowRegistration?: boolean; + /** @description Whether sign-in with an external provider is offered (any provider in IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders). */ + hasExternalProvider?: boolean; + /** @description The first provider's display name (kept for clients that offer one button); see IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders. */ + externalProviderName?: string | null; + /** @description The configured external providers, one sign-in button each. */ + externalProviders?: components["schemas"]["ExternalProviderInfo"][]; + /** @description Whether mail is configured (the forgot-password link is shown). */ + emailIsConfigured?: boolean; + /** @description The refusal to show. */ + error?: string | null; + /** @description The notice to show. */ + notice?: string | null; + /** @description The user name. */ + userName: string | null; + /** @description The password. Never echoed: a screen's model leaves it empty. */ + password: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description Setting or removing the lowest level logged for one source. */ + LogLevelForm: { + /** @description The source (a namespace prefix). */ + source: string | null; + /** @description The level (ignored when removing). */ + level: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** + * @description One `Serilog:MinimumLevel:Override:{Source}` entry: the lowest level logged for a source (a namespace or type + * name prefix such as `Microsoft.AspNetCore`). + */ + LogLevelOverride: { + /** @description The namespace or type name prefix. */ + source: string; + /** @description Verbose, Debug, Information, Warning, Error or Fatal. */ + level: string; + /** @description True when the Settings overrides file holds it, so it can be removed from here; false when only a configuration file or the environment sets it. */ + inOverridesFile: boolean; + }; + /** @description An artifact with its versions, newest first. */ + MavenArtifactInfo: { + /** @description The group id. */ + groupId: string; + /** @description The artifact id. */ + artifactId: string; + /** + * Format: date-time + * @description The first deploy (UTC). + */ + created: string; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** @description Its versions, highest first. */ + versions: components["schemas"]["MavenVersionSummary"][]; + latest?: components["schemas"]["MavenVersionSummary"]; + /** @description `group:artifact`. */ + name?: string | null; + }; + /** @description What the Maven front page (`/maven-artifacts`) shows: this page of search results and the client configuration. */ + MavenArtifactsViewModel: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The page, from 1. + */ + pageIndex?: number; + result?: components["schemas"]["MavenSearchPage"]; + settings?: components["schemas"]["MavenRepositorySettings"]; + /** @description The address Maven is configured with for this repository. */ + repositoryUrl?: string; + kind?: components["schemas"]["RepositoryKind"]; + /** @description The repository's name, which is the `id` in `settings.xml` and the POM. */ + repositoryName?: string; + /** @description Whether another page follows. */ + hasNext?: boolean; + configurationTabs?: components["schemas"]["InstallSnippet"][]; + }; + /** @description What the page of one Maven artifact (`/maven-artifacts/{group}/{artifact}/{version?}`) shows. */ + MavenArtifactViewModel: { + /** @description The group id from the address. */ + group?: string | null; + /** @description The artifact id from the address. */ + artifact?: string | null; + /** @description The version from the address; the latest when absent. */ + version?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with: 200, or 404 when the artifact or version does not exist (the page then explains). + */ + statusCode?: number; + info?: (null) | components["schemas"]["MavenArtifactInfo"]; + selected?: (null) | components["schemas"]["MavenVersionDetail"]; + /** @description The address Maven is configured with for this repository. */ + repositoryUrl?: string; + /** @description The repository's name (the `id` in `settings.xml`). */ + repositoryName?: string; + installTabs?: components["schemas"]["InstallSnippet"][]; + /** @description The owners, when accounts are on; empty otherwise. */ + owners?: string[]; + /** @description Whether the signed-in user can open the manage page (an owner or an administrator). */ + canManage?: boolean; + }; + /** @description What the upload page hands to Task<MavenResult> IMavenRepository.DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken). */ + MavenDeployment: { + /** @description The group id. */ + groupId?: string | null; + /** @description The artifact id. */ + artifactId?: string | null; + /** @description The version. */ + version?: string | null; + /** @description The packaging, the extension of the main file when it has no other (default `jar`). */ + packaging?: string | null; + /** @description The classifier of the main file, or null. */ + classifier?: string | null; + /** @description The extension of the main file (default: the packaging). */ + extension?: string | null; + file?: (null) | components["schemas"]["Stream"]; + pom?: (null) | components["schemas"]["Stream"]; + }; + /** @description A file of a version as the pages list it. */ + MavenFileDetail: { + /** @description The file name. */ + fileName: string; + /** @description The classifier, or null. */ + classifier: string | null; + /** @description The extension. */ + extension: string; + /** + * Format: int64 + * @description Bytes. + */ + size: number; + /** @description SHA-1 hex. */ + sha1: string; + /** @description MD5 hex. */ + md5: string; + /** @description SHA-256 hex. */ + sha256: string; + /** @description SHA-512 hex. */ + sha512: string; + /** + * Format: date-time + * @description When stored (UTC). + */ + created: string; + /** @description The snapshot build timestamp, or null. */ + snapshotTimestamp: string | null; + /** + * Format: int32 + * @description The snapshot build number, or 0. + */ + snapshotBuild: number; + }; + /** @description The form of the Maven management handlers: the chosen version and what the handler needs. */ + MavenManageForm: { + /** @description The user or organization (`AddOwner`, `RemoveOwner`). */ + ownerName?: string | null; + /** @description The version whose files are listed, and the one a handler acts on (`DeleteFile`, `DeleteVersion`, `Cleanup`). */ + version?: string | null; + /** @description The file to delete (`DeleteFile`). */ + fileName?: string | null; + /** @description How many snapshot builds to keep (`Cleanup`). */ + keep?: string | null; + /** @description The caller's password, for the deleting handlers. */ + password?: string | null; + }; + /** @description What the Maven artifact management screen (`/maven-manage/{group}/{artifact}`) shows; filled by the screen's workflow. */ + MavenManageViewModel: { + /** @description The group id from the address. */ + group?: string | null; + /** @description The artifact id from the address. */ + artifact?: string | null; + /** @description The version whose files are listed (`?version=`), or null. */ + version?: string | null; + info?: (null) | components["schemas"]["MavenArtifactInfo"]; + selected?: (null) | components["schemas"]["MavenVersionDetail"]; + /** @description The artifact's owners. */ + owners?: components["schemas"]["PackageOwner"][]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether string? MavenManageViewModel.Message reports a refusal. */ + failed?: boolean; + /** @description Whether the signed-in user is an administrator. */ + isAdministrator?: boolean; + /** @description Whether the user manages the artifact only as an administrator (they are not an owner). */ + actingAsAdministrator?: boolean; + /** @description Whether the user has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description `group:artifact`. */ + name?: string | null; + }; + /** + * @description Which versions a local Maven repository accepts. + * @enum {string} + */ + MavenPolicy: "Releases" | "Snapshots" | "Both"; + /** @description A dependency a POM declares (versions and scopes as written; properties are not resolved). */ + MavenPomDependency: { + /** @description The group id. */ + groupId: string; + /** @description The artifact id. */ + artifactId: string; + /** @description The version, or null (managed elsewhere). */ + version: string | null; + /** @description The scope, or null (compile). */ + scope: string | null; + /** @description Whether the dependency is optional. */ + optional: boolean; + }; + /** @description What the search and the pages read from a POM. */ + MavenPomInfo: { + /** @description The group id (the parent's when the POM has none). */ + groupId: string | null; + /** @description The artifact id. */ + artifactId: string | null; + /** @description The version (the parent's when the POM has none). */ + version: string | null; + /** @description The packaging, `jar` by default. */ + packaging: string; + /** @description The `name`. */ + name: string | null; + /** @description The `description`. */ + description: string | null; + /** @description The project `url`. */ + url: string | null; + /** @description The parent as `group:artifact:version`, or null. */ + parent: string | null; + /** @description The declared dependencies, in order. */ + dependencies: components["schemas"]["MavenPomDependency"][]; + }; + /** @description The settings of a local Maven repository, kept as JSON in string? Repository.Settings (no schema of their own). */ + MavenRepositorySettings: { + policy?: components["schemas"]["MavenPolicy"]; + /** + * @description Whether a release file that exists may be deployed again (replaced). The caller then also needs the Delete action, as + * Artifactory's Delete/Overwrite does. Default false: a release is immutable. Snapshots are never refused for this. + */ + allowRedeploy?: boolean; + /** + * Format: int32 + * @description How many timestamped builds of a snapshot version are kept: when a deploy brings a newer build, older ones beyond this + * number are deleted. Zero keeps all (clean up on the artifact's page). + */ + maxSnapshotBuilds?: number; + }; + /** @description A search hit. */ + MavenSearchHit: { + /** @description The group id. */ + groupId: string; + /** @description The artifact id. */ + artifactId: string; + /** @description The newest version (a release if there is one), or null. */ + version: string | null; + /** @description The POM's name of it, or null. */ + name: string | null; + /** @description The POM's description of it, or null. */ + description: string | null; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** @description `group:artifact`. */ + coordinateName?: string | null; + }; + /** @description A page of hits. */ + MavenSearchPage: { + /** + * Format: int32 + * @description All matches. + */ + total: number; + /** @description This page. */ + hits: components["schemas"]["MavenSearchHit"][]; + }; + /** @description What the Maven upload page (`/maven-upload`) shows, before and after a deployment. */ + MavenUploadViewModel: { + /** @description Whether accounts are on (the uploader then signs in). */ + accountsEnabled?: boolean; + /** @description Whether the server is read-only. */ + isReadOnlyMode?: boolean; + /** @description Whether the visitor is signed in. */ + signedIn?: boolean; + /** @description Without accounts there is no user to own an upload, so the uploader proves itself with the API key. */ + needsApiKey?: boolean; + /** @description Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed. */ + nothingCanAuthenticate?: boolean; + /** @description Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in. */ + canUpload?: boolean; + /** @description The address Maven is configured with for this repository. */ + repositoryUrl?: string; + /** @description The repository's name (the `id` in `settings.xml`). */ + repositoryName?: string; + settings?: components["schemas"]["MavenRepositorySettings"]; + /** @description What happened, for the page to show. */ + message?: string | null; + /** @description Whether string? MavenUploadViewModel.Message reports a failure. */ + failed?: boolean; + /** @description The artifact just deployed (`group:artifact`), so the page can link to it. */ + deployedName?: string | null; + /** @description The version just deployed. */ + deployedVersion?: string | null; + posted?: (null) | components["schemas"]["MavenDeployment"]; + /** + * Format: int32 + * @description The HTTP status the page is answered with (200, or the refusal's). + */ + statusCode?: number; + }; + /** @description One version with its files and POM. */ + MavenVersionDetail: { + summary: components["schemas"]["MavenVersionSummary"]; + /** @description Its files, by name. */ + files: components["schemas"]["MavenFileDetail"][]; + pom: (null) | components["schemas"]["MavenPomInfo"]; + /** @description The POM text (for the view), or null. */ + pomText: string | null; + }; + /** @description A version as the artifact page lists it. */ + MavenVersionSummary: { + /** @description The version. */ + version: string; + /** @description Whether it is a snapshot. */ + isSnapshot: boolean; + /** @description The POM's name, or null. */ + name: string | null; + /** @description The POM's description, or null. */ + description: string | null; + /** @description The POM's packaging, or null. */ + packaging: string | null; + /** + * Format: date-time + * @description The first file (UTC). + */ + created: string; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** + * Format: int32 + * @description Files of the version. + */ + fileCount: number; + /** + * Format: int64 + * @description Bytes of the version. + */ + size: number; + /** + * Format: int32 + * @description For a snapshot: how many timestamped builds it holds. + */ + builds: number; + }; + /** @description A node as it publishes itself. */ + NodeInfo: { + /** @description The node's name. */ + id: string; + /** + * Format: date-time + * @description When it started (UTC). + */ + started: string; + /** + * Format: date-time + * @description Its latest heartbeat (UTC). + */ + seen: string; + /** @description The BaGet version it runs. */ + version: string; + /** @description Whether its last readiness check passed. */ + ready: boolean; + /** @description What failed, when it did not. */ + problem: string | null; + /** @description Whether its read-only gate is closed. */ + gateClosed: boolean; + }; + /** @description The form of `Deprecate` and `Undeprecate`. */ + NpmManageDeprecateForm: { + /** @description The version. */ + version?: string | null; + /** @description The deprecation message (`Deprecate` only). */ + message?: string | null; + }; + /** @description The form of the npm management handlers that name an owner. */ + NpmManageOwnerForm: { + /** @description The user or organization. */ + ownerName?: string | null; + }; + /** @description The form of `SetTag`. */ + NpmManageTagForm: { + /** @description The dist-tag. */ + tag?: string | null; + /** @description The version it points at (not used by `RemoveTag`). */ + version?: string | null; + }; + /** @description The form of `Unpublish` (one version) and `UnpublishAll` (the version is ignored); the password confirms. */ + NpmManageUnpublishForm: { + /** @description The version (`Unpublish` only). */ + version?: string | null; + /** @description The caller's password. */ + password?: string | null; + }; + /** @description What the npm package management screen (`/npm-manage/{*id}`) shows; filled by the screen's workflow. */ + NpmManageViewModel: { + /** @description The package name from the address. */ + id?: string | null; + package?: (null) | components["schemas"]["NpmPackageInfo"]; + /** @description The package's owners. */ + owners?: components["schemas"]["PackageOwner"][]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether string? NpmManageViewModel.Message reports a refusal. */ + failed?: boolean; + /** @description Whether the signed-in user is an administrator. */ + isAdministrator?: boolean; + /** @description Whether the user manages the package only as an administrator (they are not an owner). */ + actingAsAdministrator?: boolean; + /** @description Whether the user has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + /** @description How long after publishing a version its owner may unpublish it with Deploy alone. */ + unpublishWindow?: string; + }; + /** @description A package with its versions and dist-tags, as stored. */ + NpmPackageInfo: { + /** @description The name (`@scope/name` for a scoped package). */ + name: string; + /** + * Format: date-time + * @description The first publish. + */ + created: string; + /** + * Format: date-time + * @description The last change. + */ + modified: string; + /** @description Tag to version. */ + distTags: { + [key: string]: string; + }; + /** @description Every version, oldest first by semantic version. */ + versions: components["schemas"]["NpmVersionInfo"][]; + latest?: components["schemas"]["NpmVersionInfo"]; + /** @description The document revision clients send back on a write (`?write=true` reads, `/-rev/{rev}` writes): changes with every change of the package. */ + revision?: string | null; + }; + /** @description What the npm front page (`/npm-packages`) shows: this page of search results and the registry address. */ + NpmPackagesViewModel: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The page, from 1. + */ + pageIndex?: number; + result?: components["schemas"]["NpmSearchPage"]; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + /** @description Whether another page follows. */ + hasNext?: boolean; + }; + /** @description What the page of one npm package (`/npm-packages/{name}`) shows. */ + NpmPackageViewModel: { + /** @description The package name from the address. */ + id?: string | null; + /** @description The version asked for with `?version=`; the latest when absent or unknown. */ + requestedVersion?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with: 200, or 404 when the package does not exist (the page then explains). + */ + statusCode?: number; + package?: (null) | components["schemas"]["NpmPackageInfo"]; + selected?: (null) | components["schemas"]["NpmVersionInfo"]; + readme?: (null) | components["schemas"]["HtmlString"]; + /** @description The dist-tags that point at the selected version. */ + selectedTags?: string[]; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + /** @description Where the selected version's tarball is. */ + tarballUrl?: string | null; + installTabs?: components["schemas"]["InstallSnippet"][]; + /** @description The owners, when accounts are on; empty otherwise. */ + owners?: string[]; + /** @description Whether the signed-in user can open the manage page (an owner or an administrator). */ + canManage?: boolean; + }; + /** @description One package in a search result. */ + NpmSearchHit: { + /** @description The name. */ + name: string; + /** @description The latest version. */ + version: string | null; + /** @description Its description. */ + description: string | null; + /** @description Its keywords. */ + keywords: string[]; + /** + * Format: date-time + * @description The last change. + */ + modified: string; + }; + /** @description A page of packages. */ + NpmSearchPage: { + /** + * Format: int32 + * @description All matches. + */ + total: number; + /** @description This page, ordered by name. */ + hits: components["schemas"]["NpmSearchHit"][]; + }; + /** @description What the npm upload page (`/npm-upload`) shows, before and after a publish. */ + NpmUploadViewModel: { + /** @description Whether accounts are on (the uploader then signs in). */ + accountsEnabled?: boolean; + /** @description Whether the server is read-only. */ + isReadOnlyMode?: boolean; + /** @description Whether the visitor is signed in. */ + signedIn?: boolean; + /** @description Without accounts there is no user to own an upload, so the uploader proves itself with the API key. */ + needsApiKey?: boolean; + /** @description Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed. */ + nothingCanAuthenticate?: boolean; + /** @description Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in. */ + canUpload?: boolean; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + publishLines?: string[]; + /** @description What happened, for the page to show. */ + message?: string | null; + /** @description Whether string? NpmUploadViewModel.Message reports a failure. */ + failed?: boolean; + /** @description The package just published, so the page can link to it. */ + publishedName?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with (200, or the refusal's). + */ + statusCode?: number; + }; + /** @description One published version as stored. */ + NpmVersionInfo: { + /** @description The version string as published. */ + version: string; + /** + * Format: date-time + * @description When it was published. + */ + published: string; + /** @description The deprecation message, or null. */ + deprecated: string | null; + /** + * Format: int64 + * @description Bytes of the tarball. + */ + tarballSize: number; + /** @description The tarball's SRI string (`sha512-…`). */ + integrity: string; + /** @description The tarball's SHA-1 in hex. */ + shasum: string; + manifest: components["schemas"]["JsonObject"]; + /** @description The manifest's `description`, or null. */ + description?: string | null; + /** @description The manifest's `readme`, or null. */ + readme?: string | null; + /** @description The manifest's `license` when it is a string, or null. */ + license?: string | null; + /** @description The manifest's `keywords` that are strings. */ + keywords?: string[] | null; + }; + NuGetVersion: { + version?: string | null; + isLegacyVersion?: boolean; + /** Format: int32 */ + revision?: number; + isSemVer2?: boolean; + originalVersion?: string | null; + /** Format: int32 */ + major?: number; + /** Format: int32 */ + minor?: number; + /** Format: int32 */ + patch?: number; + releaseLabels?: string[] | null; + release?: string | null; + isPrerelease?: boolean; + hasMetadata?: boolean; + metadata?: string | null; + }; + /** @description A descriptor in a referrers index. */ + OciDescriptor: { + /** @description The referrer's media type. */ + mediaType: string; + /** @description Its digest. */ + digest: string; + /** + * Format: int64 + * @description Its size. + */ + size: number; + /** @description Its artifact type, or null. */ + artifactType: string | null; + /** @description Its annotations, or null. */ + annotations: { + [key: string]: string; + } | null; + }; + /** @description One thing a garbage collection removes. */ + OciGcItem: { + kind: components["schemas"]["OciGcItemKind"]; + /** @description A digest or a session reference. */ + subject: string; + /** + * Format: int64 + * @description Bytes it frees (0 for a session). + */ + bytes: number; + /** @description The image it belonged to, if any. */ + image: string | null; + }; + /** + * @description What a garbage collection found (or, outside a dry run, removed). + * @enum {string} + */ + OciGcItemKind: "ExpiredUpload" | "UnreferencedLayer" | "OrphanBlob" | "OrphanFile"; + /** @description The outcome of one garbage collection of a repository. */ + OciGcReport: { + /** @description Whether nothing was changed (the numbers are what a run would remove). */ + dryRun: boolean; + /** @description The repository. */ + repository: string; + /** + * Format: int32 + * @description Upload sessions discarded. + */ + expiredUploads: number; + /** + * Format: int32 + * @description Image-to-layer links dropped (a layer two images hold counts twice). + */ + unreferencedLayers: number; + /** + * Format: int32 + * @description Blobs (rows and files) removed: those no image holds after the links are dropped, orphan rows included. + */ + blobs: number; + /** + * Format: int32 + * @description Files under the blob folder with no row, removed. + */ + orphanFiles: number; + /** + * Format: int64 + * @description Bytes freed by the blobs and orphan files, as far as they are known (an orphan file's size is not). + */ + bytes: number; + /** @description The first of the things removed (the list is capped). */ + items: components["schemas"]["OciGcItem"][]; + /** @description Whether there are more than Items holds. */ + itemsTruncated: boolean; + /** @description Something the run could not do (the store cannot list files), or null. */ + note: string | null; + /** @description One line for the Operations page and the audit log. */ + summary?: string | null; + }; + /** @description An image with its tags and manifests (the image page). */ + OciImageInfo: { + /** @description The image name. */ + name: string; + /** + * Format: date-time + * @description When the first upload arrived (UTC). + */ + created: string; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** @description The tags, by name. */ + tags: components["schemas"]["OciTagInfo"][]; + /** @description The manifests, newest first. */ + manifests: components["schemas"]["OciManifestSummary"][]; + /** + * Format: int64 + * @description Bytes of the distinct blobs the image holds. + */ + size: number; + /** + * Format: int32 + * @description Blobs held by the image that no manifest uses. + */ + unreferencedBlobs: number; + }; + /** @description A page of OciImageSummary. */ + OciImagePage: { + /** + * Format: int32 + * @description All images that matched and may be read. + */ + total: number; + /** @description The page. */ + images: components["schemas"]["OciImageSummary"][]; + }; + /** @description An image as the browse page lists it. */ + OciImageSummary: { + /** @description The image name. */ + name: string; + /** + * Format: int32 + * @description Number of tags. + */ + tags: number; + /** + * Format: int32 + * @description Number of manifests (including indexes). + */ + manifests: number; + /** + * Format: int64 + * @description Bytes of the distinct blobs the image holds. + */ + size: number; + /** + * Format: date-time + * @description The last manifest or tag change (UTC). + */ + modified: string; + }; + /** @description A layer, config or other blob a manifest lists. */ + OciLayerInfo: { + /** @description The digest. */ + digest: string; + /** + * Format: int64 + * @description The size announced by the manifest. + */ + size: number; + /** @description The media type. */ + mediaType: string; + }; + /** @description One manifest in full (the manifest page). */ + OciManifestDetail: { + summary: components["schemas"]["OciManifestSummary"]; + /** @description The manifest document, pretty-printed for display (the stored bytes are unchanged). */ + json: string; + config: (null) | components["schemas"]["OciLayerInfo"]; + /** @description The layers in order (empty for an index). */ + layers: components["schemas"]["OciLayerInfo"][]; + /** @description The entries of an index (empty for a single-image manifest). */ + platforms: components["schemas"]["OciPlatformInfo"][]; + /** @description The manifest's annotations. */ + annotations: { + [key: string]: string; + }; + }; + /** @description A manifest as the image page lists it. */ + OciManifestSummary: { + /** @description Its digest. */ + digest: string; + /** @description Its media type. */ + mediaType: string; + /** + * Format: int64 + * @description Bytes of the manifest document. + */ + size: number; + /** @description Whether it is an index of platform manifests. */ + isIndex: boolean; + /** + * Format: date-time + * @description When it was first pushed to the image (UTC). + */ + created: string; + /** @description The tags that point at it. */ + tags: string[]; + /** @description Its artifact type, or null. */ + artifactType: string | null; + /** @description The digest it refers to, or null. */ + subjectDigest: string | null; + /** @description For a single-image manifest, its platform when the config says so (`linux/amd64`); otherwise null. */ + platform: string | null; + /** + * Format: int32 + * @description Number of layers (0 for an index). + */ + layerCount: number; + /** + * Format: int64 + * @description Bytes of the config and layers (the children are not summed for an index). + */ + contentSize: number; + }; + /** @description A platform entry of an index. */ + OciPlatformInfo: { + /** @description The child manifest. */ + digest: string; + /** @description The child's media type. */ + mediaType: string; + /** + * Format: int64 + * @description The child's size. + */ + size: number; + /** @description The operating system, or null. */ + os: string | null; + /** @description The architecture, or null. */ + architecture: string | null; + /** @description The variant (`v7`), or null. */ + variant: string | null; + /** @description Whether the child manifest is in this image. */ + present: boolean; + /** @description The platform as one string: `linux/arm64/v8` (or `unknown` for an entry with none). */ + platform?: string | null; + }; + /** @description A tag of an image. */ + OciTagInfo: { + /** @description The tag. */ + name: string; + /** @description The manifest it points at. */ + digest: string; + /** + * Format: date-time + * @description When it was created or moved (UTC). + */ + updated: string; + }; + /** @description Starting a maintenance operation. */ + OperationForm: { + /** @description The operation's name (`catalog-rebuild`). */ + operation: string | null; + /** @description The repository it runs on. */ + repository: string | null; + /** @description The administrator's password (asked for operations that delete data). */ + password: string | null; + }; + /** @description One row of the operations screen: an operation on a repository. */ + OperationRow: { + operation: components["schemas"]["IAdminOperation"]; + repository: components["schemas"]["RepositoryInfo"]; + status: (null) | components["schemas"]["AdminJobStatus"]; + }; + /** @description What the operations screen (`/admin/operations`) shows: the maintenance operations and the status of each. */ + OperationsViewModel: { + /** @description The operations available on this server, for every repository. */ + rows?: components["schemas"]["OperationRow"][]; + /** @description Whether any job is running (the page refreshes itself). */ + anyRunning?: boolean; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description An account that several users own packages through. */ + Organization: { + /** Format: int32 */ + key?: number; + name?: string | null; + /** Format: date-time */ + created?: string; + }; + /** @description What the organization screen (`/admin/organizations/{name}`) shows: the organization, its members and the last action. */ + OrganizationDetailViewModel: { + /** @description The organization's name (route). */ + name?: string | null; + organization?: (null) | components["schemas"]["Organization"]; + /** @description Its members, by name. */ + members?: components["schemas"]["OrganizationMemberRow"][]; + /** + * Format: int32 + * @description How many package IDs it owns, in every repository. + */ + ownedPackageIds?: number; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Adding a member to an organization, changing their administrator flag or removing them. */ + OrganizationMemberForm: { + /** @description The member's user name. */ + userName: string | null; + /** @description Whether the member administers the organization (ignored when removing). */ + isAdmin: boolean; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description A member as the organization page lists them. */ + OrganizationMemberRow: { + /** @description The user name. */ + userName: string | null; + /** @description Whether the member administers the organization. */ + isAdmin: boolean; + }; + /** @description What happens to one organization when an administrator deletes a member. */ + OrganizationOutcome: { + /** @description The organization. */ + name: string | null; + /** @description A sentence for the confirmation page. */ + outcome: string; + }; + /** @description Renaming an organization. */ + OrganizationRenameForm: { + /** @description The new name. */ + newName: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description An organization as the administrator's list shows it. */ + OrganizationSummary: { + /** @description The name. */ + name: string | null; + /** + * Format: date-time + * @description When it was created. + */ + created: string; + /** + * Format: int32 + * @description How many members it has. + */ + members: number; + /** + * Format: int32 + * @description How many of them administer it. + */ + administrators: number; + /** + * Format: int32 + * @description How many package IDs it owns, counted per repository. + */ + packageIds: number; + }; + /** @description The signed-in user's organizations screen. */ + OrganizationsViewModel: { + /** @description The organizations the user belongs to. */ + organizations?: components["schemas"]["AccountOrganization"][]; + /** @description The answer to the last action. */ + message?: string | null; + }; + /** @description One owned package ID, summarised across its versions. */ + OwnedPackage: { + id?: string | null; + /** @description The highest version, listed or not, or null when no version remains. */ + latestVersion?: string | null; + latestVersionIsListed?: boolean; + /** Format: int32 */ + versionCount?: number; + /** Format: int64 */ + downloads?: number; + }; + Package: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + id?: string | null; + version?: components["schemas"]["NuGetVersion"]; + authors?: string[] | null; + description?: string | null; + /** Format: int64 */ + downloads?: number; + hasReadme?: boolean; + hasEmbeddedIcon?: boolean; + isPrerelease?: boolean; + releaseNotes?: string | null; + language?: string | null; + listed?: boolean; + minClientVersion?: string | null; + /** + * Format: date-time + * @description The time at which the package was published, in UTC. + */ + published?: string; + requireLicenseAcceptance?: boolean; + semVerLevel?: components["schemas"]["SemVerLevel"]; + summary?: string | null; + title?: string | null; + /** Format: uri */ + iconUrl?: string | null; + /** Format: uri */ + licenseUrl?: string | null; + /** Format: uri */ + projectUrl?: string | null; + /** Format: uri */ + repositoryUrl?: string | null; + repositoryType?: string | null; + tags?: string[] | null; + /** + * Format: byte + * @description Used for optimistic concurrency. + */ + rowVersion?: string | null; + dependencies?: components["schemas"]["PackageDependency"][] | null; + packageTypes?: components["schemas"]["PackageType"][] | null; + targetFrameworks?: components["schemas"]["TargetFramework"][] | null; + deprecation?: (null) | components["schemas"]["PackageDeprecation"]; + /** @description The known vulnerabilities affecting this version. */ + vulnerabilities?: components["schemas"]["PackageVulnerability"][] | null; + normalizedVersionString?: string | null; + originalVersionString?: string | null; + iconUrlString?: string | null; + licenseUrlString?: string | null; + projectUrlString?: string | null; + repositoryUrlString?: string | null; + }; + /** + * @description How BaGet should interpret package deletion requests. + * See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package + * @enum {string} + */ + PackageDeletionBehavior: "Unlist" | "HardDelete"; + PackageDependency: { + /** Format: int32 */ + key?: number; + /** @description The dependency's package ID. Null if this is a dependency group without any dependencies. */ + id?: string | null; + /** @description The dependency's package version. Null if this is a dependency group without any dependencies. */ + versionRange?: string | null; + targetFramework?: string | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** @description A package that depends on the queried package. */ + PackageDependent: { + /** @description The dependent package id. */ + id?: string | null; + /** @description The description of the dependent package. */ + description?: string | null; + /** + * Format: int64 + * @description The total downloads for the dependent package. + */ + totalDownloads?: number; + }; + /** + * @description A package version marked as deprecated. + * See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation + */ + PackageDeprecation: { + /** Format: int32 */ + key?: number; + /** + * @description Why the package was deprecated. The protocol defines "Legacy", "CriticalBugs" + * and "Other"; a package may carry more than one. + */ + reasons?: string[] | null; + /** @description Free text explaining the deprecation. Optional. */ + message?: string | null; + /** @description The ID of the package to use instead. Null if none was suggested. */ + alternatePackageId?: string | null; + /** + * @description The versions of the alternate package that may be used, or "*" for any. + * Null if no alternate package was suggested. + */ + alternateVersionRange?: string | null; + /** + * Format: int32 + * @description The key of the deprecated package version. Nullable so that the relationship + * stays optional in the database: a required one would need a foreign key change, + * which SQLite cannot make in place. + */ + packageKey?: number | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** @description What the package page shows about the version it displays (a flat copy of the stored package, with no navigation properties). */ + PackageDetails: { + /** @description The package ID. */ + id?: string | null; + /** @description The normalized version. */ + version?: string | null; + /** @description The description. */ + description?: string | null; + /** @description The release notes. */ + releaseNotes?: string | null; + /** @description The project website, or an empty string. */ + projectUrl?: string | null; + /** @description The source repository, or an empty string. */ + repositoryUrl?: string | null; + /** + * Format: int64 + * @description The downloads of this version. + */ + downloads?: number; + /** @description The authors. */ + authors?: string[]; + }; + PackageDownloads: { + id?: string | null; + /** @description Null when the downloads are a whole package ID's. */ + version?: string | null; + /** Format: int64 */ + downloads?: number; + /** Format: date-time */ + published?: string | null; + }; + /** @description The form of `Deprecate`. */ + PackageManageDeprecateForm: { + /** @description The version. */ + version?: string | null; + /** @description The reasons (at least one of `Legacy`, `CriticalBugs`, `Other`). */ + reasons?: string[] | null; + /** @description Free text, optional. */ + message?: string | null; + /** @description The package to use instead, optional. */ + alternatePackageId?: string | null; + /** @description The versions of it that may be used, optional (needs string? PackageManageDeprecateForm.AlternatePackageId). */ + alternateVersionRange?: string | null; + }; + /** @description A version's deprecation. */ + PackageManageDeprecation: { + /** @description Why (`Legacy`, `CriticalBugs`, `Other`). */ + reasons: string[]; + /** @description Free text, or null. */ + message: string | null; + /** @description The package to use instead, or null. */ + alternatePackageId: string | null; + /** @description The versions of it that may be used, or null. */ + alternateVersionRange: string | null; + }; + /** @description The form of a permanent deletion of a version (administrators; the password confirms). */ + PackageManageHardDeleteForm: { + /** @description The version. */ + version?: string | null; + /** @description The caller's password. */ + password?: string | null; + }; + /** @description An owner of a package ID. */ + PackageManageOwner: { + /** @description The user or organization name. */ + ownerName: string | null; + /** @description Whether the ID is reserved for this owner. */ + isVerified: boolean; + }; + /** @description The form of a handler that names an owner. */ + PackageManageOwnerForm: { + /** @description The user or organization. */ + ownerName?: string | null; + }; + /** @description The form of a handler that only asks for the password. */ + PackageManagePasswordForm: { + /** @description The caller's password. */ + password?: string | null; + }; + /** @description The form of `RemoveVulnerability`. */ + PackageManageRemoveVulnerabilityForm: { + /** @description The version. */ + version?: string | null; + /** + * Format: int32 + * @description The vulnerability's key. + */ + key?: number; + }; + /** @description An open abuse report. */ + PackageManageReport: { + /** + * Format: int32 + * @description The report's key (what `ResolveReport` takes). + */ + key: number; + /** @description The reported version. */ + packageVersion: string | null; + /** @description The reason given. */ + reason: string | null; + /** @description The details given. */ + details: string | null; + /** @description Where to reply, if the reporter gave an address. */ + reporterEmail: string | null; + }; + /** @description The form of `ResolveReport`. */ + PackageManageReportForm: { + /** + * Format: int32 + * @description The report's key. + */ + key?: number; + }; + /** + * @description What the package management screen (`/packages/{id}/manage`) shows, as plain data (the JSON model of `/api/ui/packages/{id}/manage`). + * The page's own `ManageViewModel` is built from it for the view. + */ + PackageManageScreen: { + /** @description The package ID from the address. */ + id?: string | null; + /** @description The ID's owners. */ + owners?: components["schemas"]["PackageManageOwner"][]; + /** @description The ID's versions, newest first, unlisted ones included. */ + versions?: components["schemas"]["PackageManageVersion"][]; + /** @description The open abuse reports against the ID. */ + reports?: components["schemas"]["PackageManageReport"][]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether validation has submissions for the ID. */ + hasValidation?: boolean; + /** @description Whether the ID is verified (reserved). */ + isVerified?: boolean; + /** @description The PDBs indexed from each version's symbol package, by normalized version. */ + symbols?: { + [key: string]: components["schemas"]["PackageManageSymbol"][]; + }; + /** @description Whether the database records symbols per package version. */ + symbolsSupported?: boolean; + /** @description The severity names a vulnerability can have, by their protocol number. */ + severityNames?: string[]; + /** @description Whether the caller is an administrator. */ + isAdministrator?: boolean; + /** @description Whether the caller manages this ID only as an administrator (not as an owner). */ + actingAsAdministrator?: boolean; + /** @description Whether the caller has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + deletionBehavior?: components["schemas"]["PackageDeletionBehavior"]; + /** @description Whether the server refuses writes. */ + isReadOnlyMode?: boolean; + }; + /** @description An indexed PDB of a version. */ + PackageManageSymbol: { + /** @description The PDB file name. */ + fileName: string; + /** @description Its signature key. */ + key: string; + }; + /** @description The form of `SetVerified`. */ + PackageManageVerifiedForm: { + /** @description Whether the ID is verified. */ + verified?: boolean; + }; + /** @description One version of the ID. */ + PackageManageVersion: { + /** @description The version as published (original text). */ + version: string; + /** @description The normalized version, which the forms post back. */ + normalizedVersion: string | null; + /** + * Format: int64 + * @description The download count. + */ + downloads: number; + /** @description Whether the version is listed. */ + listed: boolean; + deprecation: (null) | components["schemas"]["PackageManageDeprecation"]; + /** @description Its vulnerabilities. */ + vulnerabilities: components["schemas"]["PackageManageVulnerability"][]; + }; + /** @description The form of a handler that names a version. */ + PackageManageVersionForm: { + /** @description The (normalized) version. */ + version?: string | null; + }; + /** @description A vulnerability recorded for a version. */ + PackageManageVulnerability: { + /** + * Format: int32 + * @description The row's key (what `RemoveVulnerability` takes). + */ + key: number; + /** @description The advisory. */ + advisoryUrl: string | null; + /** + * Format: int32 + * @description 0 low, 1 moderate, 2 high, 3 critical. + */ + severity: number; + /** @description The affected range, or null. */ + versionRange: string | null; + /** @description Null for a manual entry, `osv` for one the scanner wrote (not editable here). */ + source: string | null; + }; + /** @description The form of `AddVulnerability`. */ + PackageManageVulnerabilityForm: { + /** @description The version. */ + version?: string | null; + /** @description The advisory URL. */ + advisoryUrl?: string | null; + /** + * Format: int32 + * @description 0 low, 1 moderate, 2 high, 3 critical. + */ + severity?: number; + /** @description The affected range, optional. */ + versionRange?: string | null; + }; + /** @description An owner of every version of a package ID. */ + PackageOwner: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + packageId?: string | null; + /** @description A user name or an organization name. */ + ownerName?: string | null; + /** + * @description Set by the server's administrator to mark the ID as reserved for this owner, + * which search reports as "verified". + */ + isVerified?: boolean; + }; + /** @description What the package page shows. */ + PackageScreen: { + /** @description False when the package (or any listed version of it) does not exist; PackageDetails PackageScreen.Package then only names the ID. */ + found?: boolean; + package?: components["schemas"]["PackageDetails"]; + /** @description The package is a dotnet template. */ + isDotnetTemplate?: boolean; + /** @description The package is a dotnet tool. */ + isDotnetTool?: boolean; + /** + * Format: date-time + * @description When any version was last published. + */ + lastUpdated?: string; + /** + * Format: int64 + * @description Downloads of every version. + */ + totalDownloads?: number; + /** @description The packages that depend on this one. */ + usedBy?: components["schemas"]["PackageDependent"][]; + /** @description The dependencies, by framework. */ + dependencyGroups?: components["schemas"]["DependencyGroupModel"][]; + /** @description The listed versions, newest first. */ + versions?: components["schemas"]["PackageVersionEntry"][]; + /** @description The readme as safe HTML (ReadmeMarkdown), or null. */ + readmeHtml?: string | null; + /** @description The frameworks the package supports, by family. */ + frameworkGroups?: components["schemas"]["FrameworkGroup"][]; + /** @description The install commands, one tab per tool. */ + installTabs?: components["schemas"]["InstallSnippet"][]; + /** @description Owner names; empty unless accounts are enabled and the package has owners. */ + owners?: string[]; + /** @description The avatar address of each owner by name; empty when Gravatar is off or accounts are disabled. */ + ownerAvatars?: { + [key: string]: string; + }; + /** + * @description Where the management page is, when the caller may open it (an owner holding the Manage permission, or an administrator), else null. + * The use case answers an application-relative address (`~/packages/…`); the controller resolves it against the path base. + */ + manageUrl?: string | null; + /** @description The icon address. */ + iconUrl?: string | null; + /** @description The license address, null for a license expression or file. */ + licenseUrl?: string | null; + /** @description Where the package file is downloaded. */ + packageDownloadUrl?: string | null; + /** + * @description This version on nuget.info, the web app of NuGet Package Explorer, as nuget.org links it. nuget.info always downloads from + * nuget.org, so the link only works for a package that is also published there. + */ + packageExplorerUrl?: string | null; + }; + PackageType: { + /** Format: int32 */ + key?: number; + name?: string | null; + version?: string | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** + * @description One step of validating a pushed package: a validator's verdict, or the final + * indexing step. A submission is every row sharing a string? PackageValidation.SubmissionId. + */ + PackageValidation: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + submissionId?: string | null; + packageId?: string | null; + /** @description The normalized version. */ + packageVersion?: string | null; + /** + * Format: int32 + * @description The indexed package, once the submission succeeds. Nullable so that the + * relationship is additive; see PackageDeprecation. + */ + packageKey?: number | null; + package?: (null) | components["schemas"]["Package"]; + /** @description The validator's name, or string PackageValidation.IndexType. */ + type?: string | null; + state?: components["schemas"]["PackageValidationState"]; + /** @description Why the step failed, if it did. */ + message?: string | null; + /** Format: date-time */ + created?: string; + /** Format: date-time */ + completed?: string | null; + }; + /** @enum {string} */ + PackageValidationState: "Pending" | "Succeeded" | "Failed"; + /** @description One row of the versions table of the package page. */ + PackageVersionEntry: { + /** @description The normalized version. */ + version: string; + /** + * Format: int64 + * @description Its downloads. + */ + downloads: number; + /** @description Whether it is the version shown. */ + selected: boolean; + /** + * Format: date-time + * @description When it was published. + */ + lastUpdated: string; + }; + /** + * @description A known vulnerability affecting a package version. + * See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info + */ + PackageVulnerability: { + /** Format: int32 */ + key?: number; + /** @description The URL of the advisory describing the vulnerability. */ + advisoryUrl?: string | null; + /** + * Format: int32 + * @description The severity, as the protocol numbers it: 0 low, 1 moderate, 2 high, 3 critical. + */ + severity?: number; + /** @description The range of versions the advisory applies to. */ + versionRange?: string | null; + /** + * @description Who recorded it: null for an entry set through the metadata API or the Manage page, `osv` for one the vulnerability + * scanner wrote from a scan of this version. Setting the list by hand replaces the manual entries only; the next scan + * replaces the scanner's. + */ + source?: string | null; + /** + * Format: int32 + * @description The key of the affected package version. Nullable for the same reason as on + * PackageDeprecation. + */ + packageKey?: number | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** + * @description A known vulnerability affecting a package version, as it appears in the package's + * registration metadata. + * + * See https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#vulnerabilities + */ + PackageVulnerabilityMetadata: { + /** @description The URL of the advisory describing the vulnerability. */ + advisoryUrl?: string | null; + /** + * @description The severity: "0" low, "1" moderate, "2" high, "3" critical. A string in the + * registration metadata, unlike the VulnerabilityInfo resource, which uses a number. + */ + severity?: string | null; + }; + /** @description What a form that only re-asks the password posts (delete the account, turn two-factor off, reset the authenticator). */ + PasswordConfirmationForm: { + /** @description The password, asked again. */ + password?: string | null; + }; + /** @description A write that only asks the administrator's password again (approve an account, delete an organization). */ + PasswordForm: { + /** @description The administrator's password. */ + password: string | null; + }; + /** @description The result of previewing repository and package patterns. */ + PatternPreview: { + /** @description The NuGet repositories whose names match the repository patterns. */ + repositories: string[]; + /** @description The package ID typed in the test box, if any. */ + testPackage: string | null; + test: (null) | components["schemas"]["PatternTest"]; + }; + /** @description The outcome of PatternTest AccessPatterns.Test(IEnumerable<string>? include, IEnumerable<string>? exclude, string packageId). */ + PatternTest: { + /** @description Whether the target applies to the package. */ + matches: boolean; + /** @description Which pattern decided, in words. */ + explanation: string; + }; + /** @description What the permission target screen (`/admin/permissions/{name}`) shows: the patterns, the preview and the grants. */ + PermissionDetailViewModel: { + /** @description The target name (route). */ + name?: string | null; + /** @description Repository names or globs, one per line. */ + repositoryPatterns?: string | null; + /** @description Package ID globs the target applies to, one per line. */ + includePatterns?: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + principalType?: components["schemas"]["PrincipalType"]; + /** @description The user, group or organization name in the grant form. */ + principalName?: string | null; + target?: (null) | components["schemas"]["TargetDetails"]; + preview?: (null) | components["schemas"]["PatternPreview"]; + formActions?: components["schemas"]["AccessAction"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the permission targets screen (`/admin/permissions`) shows: the targets and the new-target form. */ + PermissionsViewModel: { + /** @description The new target name. */ + name?: string | null; + /** @description Repository names or `*` globs, one per line. */ + repositoryPatterns?: string | null; + /** @description Package ID globs the target applies to, one per line; none means all. */ + includePatterns?: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns?: string | null; + /** @description The project that administers the target, if any. */ + project?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + /** @description The targets. */ + targets?: components["schemas"]["TargetSummary"][]; + /** @description The projects a target can belong to. */ + projects?: components["schemas"]["ProjectSummary"][]; + preview?: (null) | components["schemas"]["PatternPreview"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The fields of the permission-target form (new target, or the patterns of an existing one) and its test box. */ + PermissionTargetForm: { + /** @description The new target's name (ignored for an existing target: the route names it). */ + name?: string | null; + /** @description Repository names or `*` globs, one per line. */ + repositoryPatterns?: string | null; + /** @description Package ID globs the target applies to, one per line; none means all. */ + includePatterns?: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns?: string | null; + /** @description For a new target: the project that administers it, or null. */ + project?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + principalType?: (null) | components["schemas"]["PrincipalType"]; + /** @description For an existing target: the principal name in the grant form (kept across a preview). */ + principalName?: string | null; + /** @description The administrator's password (saving the patterns of an existing target). */ + password?: string | null; + }; + /** @description Removing a principal's grant or project role. */ + PrincipalRemoval: { + type: components["schemas"]["PrincipalType"]; + /** @description The principal's id. */ + principalId: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** + * @description Who a PermissionGrant or ProjectMember names. + * @enum {string} + */ + PrincipalType: "User" | "Group" | "Organization"; + /** @description A user's or an organization's public page: the packages it owns. */ + ProfileViewModel: { + /** @description The account's name. */ + name?: string | null; + /** @description Whether the account is an organization. */ + isOrganization?: boolean; + /** @description The owned packages with their downloads. */ + packages?: components["schemas"]["PackageDownloads"][]; + /** @description The members of an organization. */ + members?: string[]; + /** @description Whether the profile is the signed-in user's own. */ + isCurrentUser?: boolean; + /** @description The account's avatar address, or null when Gravatar is off. */ + avatarUrl?: string | null; + }; + /** @description A new project. */ + ProjectCreation: { + /** @description The project's name. */ + name: string | null; + /** @description A name to show, or null. */ + displayName: string | null; + }; + /** @description A project with its repositories, members and targets. */ + ProjectDetails: { + project: components["schemas"]["ProjectSummary"]; + repositories: string[]; + members: components["schemas"]["ProjectMemberInfo"][]; + targets: components["schemas"]["TargetSummary"][]; + }; + /** @description What the project screen (`/admin/projects/{name}`) shows: repositories, members and the project targets. */ + ProjectDetailViewModel: { + /** @description The project name (route). */ + name?: string | null; + project?: (null) | components["schemas"]["ProjectDetails"]; + /** @description The NuGet repositories not yet in this project, for the assignment picker. */ + assignable?: string[]; + /** @description The new target name. */ + targetName?: string | null; + /** @description Repository globs of the new target, one per line (they only ever reach the project repositories). */ + repositoryPatterns?: string | null; + /** @description Include globs of the new target. */ + includePatterns?: string | null; + /** @description Exclude globs of the new target. */ + excludePatterns?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + preview?: (null) | components["schemas"]["PatternPreview"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Giving a user or group a role in a project. */ + ProjectMemberForm: { + type: components["schemas"]["PrincipalType"]; + /** @description The principal's name. */ + principalName: string | null; + role: components["schemas"]["ProjectRole"]; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** @description A member of a project. */ + ProjectMemberInfo: { + principalType: components["schemas"]["PrincipalType"]; + principalId: string; + principal: string; + role: components["schemas"]["ProjectRole"]; + }; + /** @description Putting a repository in a project or taking it out. */ + ProjectRepositoryForm: { + /** @description The repository's name. */ + repository: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** + * @description A member's role in a Project, applying to the project's repositories. + * @enum {string} + */ + ProjectRole: "Viewer" | "Developer" | "Admin"; + /** @description A project as the admin pages list it. */ + ProjectSummary: { + /** Format: int32 */ + key: number; + name: string; + displayName: string | null; + /** Format: int32 */ + repositoryCount: number; + /** Format: int32 */ + memberCount: number; + }; + /** @description What the projects screen (`/admin/projects`) shows: the projects the user may open and the new-project form. */ + ProjectsViewModel: { + /** @description The new project name. */ + name?: string | null; + /** @description The new project display name. */ + displayName?: string | null; + /** @description The projects the signed-in user may open. */ + projects?: components["schemas"]["ProjectSummary"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The fields of a project's new permission target and its test box. */ + ProjectTargetForm: { + /** @description The new target's name. */ + targetName: string | null; + /** @description Repository globs, one per line (they only ever reach the project's repositories). */ + repositoryPatterns: string | null; + /** @description Package ID globs the target applies to, one per line. */ + includePatterns: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns: string | null; + /** @description A package ID to test the patterns with. */ + testPackage: string | null; + }; + /** @description The result of the readiness check. */ + ReadinessReport: { + /** + * Format: date-time + * @description When it ran (UTC). + */ + checkedAt: string; + /** @description Each probe. */ + probes: components["schemas"]["HealthProbe"][]; + /** @description Every probe that decides readiness answered (an informational probe, the shared store, never takes the node out of rotation). */ + isReady?: boolean; + /** @description The failing probes (informational ones too) as one line, or null. */ + problem?: string | null; + }; + /** @description The "confirm it is you" screen of an account without a password. A request binds ReauthenticateForm, never this type. */ + ReauthenticateViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The linked providers to pick from when the account has several (one button each); null otherwise. */ + providers?: components["schemas"]["ExternalProviderInfo"][] | null; + /** @description Where to go after the provider answered; only a local URL is followed. */ + returnUrl?: string | null; + /** @description The id of the linked provider to sign in again with; empty takes the only linked one (several: the screen offers the choice). */ + provider?: string | null; + }; + /** @description What the recovery-code form posts. */ + RecoveryCodeLoginForm: { + /** @description The recovery code. */ + recoveryCode: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description The second step of signing in with a recovery code. A request binds RecoveryCodeLoginForm, never this type. */ + RecoveryCodeLoginViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The recovery code. */ + recoveryCode: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description What the registration form posts. */ + RegisterForm: { + /** @description The wanted user name. */ + userName: string | null; + /** @description The email address. */ + email?: string | null; + /** @description The password. Never echoed. */ + password: string | null; + /** @description The password again. Never echoed. */ + confirmPassword: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description The registration screen. A request binds RegisterForm, never this type; the passwords are always empty here. */ + RegisterViewModel: { + /** @description Whether the account was created but waits for an administrator (`Accounts:RequireApproval`). */ + awaitingApproval?: boolean; + /** @description Whether a confirmation link was mailed. */ + confirmationSent?: boolean; + /** @description Whether the screen asks for an email address. */ + emailRequired?: boolean; + session?: (null) | components["schemas"]["SessionModel"]; + /** @description The wanted user name. */ + userName: string | null; + /** @description The email address. */ + email?: string | null; + /** @description The password. Never echoed. */ + password: string | null; + /** @description The password again. Never echoed. */ + confirmPassword: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description What a remote repository holds and remembers. */ + RemoteCacheOverview: { + status: components["schemas"]["RemoteCacheStatus"]; + /** + * Format: int32 + * @description Package versions stored. + */ + packageCount: number; + /** + * Format: int32 + * @description Distinct package ids stored. + */ + packageIdCount: number; + /** + * Format: int64 + * @description Bytes of the blobs stored (a Docker repository: its layers); 0 when the format does not report it. + * @default 0 + */ + storedBytes: number; + }; + /** @description What the cache of one remote repository looks like right now (in memory, per node; resets on restart). */ + RemoteCacheStatus: { + /** + * Format: int32 + * @description Cached answers of the upstream (version lists and metadata), expired ones included until used or purged. + */ + metadataEntries: number; + /** + * Format: int32 + * @description Remembered "the upstream does not have it" answers still in force. + */ + negativeEntries: number; + /** + * Format: int64 + * @description Answers served from the cache. + */ + hits: number; + /** + * Format: int64 + * @description Questions that went to the upstream. + */ + misses: number; + /** + * Format: int64 + * @description Questions answered "not found" from the negative cache. + */ + negativeHits: number; + /** + * Format: int64 + * @description Expired answers served because the upstream could not be reached. + */ + staleServed: number; + /** + * Format: int64 + * @description Failed attempts to reach the upstream. + */ + failures: number; + /** + * Format: date-time + * @description The last time the upstream answered. + */ + lastSuccessUtc: string | null; + /** + * Format: date-time + * @description The last time it could not be reached. + */ + lastFailureUtc: string | null; + /** + * Format: date-time + * @description When the current run of failures began, or null while it answers. + */ + failingSinceUtc: string | null; + /** @description What failed, without URLs or credentials. */ + lastError: string | null; + }; + /** @description The outcome of asking an upstream whether it answers. */ + RemoteConnectionResult: { + /** @description Whether the upstream answered as the configured protocol requires. */ + success: boolean; + /** @description What was found or what failed, without URLs or credentials. */ + message: string; + /** + * Format: int32 + * @description The HTTP status, when there was an answer. + */ + statusCode: number | null; + /** + * Format: int64 + * @description How long the attempt took. + */ + elapsedMilliseconds: number; + }; + /** + * @description The fields of a remote repository's upstream settings as the create and edit pages post them (prefix + * `Remote`). The password is never rendered back: a blank one on save keeps the stored one. + */ + RemoteFormModel: { + format?: components["schemas"]["RepositoryFormat"]; + /** @description The upstream URL (V3 `index.json` or V2 feed, or an npm registry's base URL). */ + url?: string | null; + protocol?: components["schemas"]["RemoteProtocol"]; + /** @description The HTTP Basic user name, if the upstream needs one. */ + username?: string | null; + /** @description The HTTP Basic password or token; blank keeps the stored one. Input only: a screen never sends it back (the use cases clear it from every model they return). */ + password?: string | null; + /** @description Remove the stored password on save. */ + clearPassword?: boolean; + /** + * Format: int32 + * @description How long the upstream's answers are reused, in seconds (0 = ask every time). + */ + metadataTtlSeconds?: number; + /** + * Format: int32 + * @description How long "not found" is remembered, in seconds (0 = ask every time). + */ + negativeTtlSeconds?: number; + /** + * Format: int32 + * @description The download timeout in seconds. + */ + downloadTimeoutSeconds?: number; + /** @description Never contact the upstream. */ + offline?: boolean; + /** @description Keep what is fetched (off = pass-through). */ + storeLocally?: boolean; + /** @description For display: whether a password is stored. */ + hasPassword?: boolean; + /** @description For display: URL, protocol and timeout are fixed because `Mirror:*` sets them. */ + endpointFromMirror?: boolean; + }; + /** + * @description The protocol a remote repository's upstream speaks. + * @enum {string} + */ + RemoteProtocol: "V3" | "V2" | "Npm" | "Maven" | "Docker"; + /** @description A remote repository as the administration pages edit it. */ + RemoteRepositoryDetail: { + repository: components["schemas"]["RepositoryInfo"]; + settings: components["schemas"]["RemoteRepositorySettings"]; + /** @description Whether a password is stored. */ + hasPassword: boolean; + /** @description Whether it is the string Repository.MirrorName repository the default repository fetches through while `Mirror:Enabled` is set (its URL, protocol and timeout then come from `Mirror:*`). */ + isMirror: boolean; + }; + /** + * @description What a RepositoryKind.Remote repository knows about its upstream: kept as JSON in + * string? Repository.Settings. The password never appears in clear there: it is stored as + * string? RemoteRepositorySettings.ProtectedPassword (see IRemoteCredentialProtector) and string? RemoteRepositorySettings.Password only + * exists in memory. + */ + RemoteRepositorySettings: { + /** @description The upstream: a V3 `index.json` URL or a V2 feed URL, the base URL of an npm registry, the root of a Maven repository or the address of a Docker registry (absolute http or https). */ + url?: string | null; + protocol?: components["schemas"]["RemoteProtocol"]; + /** + * @description The user name sent with HTTP Basic to the upstream's own host, if any. An npm upstream with a password and no user name + * gets the password as a bearer token (npm's `_authToken`) instead. A Docker upstream gets the pair at its token service + * (HTTP Basic, the `docker login` flow) or, when it asks for Basic itself, at its own host; a password with no user name + * is sent as a ready-made bearer token to the registry's own host. + */ + username?: string | null; + /** @description The password as stored (protected). Opaque to everything but RemoteSettingsCodec. */ + protectedPassword?: string | null; + /** + * Format: int32 + * @description How long the upstream's version list and metadata of a package are reused before it is asked again. 0 asks + * every time (what the mirror always did). + */ + metadataTtlSeconds?: number; + /** + * Format: int32 + * @description How long "the upstream does not have it" (404) is remembered. 0 asks every time. + */ + negativeTtlSeconds?: number; + /** @description Offline mode: the upstream is never contacted; only what is already stored (and cached in memory) is served. */ + offline?: boolean; + /** + * @description Whether packages fetched from the upstream are stored (database and files) so later requests, and requests + * while the upstream is down, are served locally. Off, the repository is a pass-through: metadata comes from the + * upstream (cached by int RemoteRepositorySettings.MetadataTtlSeconds), downloads stream through and nothing is kept (so search + * and the package pages stay empty). + */ + storeLocally?: boolean; + /** + * Format: int32 + * @description The time before a download from the upstream times out. + */ + downloadTimeoutSeconds?: number; + }; + /** @description What the "remove a member" (or "leave") form posts. */ + RemoveOrganizationMemberForm: { + /** @description The organization. */ + organization?: string | null; + /** @description The member to remove. */ + userName?: string | null; + }; + /** @description Removing a named OpenID Connect provider saved on the Settings screen. */ + RemoveSignInProviderForm: { + /** @description The provider id. */ + id: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description Creating, saving or testing a replication, or any write of it that asks the password. */ + ReplicationBody: { + form: (null) | components["schemas"]["ReplicationForm"]; + /** @description The administrator's password. */ + password: string | null; + }; + /** + * @description One replication relationship: a local repository and a repository of another BaGet server, copied in one direction. Not + * repository-scoped (the administrator lists configurations across repositories). Its `RepositoryKey` is a Restrict foreign key, and + * so is `ConfigKey` of its runs and ledger: deleting the repository deletes its configurations, runs and ledger first (code, not cascade). + */ + ReplicationConfig: { + /** Format: int32 */ + key?: number; + /** @description Unique, AccessNames rules. */ + name?: string | null; + /** + * Format: int32 + * @description The local int Repository.Key: a local (not remote, not virtual) repository. + */ + repositoryKey?: number; + direction?: components["schemas"]["ReplicationDirection"]; + /** @description The peer server's base address (`https://other.example/`), not a repository feed. */ + peerUrl?: string | null; + /** @description The peer's repository (`default` or its name); it must be of the same format. */ + peerRepository?: string | null; + /** @description A disabled configuration is never run by the schedule or a deploy; a manual run is refused. */ + enabled?: boolean; + /** @description Push only: a deploy to the local repository starts a run (after a short quiet period). */ + onDeploy?: boolean; + /** + * Format: int32 + * @description Run every this many minutes. Null: only when started (or on deploy). + */ + scheduleMinutes?: number | null; + /** @description What was replicated and is later deleted at the source is deleted at the target too (only items this configuration copied). */ + propagateDeletes?: boolean; + conflict?: components["schemas"]["ReplicationConflict"]; + /** + * Format: date-time + * @description When the schedule was set or the configuration enabled; the first scheduled run is due this long after it. + */ + scheduleStart?: string | null; + /** + * Format: date-time + * @description When the last run started (the schedule counts from the later of this and DateTime? ReplicationConfig.ScheduleStart). + */ + lastRun?: string | null; + /** @description One line about the last run. */ + lastResult?: string | null; + /** Format: date-time */ + created?: string; + /** Format: date-time */ + modified?: string; + }; + /** @description A configuration with the names the page shows; the API key is never part of it. */ + ReplicationConfigView: { + config: components["schemas"]["ReplicationConfig"]; + /** @description The local repository's name, or null when it no longer exists. */ + repository: string | null; + format: (null) | components["schemas"]["RepositoryFormat"]; + /** @description Whether a key is stored. */ + hasApiKey: boolean; + lastRun: (null) | components["schemas"]["ReplicationRun"]; + }; + /** @description What one replication's screen (`/admin/replication/{key}`) shows. */ + ReplicationConfigViewModel: { + /** + * Format: int32 + * @description The configuration's key (route). + */ + key?: number; + form?: components["schemas"]["ReplicationForm"]; + view?: (null) | components["schemas"]["ReplicationConfigView"]; + /** @description The log, newest first. */ + runs?: components["schemas"]["ReplicationRun"][]; + job?: (null) | components["schemas"]["ReplicationJobStatus"]; + test?: (null) | components["schemas"]["ReplicationTestResult"]; + /** + * Format: int32 + * @description How many items the local repository holds, or null when it could not be listed. + */ + localItems?: number | null; + /** @description Whether a run is going here (the page refreshes itself). */ + running?: boolean; + /** @description The local repositories a replication can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + resumable?: components["schemas"]["ReplicationRun"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** + * @description What happens when both sides hold the same item with different content. + * @enum {string} + */ + ReplicationConflict: "TargetWins" | "SourceWins"; + /** + * @description Which way a ReplicationConfig copies. + * @enum {string} + */ + ReplicationDirection: "Push" | "Pull"; + /** + * @description What the replication form posts (`Form.*`): a ReplicationConfig as a person types it. The peer's API key is write + * only: it is never filled back into a page; an empty field keeps the stored key. + */ + ReplicationForm: { + name?: string | null; + repository?: string | null; + direction?: components["schemas"]["ReplicationDirection"]; + peerUrl?: string | null; + peerRepository?: string | null; + /** @description The peer's API key (write only). */ + apiKey?: string | null; + /** @description Forget the stored key. */ + clearApiKey?: boolean; + enabled?: boolean; + onDeploy?: boolean; + /** Format: int32 */ + scheduleMinutes?: number | null; + propagateDeletes?: boolean; + conflict?: components["schemas"]["ReplicationConflict"]; + }; + /** @description What the page knows of a replication started since the server began (in memory); the log table is the durable record. */ + ReplicationJobStatus: { + /** Format: int32 */ + configKey?: number; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + /** @description True while the run is going. */ + running?: boolean; + /** @description Why the job did not even begin a run (read-only server, disabled configuration, lease held elsewhere), or null. */ + refusal?: string | null; + }; + /** @description One run of a configuration: the replication log. */ + ReplicationRun: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The int ReplicationConfig.Key. + */ + configKey?: number; + status?: components["schemas"]["ReplicationRunStatus"]; + /** @description `manual`, `resume`, `schedule` or `deploy`. */ + trigger?: string | null; + /** @description The administrator, or `scheduler`. */ + actor?: string | null; + /** + * Format: int32 + * @description The interrupted or failed run this one continues, when started with Resume. + */ + resumedFrom?: number | null; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + /** + * Format: int32 + * @description Items the plan looked at (both sides listed). + */ + examined?: number; + /** + * Format: int32 + * @description Items copied to the target. + */ + transferred?: number; + /** + * Format: int32 + * @description Items the target already had. + */ + skipped?: number; + /** + * Format: int32 + * @description Items deleted at the target because they were deleted at the source. + */ + deleted?: number; + /** + * Format: int32 + * @description Items held differently on both sides that were left alone (target wins) or replaced (source wins). + */ + conflicts?: number; + /** Format: int32 */ + failures?: number; + /** + * Format: int64 + * @description Bytes of artifact content sent or received. + */ + bytes?: number; + /** @description Why the run failed as a whole, or null. */ + error?: string | null; + /** @description The first failures and conflicts, one per line. */ + detail?: string | null; + }; + /** + * @description How a ReplicationRun ended. + * @enum {string} + */ + ReplicationRunStatus: "Running" | "Succeeded" | "Failed" | "Interrupted"; + /** @description What Task<ReplicationTestResult> IReplicationAdministration.TestAsync(ReplicationInput input, CancellationToken cancellationToken) found. */ + ReplicationTestResult: { + /** @description Whether the peer answered as a BaGet server with this repository. */ + ok: boolean; + /** @description A sentence for the administrator (never the key). */ + message: string; + /** + * Format: int64 + * @description How long it took. + */ + elapsedMilliseconds: number; + peerFormat: (null) | components["schemas"]["RepositoryFormat"]; + /** + * Format: int32 + * @description How many items it holds, when it answered. + */ + peerItems: number | null; + }; + /** @description What the replications screen (`/admin/replication`) shows: every replication and the form that creates one. */ + ReplicationViewModel: { + form?: components["schemas"]["ReplicationForm"]; + /** @description Every replication. */ + replications?: components["schemas"]["ReplicationConfigView"][]; + /** @description The local repositories a replication can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the reporter fills in. The field names (Reason, Details, ReporterEmail) are the contract of the form and of the JSON body. */ + ReportAbuseForm: { + /** @description One of string[] AbuseReport.Reasons. */ + reason: string | null; + /** @description What the reporter saw. */ + details: string | null; + /** @description The address of the reporter, optional. */ + reporterEmail?: string | null; + }; + /** @description The report-abuse screen: the package it is about, what was typed, and whether the report was recorded. */ + ReportAbuseScreen: { + /** @description The package ID. */ + id: string | null; + /** @description The package version. */ + version: string | null; + /** @description Reports are kept in the database, which Azure Table storage cannot do. */ + canReport: boolean; + /** @description True once the report was recorded. */ + submitted: boolean; + form: components["schemas"]["ReportAbuseForm"]; + }; + /** + * @description What the repositories screen (`/admin/repositories`) shows: the repositories with their feed addresses, the list filter and + * the create forms. The posted fields of the create forms (string? RepositoriesViewModel.Name, RemoteFormModel RepositoriesViewModel.Remote) live here too, so a refused + * creation shows again what was typed (the typed upstream password excepted: it is never sent back). + */ + RepositoriesViewModel: { + /** @description The name for the repository to create. */ + name?: string | null; + remote?: components["schemas"]["RemoteFormModel"]; + /** @description The repositories. */ + repositories?: components["schemas"]["RepositorySummary"][]; + /** @description Whether the database can hold more than the default repository. */ + canCreate?: boolean; + message?: string | null; + /** @description Why the last action was refused. */ + error?: string | null; + /** @description The format to keep selected after a refused creation. */ + format?: string | null; + /** @description The format the list is narrowed to (`?format=`), or null. */ + filterFormat?: string | null; + /** @description The kind the list is narrowed to (`?kind=`), or null. */ + filterKind?: string | null; + /** @description The name fragment the list is narrowed to (`?q=`), or null. */ + filterName?: string | null; + /** @description Every format this server knows, for the list filter. */ + allFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The formats a remote repository can be created for. */ + remoteFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The formats a virtual repository can be created for. */ + virtualFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The formats other than NuGet that can be created here, with their form fields. */ + otherFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The virtual repositories that have a deploy repository, so take uploads (a remote one takes none). */ + deployable?: string[]; + /** @description The feed address of each repository, by repository name. */ + feeds?: { + [key: string]: string; + }; + /** @description The base address of each repository (where its format's routes start, ends with a slash), by repository name. */ + baseUrls?: { + [key: string]: string; + }; + /** @description The links its format contributes for each repository (browse, upload...), without the upload link where it takes none, by repository name. */ + links?: { + [key: string]: components["schemas"]["FormatLink"][]; + }; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description One repository with what a user may do there and the grants behind it (the account and user pages). */ + RepositoryAccessRow: { + repository: components["schemas"]["RepositoryInfo"]; + explanation: components["schemas"]["AccessExplanation"]; + }; + /** @description Who holds what in one repository (Task<RepositoryAccessSummary> IAccessEvaluator.DescribeAsync(RepositoryInfo repository, CancellationToken cancellationToken)). */ + RepositoryAccessSummary: { + repository: components["schemas"]["RepositoryInfo"]; + /** @description The repository's anonymous-read switch. */ + anonymousRead: boolean; + /** @description The name of the project the repository belongs to, if any. */ + project: string | null; + /** + * @description False where there is no access model (Azure Table): everyone reads, any authenticated + * caller writes, subject to ownership. + */ + modelAvailable: boolean; + /** @description Every grant and project role that applies to the repository. */ + holders: components["schemas"]["AccessReason"][]; + }; + /** + * @description The body of the create forms of the repositories screen (`POST /api/ui/admin/repositories` and its `create/...` handlers). Which fields + * a handler reads is stated on its use case method; the others are ignored. + */ + RepositoryCreateForm: { + /** @description The name of the repository to create. */ + name?: string | null; + /** @description The format (`Npm`, `Maven`, `Docker`...); blank is NuGet where a format may be omitted. */ + format?: string | null; + remote?: components["schemas"]["RemoteFormModel"]; + /** + * @description Whether requests without credentials may read the repository. Null: the default (a local or virtual repository is readable by anyone; a remote + * one only when it has no credentials). + */ + anonymousRead?: boolean | null; + /** @description The administrator's password (creating a remote repository asks for it). */ + password?: string | null; + /** @description The format's own create fields (string FormatCreateField.Name to value) of a local repository of a format other than NuGet. */ + fields?: { + [key: string]: string; + } | null; + }; + /** @description What the delete-repository screen (`/admin/repositories/{name}/delete`) shows. */ + RepositoryDeleteViewModel: { + /** @description The repository's name (route). */ + name?: string | null; + repository?: (null) | components["schemas"]["RepositorySummary"]; + /** @description The virtual repositories that list this repository as a member (the deletion is refused while there are any). */ + referencedBy?: string[]; + /** @description Why the deletion was refused. */ + error?: string | null; + }; + /** + * @description The body of every action of the repository screen (`/api/ui/admin/repositories/{name}/...`), the JSON twin of what the page's forms post. Which fields + * an action reads is stated on its use case method; the others are ignored. + */ + RepositoryEditRequest: { + /** @description Whether requests without credentials may read the repository. */ + anonymousRead?: boolean; + remote?: components["schemas"]["RemoteFormModel"]; + /** @description The package id to resolve in the preview. */ + previewPackageId?: string | null; + /** @description The package version to resolve in the preview. */ + previewVersion?: string | null; + /** @description The package id to purge from the cache. */ + packageId?: string | null; + /** @description The version to purge (blank = every version). */ + packageVersion?: string | null; + /** @description The administrator's password (saving, testing and purging a remote repository ask for it). */ + password?: string | null; + /** @description The member to add, remove or move. */ + member?: string | null; + /** @description `up` or `down`. */ + direction?: string | null; + /** @description The member that receives uploads (blank: none). */ + deploy?: string | null; + /** @description The versions a Maven repository accepts (`Releases`, `Snapshots`, `Both`). */ + policy?: string | null; + /** @description Whether a Maven release may be redeployed (`Yes`/`No`). */ + redeploy?: string | null; + /** @description How many snapshot builds a Maven repository keeps. */ + snapshotBuilds?: string | null; + }; + /** + * @description What the repository screen (`/admin/repositories/{name}`) shows: the repository, its access summary and, by kind, its + * upstream and cache (remote), members and preview (virtual) or Maven settings. The posted fields (anonymous read, upstream, preview + * and purge inputs) live here too, so a refused action shows again what was typed. + */ + RepositoryEditViewModel: { + /** @description The repository's name (route). */ + name?: string | null; + /** @description Whether requests without credentials may read the repository. */ + anonymousRead?: boolean; + repository?: (null) | components["schemas"]["RepositorySummary"]; + remote?: components["schemas"]["RemoteFormModel"]; + remoteDetail?: (null) | components["schemas"]["RemoteRepositoryDetail"]; + mavenSettings?: (null) | components["schemas"]["MavenRepositorySettings"]; + cache?: (null) | components["schemas"]["RemoteCacheOverview"]; + virtualDetail?: (null) | components["schemas"]["VirtualRepositoryDetail"]; + /** @description The repositories that can still be added to a virtual repository. */ + memberCandidates?: components["schemas"]["RepositoryInfo"][]; + /** @description The virtual repositories that list this repository as a member. */ + referencedBy?: string[]; + /** @description The package id to resolve in the preview. */ + previewPackageId?: string | null; + /** @description The package version to resolve in the preview. */ + previewVersion?: string | null; + preview?: (null) | components["schemas"]["ResolutionPreview"]; + testResult?: (null) | components["schemas"]["RemoteConnectionResult"]; + message?: string | null; + /** @description Why the last action was refused. */ + error?: string | null; + /** @description The package id to purge from the cache. */ + packageId?: string | null; + /** @description The version to purge (blank = every version). */ + packageVersion?: string | null; + access?: (null) | components["schemas"]["RepositoryAccessSummary"]; + browseScreen?: components["schemas"]["ScreenRef"]; + /** @description The repository's feed address. */ + feedUrl?: string; + mirrorRepository?: (null) | components["schemas"]["RemoteRepositoryDetail"]; + /** @description Whether `Mirror:Enabled` makes the default repository fetch through RemoteRepositoryDetail? RepositoryEditViewModel.MirrorRepository. */ + mirrorActive?: boolean; + /** @description The name of what a package is called in this repository's format (shown in the labels). */ + packageWord?: string | null; + /** @description What the "version" of a package is called in this repository's format (a Docker image has a tag or a digest). */ + versionWord?: string | null; + /** @description The label of the field that names a package (a Docker image is an image name). */ + packageLabel?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** + * @description The package format a Repository serves. Stored as its name, so a value may be appended + * but never renumbered or renamed. + * @enum {string} + */ + RepositoryFormat: "NuGet" | "Npm" | "Maven" | "Docker"; + /** @description A package format a repository can be created for, with the extra fields its create form asks (the JSON form of an IFormatModule). */ + RepositoryFormatChoice: { + format: components["schemas"]["RepositoryFormat"]; + /** @description Its name for people (`npm`, `Maven`). */ + displayName: string; + /** @description What the administrator fills in to create a local repository of it, besides the name. */ + createFields: components["schemas"]["FormatCreateField"][]; + }; + /** + * @description What a request, job or command needs to know about the repository it works in: immutable, and small enough to + * copy around. + */ + RepositoryInfo: { + /** + * Format: int32 + * @description The int Repository.Key. + */ + key: number; + /** @description The string? Repository.Name. */ + name: string; + format: components["schemas"]["RepositoryFormat"]; + kind: components["schemas"]["RepositoryKind"]; + /** @description Whether this is the string Repository.DefaultName repository. */ + isDefault?: boolean; + /** + * @description The path in front of this repository's routes, feeds and pages, without a leading slash: nothing for the + * default repository (served at `/`), else `r/{name}/`. + */ + pathPrefix?: string | null; + }; + /** + * @description How a Repository gets its content. Stored as its name. + * @enum {string} + */ + RepositoryKind: "Local" | "Remote" | "Virtual"; + /** @description The packages the user owns in one repository. */ + RepositoryPackages: { + repository: components["schemas"]["RepositoryInfo"]; + packages: components["schemas"]["OwnedPackage"][]; + }; + /** @description A repository as the administration pages list it. */ + RepositorySummary: { + /** + * Format: int32 + * @description The int Repository.Key. + */ + key: number; + /** @description The string? Repository.Name. */ + name: string; + format: components["schemas"]["RepositoryFormat"]; + kind: components["schemas"]["RepositoryKind"]; + /** @description Whether requests without credentials may read it. */ + anonymousRead: boolean; + /** + * Format: date-time + * @description When the repository was created (UTC). + */ + created: string; + /** + * Format: int32 + * @description How many package versions it holds. + */ + packageCount: number; + /** @description Whether this is the string Repository.DefaultName repository, which can be neither renamed nor deleted. */ + isDefault?: boolean; + }; + /** @description What the new-password form behind a reset link posts. */ + ResetPasswordForm: { + /** @description The account named by the link. */ + userId?: string | null; + /** @description The encoded reset token of the link. */ + code?: string | null; + /** @description The new password. Never echoed. */ + password: string | null; + /** @description The new password again. Never echoed. */ + confirmPassword: string | null; + }; + /** @description The screen behind the link of a password reset email. A request binds ResetPasswordForm, never this type. */ + ResetPasswordViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The account named by the link. */ + userId?: string | null; + /** @description The encoded reset token of the link. */ + code?: string | null; + /** @description The new password. Never echoed. */ + password: string | null; + /** @description The new password again. Never echoed. */ + confirmPassword: string | null; + }; + /** + * @description What asking one member about a package version found. + * @enum {string} + */ + ResolutionOutcome: "Stored" | "WouldFetch" | "NotFound" | "Unavailable" | "NotAsked" | "Offline"; + /** @description Where a package version would come from, member by member. */ + ResolutionPreview: { + /** @description The package id asked about (`group:artifact` for Maven). */ + packageId: string; + /** @description The version asked about, as written for the format (a NuGet or npm version in its normalized form; a Maven version as typed). */ + version: string; + /** @description The effective members in resolution order and what each found. */ + steps: components["schemas"]["ResolutionStep"][]; + answers: (null) | components["schemas"]["RepositoryInfo"]; + }; + /** @description One member's part in ResolutionPreview. */ + ResolutionStep: { + member: components["schemas"]["RepositoryInfo"]; + outcome: components["schemas"]["ResolutionOutcome"]; + }; + /** @description Placing a legal hold. */ + RetentionHoldForm: { + /** @description The repository of the hold. */ + holdRepository: string | null; + /** @description The artifact name. */ + holdName: string | null; + /** @description The version; empty for every version. */ + holdVersion: string | null; + /** @description Why (a case number, a ticket). */ + reason: string | null; + }; + /** @description Lifting a legal hold. */ + RetentionHoldRemoval: { + /** + * Format: int32 + * @description The hold's number. + */ + key: number; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description What the legal holds screen (`/admin/retention/holds`) shows. */ + RetentionHoldsViewModel: { + /** @description Only the holds of this repository (query). */ + repository?: string | null; + /** @description The repository of the new hold. */ + holdRepository?: string | null; + /** @description The artifact name of the new hold. */ + holdName?: string | null; + /** @description The version of the new hold; empty for every version. */ + holdVersion?: string | null; + /** @description Why (a case number, a ticket). */ + reason?: string | null; + /** @description The holds. */ + holds?: components["schemas"]["RetentionHoldView"][]; + /** @description The repositories a hold can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description A legal hold with its repository's name. */ + RetentionHoldView: { + /** Format: int32 */ + key: number; + /** Format: int32 */ + repositoryKey: number; + repository: string; + name: string; + version: string; + reason: string | null; + createdBy: string | null; + /** Format: date-time */ + created: string; + }; + /** @enum {string} */ + RetentionJobState: "Running" | "Succeeded" | "Failed"; + /** @description The last run of a policy since the server started (in memory). */ + RetentionJobStatus: { + /** Format: int32 */ + policyKey?: number; + dryRun?: boolean; + state?: components["schemas"]["RetentionJobState"]; + /** @description The administrator, or `scheduler`. */ + actor?: string | null; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + report?: (null) | components["schemas"]["RetentionReport"]; + /** @description Why the run failed as a whole, or null. */ + error?: string | null; + }; + /** + * @description What happened (or, in a dry run, would happen) to one selected version. + * @enum {string} + */ + RetentionOutcome: "Planned" | "Deleted" | "Held" | "Failed"; + /** + * @description A retention policy: which stored versions of one repository (or of every repository of a project) are deleted, and when. + * A version is deleted when any enabled rule selects it and no RetentionHold covers it. Not repository-scoped: + * the administrator lists policies across repositories. `RepositoryKey` and `ProjectKey` are optional Restrict foreign keys; + * deleting a repository or a project deletes its policies first. + */ + RetentionPolicy: { + /** Format: int32 */ + key?: number; + /** @description Unique, AccessNames rules. */ + name?: string | null; + /** + * Format: int32 + * @description The int Repository.Key the policy applies to, or null when it applies to a project. + */ + repositoryKey?: number | null; + /** + * Format: int32 + * @description The int Project.Key: the policy applies to every repository of the project. Exactly one of the two keys is set. + */ + projectKey?: number | null; + /** @description A disabled policy is never run by the schedule and refuses a manual run (a dry run still reports). */ + enabled?: boolean; + /** + * @description Globs (AccessPatterns, one per line) naming the artifacts the policy looks at (package ids, npm names, Maven + * `group:artifact`, image names); empty means every artifact. + */ + namePatterns?: string | null; + /** + * Format: int32 + * @description Keep this many newest versions of each artifact (by publish time); older ones are selected. Null: rule off. + */ + keepLast?: number | null; + /** + * Format: int32 + * @description Select versions published more than this many days ago. Null: rule off. + */ + olderThanDays?: number | null; + /** + * Format: int32 + * @description Select versions not downloaded for this many days (the publish time counts when never downloaded). Null: rule off. + */ + unusedDays?: number | null; + /** @description The age and count rules look at prerelease versions (NuGet pre-release, npm prerelease, Maven snapshot) only. */ + prereleaseOnly?: boolean; + /** + * Format: int64 + * @description Remote repositories only: when what the repository cached is larger than this many bytes, the least recently used versions are + * selected until it fits. Null: rule off. + */ + cacheLimitBytes?: number | null; + /** + * Format: int32 + * @description Docker only: select manifests no tag, index or referrer relationship points at that were pushed more than this many days ago. + * Null: rule off. + */ + untaggedAfterDays?: number | null; + /** @description Docker only: run the garbage collection (IOciGarbageCollector) after the rules, to free the blobs. */ + collectGarbage?: boolean; + /** + * Format: int32 + * @description Run every this many hours (a real run, by the background worker). Null: only when an administrator starts it. + */ + scheduleHours?: number | null; + /** + * Format: date-time + * @description When the schedule was set or the policy enabled; the first scheduled run is due this long after it. + */ + scheduleStart?: string | null; + /** + * Format: date-time + * @description When the last real run started (the schedule counts from the later of this and DateTime? RetentionPolicy.ScheduleStart). + */ + lastRun?: string | null; + /** @description One line about the last real run. */ + lastResult?: string | null; + /** Format: date-time */ + created?: string; + /** + * Format: date-time + * @description Since when the unused rule has been watching the policy's scope (set when the rule is enabled or changed, or the repository, + * project or name patterns change; null on rows that predate it, which fall back to DateTime RetentionPolicy.Created). A version never + * downloaded counts as unused from the later of its publication and this time: downloads are recorded only while watched. + */ + unusedSince?: string | null; + /** Format: date-time */ + modified?: string; + }; + /** @description Creating or saving a retention policy, or any write of it that asks the password. */ + RetentionPolicyBody: { + form: (null) | components["schemas"]["RetentionPolicyForm"]; + /** @description The administrator's password. */ + password: string | null; + }; + /** + * @description What the policy form posts (`Form.*`): the rules of a RetentionPolicy in the units a person types + * (the cache limit in MiB). RetentionPolicyInput RetentionPolicyForm.ToInput(int key) turns it into the administration's input. + */ + RetentionPolicyForm: { + name?: string | null; + /** @description `repository` or `project`. */ + scopeKind?: string | null; + /** @description The repository or project name. */ + scopeName?: string | null; + enabled?: boolean; + namePatterns?: string | null; + /** Format: int32 */ + keepLast?: number | null; + /** Format: int32 */ + olderThanDays?: number | null; + /** Format: int32 */ + unusedDays?: number | null; + prereleaseOnly?: boolean; + /** + * Format: int64 + * @description The remote cache limit in MiB. + */ + cacheLimitMb?: number | null; + /** Format: int32 */ + untaggedAfterDays?: number | null; + collectGarbage?: boolean; + /** Format: int32 */ + scheduleHours?: number | null; + }; + /** @description A policy with the name of what it applies to. */ + RetentionPolicyView: { + policy: components["schemas"]["RetentionPolicy"]; + /** @description The repository name, when it applies to one. */ + repository: string | null; + /** @description The project name, when it applies to a project. */ + project: string | null; + /** + * Format: int32 + * @description How many repositories it currently applies to. + */ + targets: number; + }; + /** @description What one retention policy's screen (`/admin/retention/{key}`) shows. */ + RetentionPolicyViewModel: { + /** + * Format: int32 + * @description The policy's key (route). + */ + key?: number; + form?: components["schemas"]["RetentionPolicyForm"]; + view?: (null) | components["schemas"]["RetentionPolicyView"]; + status?: (null) | components["schemas"]["RetentionJobStatus"]; + /** @description Whether a run is in progress (the page refreshes itself). */ + running?: boolean; + /** @description The repositories a policy can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + /** @description The names of the projects a policy can name. */ + projectNames?: string[]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The result of running (or dry-running) a policy over its repositories. */ + RetentionReport: { + /** Format: int32 */ + policyKey?: number; + policyName?: string; + /** @description Whether nothing was changed. */ + dryRun?: boolean; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + repositories?: components["schemas"]["RetentionRepositoryReport"][] | null; + /** Format: int32 */ + selected?: number; + /** Format: int32 */ + deleted?: number; + /** Format: int32 */ + held?: number; + /** Format: int32 */ + failed?: number; + /** Format: int64 */ + bytes?: number; + /** @description One line for the policy page, the job status and the audit log. */ + summary?: string | null; + }; + /** @description One version in a report. */ + RetentionReportItem: { + repository: string; + name: string; + version: string; + /** Format: date-time */ + published: string; + /** Format: date-time */ + lastDownloaded: string | null; + /** Format: int64 */ + size: number | null; + rules: string; + outcome: components["schemas"]["RetentionOutcome"]; + error: string | null; + }; + /** @description The part of a RetentionReport that concerns one repository. */ + RetentionRepositoryReport: { + repository?: string; + format?: components["schemas"]["RepositoryFormat"]; + /** + * Format: int32 + * @description Versions looked at (matching the policy's name patterns). + */ + examined?: number; + /** + * Format: int32 + * @description Versions selected by a rule and not held (dry run: to be deleted). + */ + selected?: number; + /** + * Format: int32 + * @description Versions deleted (always 0 in a dry run). + */ + deleted?: number; + /** + * Format: int32 + * @description Versions a rule selected that a legal hold kept. + */ + held?: number; + /** + * Format: int32 + * @description Versions whose deletion failed. + */ + failed?: number; + /** + * Format: int64 + * @description Bytes of the deleted versions (dry run: of the selected ones), as far as known. + */ + bytes?: number; + items?: components["schemas"]["RetentionReportItem"][] | null; + itemsTruncated?: boolean; + /** @description Rules that did not apply, and similar remarks. */ + notes?: string[] | null; + garbageCollection?: (null) | components["schemas"]["OciGcReport"]; + /** @description Why the repository could not be processed, or null. */ + error?: string | null; + }; + /** @description What the retention policies screen (`/admin/retention`) shows: every policy and the form that creates one. */ + RetentionViewModel: { + form?: components["schemas"]["RetentionPolicyForm"]; + /** @description Every policy. */ + policies?: components["schemas"]["RetentionPolicyView"][]; + /** @description The repositories a policy can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + /** @description The names of the projects a policy can name. */ + projectNames?: string[]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The body of the scan twin's POST: the artifact and version to scan, and where the link back goes. */ + ScanArtifactForm: { + /** @description The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image). */ + name?: string | null; + /** @description The version (Docker: the manifest digest). */ + version?: string | null; + /** @description Where the link back goes (a local address only). */ + returnUrl?: string | null; + }; + /** @description Whether the repository of the request can be scanned now, and by what. */ + ScanEngineStatus: { + /** @description Whether a scan can run. */ + available: boolean; + /** @description What scans the repository's artifacts (`OSV.dev`, `OSV offline copy`, `Trivy`), or null. */ + engine: string | null; + /** @description Why it cannot, or null. Safe to show. */ + reason: string | null; + }; + /** @description One vulnerability a scan found in an artifact or one of its components. */ + ScanFinding: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The int ScanResult.Key. Required; deleting the result deletes its findings. + */ + resultKey?: number; + /** @description The advisory id (`GHSA-…`, `CVE-…`), as the source names it. */ + vulnerabilityId?: string | null; + /** @description The component that is vulnerable: the artifact itself or one of its dependencies (package, OS package…). */ + component?: string | null; + /** @description The version of string? ScanFinding.Component. */ + componentVersion?: string | null; + /** + * Format: int32 + * @description 0 low, 1 moderate, 2 high, 3 critical (the numbering of NuGet's vulnerability resource). + */ + severity?: number; + /** @description A one-line description from the source, or null. */ + summary?: string | null; + /** @description Where the advisory is described (an absolute http(s) URL). */ + advisoryUrl?: string | null; + /** @description The first version that fixes it, when the source says. */ + fixedVersion?: string | null; + }; + /** @description One project of the scanning overview. */ + ScanningProjectRow: { + project: components["schemas"]["ProjectSummary"]; + /** @description Whether it has a scanning policy of its own. */ + hasPolicy: boolean; + }; + /** @description One repository of the scanning overview. */ + ScanningRepositoryRow: { + repository: components["schemas"]["RepositoryInfo"]; + summary: components["schemas"]["ScanSummary"]; + policy: components["schemas"]["EffectiveScanPolicy"]; + }; + /** @description The scanning options the overview shows. */ + ScanningSettingsView: { + /** @description Whether artifacts are scanned. */ + enabled: boolean; + /** @description Whether a stored version is queued for a scan at once. */ + scanOnDeploy: boolean; + /** @description The OSV API root. */ + osvUrl: string; + /** @description The offline copy of the OSV data, or null. */ + osvOfflinePath: string | null; + /** @description The age after which an artifact is scanned again (zero or negative: never). */ + rescanInterval: string; + }; + /** @description What the vulnerability scanning overview (`/admin/scanning`) shows. */ + ScanningViewModel: { + settings?: components["schemas"]["ScanningSettingsView"]; + /** @description Whether Trivy is configured (container images are scanned). */ + trivyConfigured?: boolean; + /** @description The repositories that can hold artifacts (virtual ones hold none). */ + repositories?: components["schemas"]["ScanningRepositoryRow"][]; + /** @description The projects. */ + projects?: components["schemas"]["ScanningProjectRow"][]; + }; + /** + * @description What a repository (or a project's repositories) does about findings: a threshold severity per action, or none (null) for + * the action. A repository's own policy wins over its project's. Exactly one of int? ScanPolicy.RepositoryKey and + * int? ScanPolicy.ProjectKey is set. + */ + ScanPolicy: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The repository this policy is for, or null for a project policy. + */ + repositoryKey?: number | null; + /** + * Format: int32 + * @description The project this policy is for, or null for a repository policy. + */ + projectKey?: number | null; + /** + * Format: int32 + * @description Findings at or above this severity (0..3) are shown as a warning. Null: no warning. + */ + warnSeverity?: number | null; + /** + * Format: int32 + * @description A version with a finding at or above this severity cannot be downloaded (403 with the reason). Null: never. + */ + blockDownloadSeverity?: number | null; + /** + * Format: int32 + * @description A deploy whose artifact or declared dependencies have a finding at or above this severity is refused (403). Null: never. + */ + blockDeploySeverity?: number | null; + /** @description Whether a version that has not been scanned (yet, or at all) cannot be downloaded. */ + blockUnscanned?: boolean; + /** + * Format: date-time + * @description When the policy was last saved (UTC). + */ + modified?: string; + /** @description The administrator who saved it, or null. */ + modifiedBy?: string | null; + }; + /** @description Saving the scanning policy of a repository or project (empty values remove it). */ + ScanPolicyBody: { + /** @description Warn from this severity (0 to 3, or empty). */ + warn: string | null; + /** @description Refuse downloads from this severity. */ + blockDownload: string | null; + /** @description Refuse deploys from this severity. */ + blockDeploy: string | null; + /** @description Refuse downloads of versions that were not scanned. */ + blockUnscanned: boolean; + /** @description The administrator's password. */ + password: string | null; + }; + /** @enum {string} */ + ScanPolicyScope: "Repository" | "Project"; + /** @description The thresholds of a policy; null disables the action. */ + ScanPolicyValues: { + /** + * Format: int32 + * @description Show a warning from this severity (0 low … 3 critical). + */ + warnSeverity: number | null; + /** + * Format: int32 + * @description Refuse downloads from this severity. + */ + blockDownloadSeverity: number | null; + /** + * Format: int32 + * @description Refuse deploys from this severity. + */ + blockDeploySeverity: number | null; + /** @description Refuse downloads of versions that were not scanned. */ + blockUnscanned: boolean; + /** @description Whether nothing is enabled. */ + isEmpty?: boolean; + }; + /** @description What the scanning policy of a project (`/admin/scanning/projects/{name}`) shows. */ + ScanProjectViewModel: { + /** @description The project's name (route). */ + name?: string | null; + project?: (null) | components["schemas"]["ProjectDetails"]; + own?: (null) | components["schemas"]["ScanPolicy"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the scanning dashboard of one repository (`/admin/scanning/{name}`) shows. */ + ScanRepositoryViewModel: { + /** @description The repository's name (route). */ + name?: string | null; + /** + * Format: int32 + * @description The lowest severity listed (0 low ... 3 critical). + */ + minSeverity?: number; + /** + * Format: int32 + * @description The page of the list, from 1. + */ + pageNumber?: number; + repository?: (null) | components["schemas"]["RepositoryInfo"]; + summary?: (null) | components["schemas"]["ScanSummary"]; + effective?: components["schemas"]["EffectiveScanPolicy"]; + own?: (null) | components["schemas"]["ScanPolicy"]; + /** @description The versions with findings on this page. */ + findings?: components["schemas"]["ScanResult"][]; + /** @description Whether there is another page. */ + hasMore?: boolean; + job?: (null) | components["schemas"]["AdminJobStatus"]; + /** @description The package screen of each finding's version (by int ScanResult.Key), when its format has one. */ + packageLinks?: { + [key: string]: components["schemas"]["ScreenLink"]; + }; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** + * @description What the last scans of one artifact version found, in one repository (table `ScanResults`). The artifact is named the way + * its format names it: NuGet package id (as stored), npm package name, Maven `group:artifact`, Docker image name; the + * version is the package version, npm version, Maven version or the Docker manifest digest. A row exists once a scan was + * attempted; there is no foreign key to the artifact (it may be deleted, and each format keeps its own tables), so stale rows are + * dropped by the next sweep. + */ + ScanResult: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + /** @description The artifact name (see the class remarks). At most `ScanLimits.NameLength` characters. */ + name?: string | null; + /** @description The artifact version. At most `ScanLimits.VersionLength` characters. */ + version?: string | null; + /** @description The scanner that produced the findings: `osv` or `trivy`. */ + scanner?: string | null; + /** + * Format: date-time + * @description When the last scan succeeded (UTC); null when none ever did (the artifact counts as unscanned). + */ + scannedAt?: string | null; + /** + * Format: date-time + * @description When a scan was last attempted (UTC). + */ + attempted?: string; + /** @description The scrubbed reason the last attempt failed, or null. The findings of the last success stay while this is set. */ + error?: string | null; + /** + * Format: int32 + * @description The highest severity among List<ScanFinding>? ScanResult.Findings (0 low … 3 critical), or -1 when there are none. + */ + highest?: number; + /** + * Format: int32 + * @description How many findings the last success recorded. + */ + findingCount?: number; + findings?: components["schemas"]["ScanFinding"][] | null; + }; + /** @description The repository dashboard numbers. */ + ScanSummary: { + engine: components["schemas"]["ScanEngineStatus"]; + /** + * Format: int32 + * @description Artifacts stored in the repository. + */ + artifacts: number; + /** + * Format: int32 + * @description Artifacts with no successful scan. + */ + unscanned: number; + /** + * Format: int32 + * @description Of those, the ones whose last attempt failed. + */ + failed: number; + /** + * Format: int32 + * @description Artifacts scanned without findings. + */ + clean: number; + /** @description Artifacts by their highest finding: index 0 low … 3 critical. */ + bySeverity: number[]; + }; + /** @description What the Scan now screen (`/scan-artifact`) shows; filled by the screen's workflow. */ + ScanViewModel: { + /** @description The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image). */ + name?: string | null; + /** @description The version (Docker: the manifest digest). */ + version?: string | null; + /** @description Where the link back goes: the package page the user came from (a local address only). */ + returnUrl?: string | null; + /** @description What happened, for the screen to show. */ + message?: string | null; + /** @description Whether string? ScanViewModel.Message reports a refusal. */ + failed?: boolean; + result?: (null) | components["schemas"]["ScanResult"]; + engine?: (null) | components["schemas"]["ScanEngineStatus"]; + /** @description The address the link back leads to (the return address when it is local, else the home page). */ + backUrl?: string; + }; + /** @description A screen as a client links to it: the screen (controller and action) and its route values; the view turns it into an address. */ + ScreenLink: { + screen: components["schemas"]["ScreenRef"]; + /** @description Route values; a null value (`repo` of the default repository) is kept. */ + routeValues: Record; + }; + /** @description Where a finished action leads: the screen (controller and action, see ScreenCatalog), its route values and the message to show there. */ + ScreenNext: { + screen: (null) | components["schemas"]["ScreenRef"]; + /** @description Route and query values of the next screen (`repo`, `name`, `handler`). */ + routeValues?: Record | null; + /** @description The outcome to show on the next screen (a flash message). */ + message?: string | null; + /** @description The refusal to show on the next screen (a flash error). */ + error?: string | null; + /** + * @description Instead of a screen: a local address to continue at (`/packages`, or `~/` for the site root, which the view prefixes with the path + * base). Always safe to follow: a use case only puts a validated local address here (LocalUrls). + */ + localUrl?: string | null; + /** @description The URL fragment (`#id`) to leave the next screen at, or null. */ + fragment?: string | null; + }; + /** + * @description A screen of the web UI: the MVC controller (without the `Controller` suffix, as `asp-controller` writes it) and the action that + * answers a plain `GET` for it (`AdminUsers` / `Index`). The Application projects have no MVC reference, so the UI project + * turns it into a link. ScreenCatalog lists every screen. + */ + ScreenRef: { + /** @description The controller name without the `Controller` suffix (`AdminUsers`). */ + controller: string; + /** @description The action that shows the screen (`Index`). */ + action: string; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAbuseViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AbuseViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAccessUnavailableViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AccessUnavailableViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAccountAccessViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AccountAccessViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAccountPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AccountPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAdminOrganizationsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AdminOrganizationsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAdminPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AdminPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAdminSettingsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AdminSettingsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAntiforgeryTokenModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AntiforgeryTokenModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfApiCatalogViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ApiCatalogViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfApiKeysViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ApiKeysViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAuditViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AuditViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfClusterViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ClusterViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfConfirmEmailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ConfirmEmailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfContactOwnersViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ContactOwnersViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDatabaseCopyStatusView: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DatabaseCopyStatusView"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDeleteUserViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DeleteUserViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDockerImagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DockerImagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDockerImageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DockerImageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDockerManageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DockerManageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfEmptyScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["EmptyScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfForgotPasswordViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ForgotPasswordViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfFormatsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["FormatsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfGroupDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["GroupDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfGroupsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["GroupsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfIndexScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["IndexScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfLegalScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["LegalScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfLoginViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["LoginViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenArtifactsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenArtifactsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenArtifactViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenArtifactViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenManageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenManageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenUploadViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenUploadViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmManageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmManageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmPackageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmPackageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmUploadViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmUploadViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfOperationsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["OperationsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfOrganizationDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["OrganizationDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfOrganizationsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["OrganizationsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPackageManageScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PackageManageScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPackageScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PackageScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPermissionDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PermissionDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPermissionsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PermissionsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfProfileViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ProfileViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfProjectDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ProjectDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfProjectsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ProjectsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReauthenticateViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReauthenticateViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRecoveryCodeLoginViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RecoveryCodeLoginViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRegisterViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RegisterViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReplicationConfigViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReplicationConfigViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReplicationViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReplicationViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReportAbuseScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReportAbuseScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRepositoriesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RepositoriesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRepositoryDeleteViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RepositoryDeleteViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRepositoryEditViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RepositoryEditViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfResetPasswordViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ResetPasswordViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRetentionHoldsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RetentionHoldsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRetentionPolicyViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RetentionPolicyViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRetentionViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RetentionViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanningViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanningViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanProjectViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanProjectViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanRepositoryViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanRepositoryViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfSessionModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["SessionModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfSessionProvidersModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["SessionProvidersModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfSettingsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["SettingsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfStatisticsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["StatisticsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfTwoFactorLoginViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["TwoFactorLoginViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfTwoFactorViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["TwoFactorViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUploadViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UploadViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUserDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UserDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUserPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UserPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUsersViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UsersViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfValidationStatusViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ValidationStatusViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfValidationViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ValidationViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case decided about a screen. + * @enum {string} + */ + ScreenStatus: "Ok" | "Invalid" | "NotFound" | "Forbidden" | "SignIn" | "Next"; + /** + * @description A package that matched a search query. + * + * See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + */ + SearchResult: { + /** @description The ID of the matched package. */ + id?: string | null; + /** + * @description The latest version of the matched pacakge. This is the full NuGet version after normalization, + * including any SemVer 2.0.0 build metadata. + */ + version?: string | null; + /** @description The description of the matched package. */ + description?: string | null; + /** @description The authors of the matched package. */ + authors?: string[] | null; + /** @description The URL of the matched package's icon. */ + iconUrl?: string | null; + /** @description The URL of the matched package's license. */ + licenseUrl?: string | null; + /** @description The package types defined by the package author. */ + packageTypes?: components["schemas"]["SearchResultPackageType"][] | null; + /** @description The URL of the matched package's homepage. */ + projectUrl?: string | null; + /** @description The URL for the matched package's registration index. */ + registration?: string | null; + /** @description The summary of the matched package. */ + summary?: string | null; + /** @description The tags of the matched package. */ + tags?: string[] | null; + /** @description The title of the matched package. */ + title?: string | null; + /** + * Format: int64 + * @description The total downloads for all versions of the matched package. + */ + totalDownloads?: number; + /** @description The versions of the matched package. */ + versions?: components["schemas"]["SearchResultVersion"][] | null; + deprecation?: (null) | components["schemas"]["PackageDeprecation"]; + /** @description The latest version's known vulnerabilities, or null if it has none. */ + vulnerabilities?: components["schemas"]["PackageVulnerabilityMetadata"][] | null; + /** @description The package's owners, or null if it has none. */ + owners?: string[] | null; + /** @description Whether the package ID is reserved for its owners. Null if it has no owners. */ + verified?: boolean | null; + }; + /** + * @description A single package type from a SearchResult. + * + * See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + */ + SearchResultPackageType: { + /** @description The name of the package type. */ + name?: string | null; + }; + /** + * @description A single version from a SearchResult. + * + * See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + */ + SearchResultVersion: { + /** @description The registration leaf URL for this single version of the matched package. */ + "@id"?: string | null; + /** @description The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata. */ + version?: string | null; + /** + * Format: int64 + * @description The downloads for this single version of the matched package. + */ + downloads?: number; + }; + /** + * @description How the web UI orders search results. The V3 search API has no sort parameter, so + * it always uses SearchSort.Relevance. + * @enum {string} + */ + SearchSort: "Relevance" | "TotalDownloads" | "LastUpdated"; + /** @enum {string} */ + SemVerLevel: "Unknown" | "SemVer2"; + /** + * @description The body of `POST /api/ui/session/cookie` (a same-origin client that signs in with the cookie): the password step (string? SessionCookieForm.UserName, + * string? SessionCookieForm.Password), or, when the account has two-factor, the second step (string? SessionCookieForm.Ticket with string? SessionCookieForm.Code or string? SessionCookieForm.RecoveryCode). + */ + SessionCookieForm: { + /** @description The username (password step). */ + userName?: string | null; + /** @description The password (password step). */ + password?: string | null; + /** @description The `twoFactorTicket` of the password step (second step). */ + ticket?: string | null; + /** @description A code of the authenticator app (second step). */ + code?: string | null; + /** @description A recovery code (second step). */ + recoveryCode?: string | null; + }; + /** @description The body of `POST /api/ui/session/exchange`. */ + SessionExchangeForm: { + /** @description The `exchange_token` of the external sign-in's redirect. */ + exchangeToken: string | null; + }; + /** @description What `/api/ui/session` answers: a pair of tokens, or the ticket for the second factor of a sign-in. */ + SessionModel: { + /** @description Authenticates requests to `/api/ui` (`Authorization: Bearer`); null while bool SessionModel.TwoFactorRequired. */ + accessToken?: string | null; + /** + * Format: date-time + * @description When the access token stops being accepted (UTC). + */ + expiresAt?: string | null; + /** @description Exchanged for a new pair at `/api/ui/session/refresh`; each refresh returns a new one and the old one stays valid until it expires. */ + refreshToken?: string | null; + /** + * Format: date-time + * @description When the refresh token stops being accepted (UTC). + */ + refreshExpiresAt?: string | null; + /** @description The signed-in user's name. */ + userName?: string | null; + /** @description The password was right but the account asks for a second factor: post the string? SessionModel.TwoFactorTicket and a code to `/api/ui/session/two-factor` or `/recovery-code`. */ + twoFactorRequired?: boolean; + /** @description Proves the password step; valid for five minutes, and useless without a code. */ + twoFactorTicket?: string | null; + /** + * Format: date-time + * @description When the ticket stops being accepted (UTC). + */ + twoFactorTicketExpiresAt?: string | null; + /** @description External sign-in only: a single-use-in-practice token (60 seconds) to exchange for the real ones at `POST /api/ui/session/exchange`. */ + exchangeToken?: string | null; + /** + * Format: date-time + * @description When the exchange token stops being accepted (UTC). + */ + exchangeExpiresAt?: string | null; + /** @description Something to tell the user when there are no tokens yet (external sign-in: the account was created and awaits approval or a confirmed email address). */ + notice?: string | null; + }; + /** @description The external sign-in providers a client can offer (`GET /api/ui/session/providers`): one button each, started at `/api/ui/session/external/{id}`. */ + SessionProvidersModel: { + /** @description The configured providers, empty when there is none. */ + providers?: components["schemas"]["ExternalProviderInfo"][]; + }; + /** @description The body of `POST /api/ui/session/recovery-code`: the ticket of the password step and one of the account's recovery codes (each works once). */ + SessionRecoveryCodeForm: { + /** @description The `twoFactorTicket` the password step answered. */ + ticket: string | null; + /** @description A recovery code. */ + recoveryCode: string | null; + }; + /** @description The body of `POST /api/ui/session/refresh`. */ + SessionRefreshForm: { + /** @description The `refreshToken` of the last answer. */ + refreshToken: string | null; + }; + /** @description The body of `POST /api/ui/session`: the same credentials as the sign-in page. */ + SessionSignInForm: { + /** @description The user name. */ + userName: string | null; + /** @description The password. */ + password: string | null; + }; + /** @description The body of `POST /api/ui/session/sign-out`. */ + SessionSignOutForm: { + /** @description The refresh token to end the session with when the request carries no access token. */ + refreshToken?: string | null; + /** + * @description Also ends every other session of the account (cookie sessions and tokens) by changing its security stamp. Without it nothing is + * revoked: the tokens are stateless, so the client simply forgets them, and they expire. + */ + everywhere?: boolean; + }; + /** @description The body of `POST /api/ui/session/two-factor`: the ticket of the password step and a code of the authenticator app. */ + SessionTwoFactorForm: { + /** @description The `twoFactorTicket` the password step answered. */ + ticket: string | null; + /** @description The code from the authenticator app. */ + code: string | null; + }; + /** @description One configuration key the Settings page can show. */ + SettingDescriptor: { + /** @description The full key, such as "Email:Smtp:Host". */ + key: string; + /** @description The first segment of the key, or an empty string for a top-level key. */ + section: string; + /** @description The options type's name without "Options", such as "AzureBlobStorage". */ + group: string; + kind: components["schemas"]["SettingKind"]; + /** @description The allowed names of an SettingKind.Enum, otherwise empty. */ + enumValues: string[]; + /** @description The value is a credential: masked and write-only. */ + isSensitive: boolean; + /** @description A change applies after a restart. */ + requiresRestart: boolean; + /** @description The property's XML documentation summary, or an empty string. */ + description: string; + /** + * @description The full key of the setting that selects Examples (see + * SettingExampleAttribute), or null. + */ + exampleDependsOnKey?: string | null; + /** @description Example values by the value of ExampleDependsOnKey (case-insensitive), or null. */ + examples?: { + [key: string]: string; + } | null; + }; + /** + * @description The editable type of a setting. + * @enum {string} + */ + SettingKind: "Boolean" | "Integer" | "Number" | "String" | "Enum" | "TimeSpan" | "StringList" | "ReadOnly"; + /** @description One section of the settings screen: its key (empty for the top-level keys), its DOM id and its settings. */ + SettingsSection: { + /** @description The section's key; empty for the settings that sit at the top level. */ + key: string; + /** @description The stable DOM id (string AdminSettingsViewModel.SectionId(string key)). */ + id: string; + /** @description The settings of the section; a sensitive one never carries its value. */ + settings: components["schemas"]["SettingState"][]; + }; + /** + * @description The fields of a submitted Settings form, per setting key (`v:<key>` the value, `reset:<key>`, `clear:<key>`; a checkbox posts + * `true` next to a hidden `false`, a list is one entry per line) and the section they belong to. The same shape whether it comes from the + * page's form or from a JSON body. + */ + SettingsSubmission: { + /** @description The section being saved (the empty section holds the top-level keys). */ + section: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + /** @description The posted fields; a field may repeat. */ + fields: { + [key: string]: string[]; + }; + }; + /** @description A setting as the Settings page shows it. */ + SettingState: { + descriptor: components["schemas"]["SettingDescriptor"]; + /** + * @description The value in effect, as text (a list one entry per line). Always null for a sensitive + * setting: only HasValue says whether one is set. + */ + effectiveValue: string | null; + /** @description The setting has a non-empty value. */ + hasValue: boolean; + /** @description The setting is saved in the overrides file. */ + isOverridden: boolean; + /** + * @description What overrides the saved value ("environment variable", "command line", ...), or null. + * While set, a saved value has no effect. + */ + shadowedBy: string | null; + /** @description A restart-only setting whose value changed since startup. */ + pendingRestart: boolean; + }; + /** @description What the account settings screen shows (change email, change password, delete the account). */ + SettingsViewModel: { + /** @description The account's email address. */ + email?: string | null; + /** @description Whether the address is confirmed. */ + emailConfirmed?: boolean; + /** @description Whether the account has a password (else it signs in through a provider). */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is configured to sign in again with. */ + canReauthenticate?: boolean; + /** @description Whether mail is configured. */ + canSendEmail?: boolean; + /** @description Every configured external provider with whether this account has linked a login at it (empty when there is none). */ + externalLogins?: components["schemas"]["ExternalLoginStatus"][]; + /** @description The success message to show. */ + message?: string | null; + /** @description The refusal to show. */ + error?: string | null; + blockers?: (null) | components["schemas"]["DeletionBlockers"]; + }; + /** + * @description What the "Sign-in providers" panel of the Settings screen posts to add or edit a named OpenID Connect provider (the body of + * `POST /api/ui/admin/settings/save-provider`). The id is the key and cannot change once created; a blank secret keeps the saved one. + * string? SignInProviderForm.Parameters and string? SignInProviderForm.GroupMappings are one `name=value` per line. + */ + SignInProviderForm: { + /** @description The provider id (lower-case letters, digits and `-`, 1 to 32). */ + id?: string | null; + /** @description The name on the sign-in button. */ + displayName?: string | null; + /** @description The issuer address. */ + authority?: string | null; + /** @description The client id. */ + clientId?: string | null; + /** @description The client secret; blank keeps the saved one. Never sent back. */ + clientSecret?: string | null; + /** @description Extra scopes, separated by spaces or semicolons. */ + scopes?: string | null; + /** @description Extra authorization request parameters, one `name=value` per line. */ + parameters?: string | null; + /** @description The claim holding the user name. */ + userNameClaim?: string | null; + /** @description The claim holding the email address. */ + emailClaim?: string | null; + /** @description The claim saying the address is verified. */ + emailVerifiedClaim?: string | null; + /** @description The claim that decides the administrator flag (the provider becomes authoritative for it). */ + administratorClaim?: string | null; + /** @description The value of that claim that makes a user an administrator. */ + administratorValue?: string | null; + /** @description The claim holding the user's groups. */ + groupClaim?: string | null; + /** @description Claim value to BaGet group, one `value=group` per line. */ + groupMappings?: string | null; + /** @description The administrator's password, asked again. */ + password?: string | null; + }; + /** @description A named OpenID Connect provider as the Settings screen lists it. The client secret is never carried, only whether one is set. */ + SignInProviderView: { + /** @description The provider id. */ + id?: string; + /** @description The name on the sign-in button. */ + displayName?: string | null; + /** @description The issuer address. */ + authority?: string | null; + /** @description The client id. */ + clientId?: string | null; + /** @description Whether a client secret is set. */ + hasSecret?: boolean; + /** @description Extra scopes. */ + scopes?: string | null; + /** @description Extra request parameters, one `name=value` per line. */ + parameters?: string | null; + /** @description The claim holding the user name. */ + userNameClaim?: string | null; + /** @description The claim holding the email address. */ + emailClaim?: string | null; + /** @description The claim saying the address is verified. */ + emailVerifiedClaim?: string | null; + /** @description The claim that decides the administrator flag. */ + administratorClaim?: string | null; + /** @description The value of that claim that makes a user an administrator. */ + administratorValue?: string | null; + /** @description The claim holding the user's groups. */ + groupClaim?: string | null; + /** @description Claim value to BaGet group, one `value=group` per line. */ + groupMappings?: string | null; + /** @description Whether the overrides file holds it, so this screen can edit or remove it; false when a configuration file or the environment sets it. */ + editable?: boolean; + /** @description Whether the running server has a handler for it (false: saved or removed since startup). */ + active?: boolean; + /** @description Whether what is saved differs from what the running server uses, so a restart is needed. */ + pendingRestart?: boolean; + }; + /** @description A package ID in one repository that only one user owns. */ + SoleOwnedPackage: { + /** + * Format: int32 + * @description The repository's key. + */ + repositoryKey: number; + /** @description The repository's name (string Repository.DefaultName for the default). */ + repositoryName: string; + /** @description The package ID. */ + packageId: string | null; + format?: components["schemas"]["RepositoryFormat"]; + /** @description The ID for the default repository, `ID (name)` for any other, for messages that mix repositories. */ + label?: string | null; + }; + /** @description What the statistics page shows. */ + StatisticsViewModel: { + statistics: (null) | components["schemas"]["FeedStatistics"]; + }; + /** Format: binary */ + Stream: string | null; + /** @description A decision on a stuck submission of the validation queue. */ + SubmissionForm: { + /** @description The submission. */ + submissionId: string | null; + /** @description The administrator's password (asked to release or reject). */ + password: string | null; + }; + /** @description A permission target with its grants. */ + TargetDetails: { + target: components["schemas"]["TargetSummary"]; + grants: components["schemas"]["GrantInfo"][]; + }; + TargetFramework: { + /** Format: int32 */ + key?: number; + moniker?: string | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** @description A permission target as the admin pages list it. */ + TargetSummary: { + /** Format: int32 */ + key: number; + name: string; + repositoryPatterns: string[]; + includePatterns: string[]; + excludePatterns: string[]; + /** Format: int32 */ + projectKey: number | null; + projectName: string | null; + isBuiltIn: boolean; + /** Format: int32 */ + grantCount: number; + }; + /** @description One signal's state. string? TelemetrySignalReport.LastError is already scrubbed (no headers, credentials or URL paths). */ + TelemetrySignalReport: { + signal: string; + state: components["schemas"]["TelemetrySignalState"]; + /** Format: date-time */ + lastSuccess: string | null; + /** Format: date-time */ + failingSince: string | null; + lastError: string | null; + /** Format: int64 */ + dropped: number; + }; + /** + * @description What one telemetry signal is doing, as the Settings page shows it. + * @enum {string} + */ + TelemetrySignalState: "Off" | "NotConfigured" | "Waiting" | "Ok" | "Failing"; + /** @description The outcome of a connection test; string TelemetryTestOutcome.Message and string? TelemetryTestOutcome.Target are scrubbed. */ + TelemetryTestOutcome: { + /** @description The collector accepted a test span. */ + ok: boolean; + /** @description What happened. */ + message: string; + /** @description The endpoint that was tested, cut to scheme, host and port. */ + target: string | null; + }; + /** @description What the "turn two-factor authentication on" form posts. */ + TwoFactorCodeForm: { + /** @description The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it. */ + password?: string | null; + /** @description The code from the authenticator app. */ + code?: string | null; + }; + /** @description What the authenticator-code form posts. */ + TwoFactorLoginForm: { + /** @description The code from the authenticator app. */ + code: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description The second step of signing in: an authenticator code. A request binds TwoFactorLoginForm, never this type. */ + TwoFactorLoginViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The code from the authenticator app. */ + code: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description What the two-factor authentication screen shows. */ + TwoFactorViewModel: { + /** @description Whether two-factor authentication is on. */ + twoFactorEnabled?: boolean; + /** @description The key to type into an authenticator that cannot scan the QR code. */ + sharedKey?: string | null; + /** @description The QR code of the setup link, an SVG built from the user's own key. */ + qrCodeSvg?: string | null; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is configured to sign in again with. */ + canReauthenticate?: boolean; + /** + * Format: int32 + * @description How many recovery codes are unused. + */ + recoveryCodesLeft?: number; + /** @description Whether the account has a password (else it signs in through a provider). */ + hasPassword?: boolean; + /** @description The new recovery codes. Shown once, when two-factor authentication is turned on. */ + recoveryCodes?: string[]; + /** @description The refusal to show. */ + error?: string | null; + /** @description The success message to show. */ + message?: string | null; + }; + /** @description What unlinking an external provider posts. */ + UnlinkExternalForm: { + /** @description The id of the provider to unlink. */ + provider?: string | null; + /** @description The password, asked again. */ + password?: string | null; + }; + /** @description What a staged NuGet upload contains, as the preview of the upload page shows it (read from the archive itself). */ + UploadPreview: { + /** @description The handle of the staged file; only the user who staged it can open it. */ + token?: string | null; + /** @description Whether the file is a symbol package (`.snupkg`, by its nuspec's package type). */ + isSymbolPackage?: boolean; + /** @description The package ID, from the nuspec. */ + id?: string | null; + /** @description The normalized version, from the nuspec. */ + version?: string | null; + /** @description The description. */ + description?: string | null; + /** @description The authors. */ + authors?: string[]; + /** @description The license expression or license file the package declares, if any. */ + license?: string | null; + /** @description The license URL, if any. */ + licenseUrl?: string | null; + /** @description The dependencies by target framework. */ + dependencyGroups?: components["schemas"]["DependencyGroupModel"][]; + readme?: (null) | components["schemas"]["HtmlString"]; + /** @description The PDBs of a symbol package. */ + symbolFiles?: string[]; + /** @description Whether the version a symbol package belongs to is on this server. */ + targetPackageExists?: boolean; + /** @description What to tell about a symbol package whose package is missing. */ + targetPackageMessage?: string | null; + }; + /** + * @description What the second and third step of the NuGet upload send (publish and discard a staged upload): the handle of the staged file and, while accounts are + * off, the API key that authenticates the uploader. The key is read and never echoed in an answer. + */ + UploadTokenRequest: { + /** @description The handle of the staged upload (string? UploadPreview.Token). */ + token?: string; + /** @description The API key of the uploader while accounts are off (otherwise the signed-in session or the key of the request authenticates). */ + apiKey?: string | null; + /** @description The confirmation that the uploader may publish the package (required to publish, ignored when discarding). */ + acceptTerms?: boolean; + }; + /** @description What the NuGet upload page (`/upload`) shows: the form, the preview of a staged file, or the outcome of a step. */ + UploadViewModel: { + /** + * @description The package ID a link arrived with, as "upload a new version of this" does. A hint for the page only: the ID and version that + * are published are read from the file, never from the request. + */ + id?: string | null; + /** @description Whether accounts are on (the uploader then signs in). */ + accountsEnabled?: boolean; + /** @description Whether the server is read-only. */ + isReadOnlyMode?: boolean; + /** @description Whether the visitor is signed in. */ + signedIn?: boolean; + /** @description With accounts off there is no user to own an upload, so the pusher proves itself with an API key. */ + needsApiKey?: boolean; + /** @description Nothing on this server can tell one caller from another (accounts off and no global API key): the browser upload is closed. */ + nothingCanAuthenticate?: boolean; + /** @description What the page says in that state, so the explanation and the refusal are one sentence. */ + noApiKeyExplanation?: string | null; + /** @description Whether to render the form at all. */ + canUpload?: boolean; + staged?: (null) | components["schemas"]["UploadPreview"]; + /** @description What happened, for the page to show. */ + message?: string | null; + /** @description Whether string? UploadViewModel.Message reports a failure. */ + failed?: boolean; + published?: (null) | components["schemas"]["UploadPreview"]; + /** @description The token of a staged upload whose API key was rejected, so the key can be entered again. */ + retryToken?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with (200, or the refusal's). + */ + statusCode?: number; + }; + /** @description The account an administrator looks at, without anything that signs in as it (no password hash, security stamp or tokens). */ + UserAccountInfo: { + /** @description The user name. */ + userName: string | null; + /** @description The email address, or null. */ + email: string | null; + /** + * Format: date-time + * @description When the account was created. + */ + created: string; + /** @description Whether it is a server administrator. */ + isAdministrator: boolean; + /** @description Whether it waits for an administrator to enable it. */ + pendingApproval: boolean; + }; + /** @description A change to one account from the Users screen, with the list's filter and page to come back to. */ + UserChange: { + /** @description The account the change applies to. */ + userName: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + /** @description The list's user-name filter. */ + q?: string | null; + /** + * Format: int32 + * @description The list's page. + * @default 1 + */ + pageNumber: number; + /** @description For a password reset: the address to mail the new password to, if the administrator typed one. */ + resetEmail?: string | null; + }; + /** @description A new account from the Users screen. */ + UserCreation: { + /** @description The new account's name. */ + newUserName: string | null; + /** @description Its address, or null. */ + newEmail: string | null; + /** @description The password typed; empty means generate one (unless Invite). */ + newPassword: string | null; + /** @description Mail the user a link to choose their own password. */ + invite: boolean; + /** @description The administrator's password, asked again. */ + password: string | null; + /** @description The list's user-name filter. */ + q?: string | null; + /** + * Format: int32 + * @description The list's page. + * @default 1 + */ + pageNumber: number; + }; + /** @description Deleting an account. */ + UserDeletionForm: { + /** @description "keep" (default) or "delete": what to do with the package IDs only this user owns. */ + soleOwned: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description What the user detail screen (`/admin/users/{name}`) shows: the account, its keys, organizations and access. */ + UserDetailViewModel: { + /** @description A package ID to evaluate the effective permissions for; empty means each repository as a whole. */ + package?: string | null; + /** @description The user name (route). */ + name?: string | null; + /** @description Whether the configured database has an access model (else the access sections are hidden). */ + modelAvailable?: boolean; + /** @description The names of the groups the account belongs to (the implicit built-ins excluded). */ + groups?: string[]; + /** @description The roles the account holds in projects, directly or through a group. */ + projectRoles?: components["schemas"]["UserProjectRole"][]; + /** @description What the account may do in each NuGet repository, and why. */ + access?: components["schemas"]["RepositoryAccessRow"][]; + account?: (null) | components["schemas"]["UserAccountInfo"]; + /** @description The account's API keys; the key and its hash are never shown. */ + keys?: components["schemas"]["UserKeyRow"][]; + /** @description The organizations the account belongs to. */ + organizations?: components["schemas"]["Organization"][]; + /** + * Format: int32 + * @description How many package IDs the account owns, in every repository. + */ + ownedPackageIds?: number; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Adding an account to a group or removing it. */ + UserGroupForm: { + /** @description The group's name. */ + group: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description Revoking one of an account's API keys. */ + UserKeyForm: { + /** + * Format: int32 + * @description The key's number (int UserKeyRow.Key). + */ + key: number; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description One of an account's API keys as the administrator sees it; the key itself and its hash are never shown. */ + UserKeyRow: { + /** + * Format: int32 + * @description The key's number (what revoking names). + */ + key: number; + /** @description The description the owner gave it. */ + description: string | null; + /** @description What it may do. */ + scopes: string[]; + /** @description The package IDs it applies to. */ + packageGlobPattern: string | null; + /** + * Format: date-time + * @description When it was created. + */ + created: string; + /** + * Format: date-time + * @description When it expires, or null. + */ + expires: string | null; + /** @description Where it may be used: the repositories it is limited to, or "all repositories". */ + repositories: string; + }; + /** @description What the user packages screen (`/admin/users/{name}/packages`) shows: the package IDs one user owns. */ + UserPackagesViewModel: { + /** @description The user name, from the route. */ + name?: string | null; + /** @description The user's packages. */ + packages?: components["schemas"]["AdminPackageRow"][]; + }; + /** @description A role a user holds in a project, directly or through a group. */ + UserProjectRole: { + project: string; + role: components["schemas"]["ProjectRole"]; + via: string; + }; + /** @description A user as the Users page lists them. */ + UserRow: { + /** @description The user name. */ + userName: string | null; + /** @description The email address, if any. */ + email: string | null; + /** + * Format: date-time + * @description When the account was created. + */ + created: string; + /** @description Whether the user is an administrator. */ + isAdministrator: boolean; + /** @description The avatar's address, or null for the initial. */ + avatarUrl: string | null; + /** + * @description Whether the account waits for an administrator to enable it (`Accounts:RequireApproval`). + * @default false + */ + pendingApproval: boolean; + }; + /** @description What the Users screen (`/admin/users`) shows: the filtered, paged accounts and the state of the last action. */ + UsersViewModel: { + /** @description User-name filter (contains). */ + q?: string | null; + /** + * Format: int32 + * @description One-based page number (the `p` query value; not "page", which Razor Pages reserved for the page path). + */ + pageNumber?: number; + /** @description The users on this page. */ + users?: components["schemas"]["UserRow"][]; + /** + * Format: int32 + * @description How many accounts, in all pages, wait for approval. + */ + pendingCount?: number; + /** + * Format: int32 + * @description The number of pages for the current filter. + */ + pageCount?: number; + /** @description The signed in administrator's user name; their own row has no actions. */ + currentUserName?: string | null; + /** @description Whether a reset link can be mailed: SMTP is configured. */ + canEmailResetLink?: boolean; + /** @description Whether an invitation (a reset link mailed to the new user) can be offered: SMTP is configured. */ + canInvite?: boolean; + /** @description The password just generated. Only ever rendered by the response to the reset itself, never kept in TempData or a cookie. */ + generatedPassword?: string | null; + /** @description The user string? UsersViewModel.GeneratedPassword belongs to. */ + generatedFor?: string | null; + /** @description Whether string? UsersViewModel.GeneratedPassword is a new account's first password rather than a reset. */ + generatedForNewUser?: boolean; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the validation status screen (`/packages/{id}/validation`) shows; filled by the screen's workflow. */ + ValidationStatusViewModel: { + /** @description The package ID from the address. */ + id?: string | null; + /** @description The newest submission of each version, newest version first. */ + submissions?: components["schemas"]["ValidationSubmission"][]; + }; + /** @description One version's newest validation submission and the verdict of every step. */ + ValidationSubmission: { + version: string; + submissionId: string | null; + status: string; + steps: components["schemas"]["PackageValidation"][]; + }; + /** + * @description Where a submission stands: still to run, or stopped without being indexed. + * @enum {string} + */ + ValidationSubmissionState: "Pending" | "Quarantined"; + /** @description One submission awaiting validation or quarantined. */ + ValidationSubmissionSummary: { + submissionId: string; + repository: string; + packageId: string | null; + packageVersion: string | null; + state: components["schemas"]["ValidationSubmissionState"]; + /** Format: date-time */ + created: string; + failureMessages: string[]; + }; + /** @description What the validation queue screen (`/admin/validation`) shows: pending and quarantined submissions. */ + ValidationViewModel: { + /** @description Whether validation can be administered here. */ + isSupported?: boolean; + /** @description The pending and quarantined submissions. */ + submissions?: components["schemas"]["ValidationSubmissionSummary"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description One member of a virtual repository as the administration page lists it. */ + VirtualMemberDetail: { + /** @description The member's name, as stored. */ + name: string; + repository: (null) | components["schemas"]["RepositoryInfo"]; + /** @description Whether a repository of that name exists. */ + exists?: boolean; + }; + /** @description A virtual repository as the administration pages edit it. */ + VirtualRepositoryDetail: { + repository: components["schemas"]["RepositoryInfo"]; + /** @description Its direct members in resolution order. */ + members: components["schemas"]["VirtualMemberDetail"][]; + /** @description The name of the member that receives deployments, if any. */ + deployRepository: string | null; + deployTarget: (null) | components["schemas"]["RepositoryInfo"]; + /** @description The local and remote repositories that answer, in order, nested virtual members expanded. */ + effectiveMembers: components["schemas"]["RepositoryInfo"][]; + }; + }; + responses: never; + parameters: never; + requestBodies: never; + headers: never; + pathItems: never; +} +export type $defs = Record; +export type operations = Record; diff --git a/samples/BaGet.Frontend.Angular/src/app/api/screens.ts b/samples/BaGet.Frontend.Angular/src/app/api/screens.ts new file mode 100644 index 000000000..fa8208f46 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/api/screens.ts @@ -0,0 +1,117 @@ +import { Injectable, signal } from '@angular/core'; +import { AbstractControl, FormGroup } from '@angular/forms'; +import { Router, UrlTree } from '@angular/router'; +import type { ScreenNext, ScreenResult } from './api-types'; + +type RouteValues = Record; + +/** + * A screen of the web UI is `controller/action` (`AdminUsers/Index`, `ScreenCatalog` on the server). The application maps the ones + * it has to its own routes; the rest fall back to the home page. The SPA routes of the emails (`confirm-email`, `reset-password`, + * `sign-in`) are the server's `Frontend:SpaLinks` routes. + */ +const SCREEN_ROUTES: Record unknown[]> = { + 'Home/Index': () => ['/packages'], + 'Package/Show': (v) => ['/packages', ...[v['id'], v['version']].filter((x) => x != null && x !== '')], + 'Account/Login': () => ['/sign-in'], + 'Account/Register': () => ['/register'], + 'Account/ForgotPassword': () => ['/forgot-password'], + 'Account/ResetPassword': () => ['/reset-password'], + 'Account/ConfirmEmail': () => ['/confirm-email'], + 'AdminUsers/Index': () => ['/admin/users'], +}; + +/** Route values that are part of a screen's path in the SPA; everything else of `routeValues` becomes the query string. */ +const PATH_VALUES = new Set(['id', 'version']); + +/** The router address of `ScreenResult.next`, or `null` when the application has no such screen. */ +export function nextToUrlTree(router: Router, next: ScreenNext | null | undefined): UrlTree | null { + if (!next) { + return null; + } + if (next.localUrl) { + // A local address of the server's own screens ("/packages", "~/"): only the home page makes sense here. + return router.parseUrl(next.localUrl === '~/' || next.localUrl === '/' ? '/packages' : safeLocalUrl(next.localUrl) ?? '/packages'); + } + const screen = next.screen; + const build = screen ? SCREEN_ROUTES[`${screen.controller}/${screen.action}`] : undefined; + if (!build) { + return null; + } + const values = (next.routeValues ?? {}) as RouteValues; + const queryParams: Record = {}; + for (const [key, value] of Object.entries(values)) { + if (!PATH_VALUES.has(key) && value != null && value !== '' && key !== 'handler') { + queryParams[key] = String(value); + } + } + return router.createUrlTree(build(values), { queryParams, fragment: next.fragment ?? undefined }); +} + +/** A return address is followed only when it is a path of this application ("/x", never "//host" or "https://..."). */ +export function safeLocalUrl(url: string | null | undefined): string | null { + return url && url.startsWith('/') && !url.startsWith('//') && !url.includes('\\') ? url : null; +} + +/** The flash message a finished action leaves for the next screen (`next.message` / `next.error`). */ +@Injectable({ providedIn: 'root' }) +export class Flash { + readonly message = signal(null); + readonly error = signal(null); + + show(message?: string | null, error?: string | null): void { + this.message.set(message ?? null); + this.error.set(error ?? null); + } + + clear(): void { + this.show(); + } +} + +/** Follows `next` of a result (flash included). Returns false when the application has no such screen. */ +export function follow(router: Router, flash: Flash, result: ScreenResult, fallback: unknown[] = ['/packages']): void { + flash.show(result.next?.message, result.next?.error); + const target = nextToUrlTree(router, result.next); + void router.navigateByUrl(target ?? router.createUrlTree(fallback)); +} + +/** The messages of the whole form (`errors[""]`), then of fields no control has. */ +export function formLevelErrors(result: ScreenResult, form?: FormGroup): string[] { + const errors = result.errors ?? {}; + const messages = [...(errors[''] ?? [])]; + for (const [field, list] of Object.entries(errors)) { + if (field !== '' && (!form || !findControl(form, field))) { + messages.push(...list); + } + } + return messages; +} + +/** + * Puts `ScreenResult.errors` on a reactive form: a field's messages become the `server` error of its control (matched + * case-insensitively, so `Password` and `password` both find it), and the control is touched so the message shows. Returns the + * messages that belong to no control (the whole form's `""` and unknown fields), to print above the form. + */ +export function applyServerErrors(form: FormGroup, result: ScreenResult): string[] { + for (const control of Object.values(form.controls)) { + if (control.hasError('server')) { + const { server: _server, ...rest } = control.errors ?? {}; + control.setErrors(Object.keys(rest).length ? rest : null); + } + } + for (const [field, list] of Object.entries(result.errors ?? {})) { + const control = field === '' ? null : findControl(form, field); + if (control) { + control.setErrors({ ...control.errors, server: list }); + control.markAsTouched(); + } + } + return formLevelErrors(result, form); +} + +function findControl(form: FormGroup, field: string): AbstractControl | null { + const wanted = field.toLowerCase(); + const name = Object.keys(form.controls).find((key) => key.toLowerCase() === wanted); + return name ? form.controls[name] : null; +} diff --git a/samples/BaGet.Frontend.Angular/src/app/app.config.ts b/samples/BaGet.Frontend.Angular/src/app/app.config.ts new file mode 100644 index 000000000..ab688a764 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/app.config.ts @@ -0,0 +1,17 @@ +import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { ApplicationConfig, inject, provideAppInitializer, provideBrowserGlobalErrorListeners } from '@angular/core'; +import { provideRouter, withComponentInputBinding } from '@angular/router'; +import { firstValueFrom } from 'rxjs'; +import { routes } from './app.routes'; +import { SessionService } from './session/session.service'; +import { sessionInterceptor } from './session/session.interceptor'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideBrowserGlobalErrorListeners(), + provideRouter(routes, withComponentInputBinding()), + provideHttpClient(withInterceptors([sessionInterceptor])), + // A refresh token left in sessionStorage by a reload is exchanged for an access token before the first guard runs. + provideAppInitializer(() => firstValueFrom(inject(SessionService).restore())), + ], +}; diff --git a/samples/BaGet.Frontend.Angular/src/app/app.html b/samples/BaGet.Frontend.Angular/src/app/app.html new file mode 100644 index 000000000..e0533a268 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/app.html @@ -0,0 +1,28 @@ +

+ BaGet + + + @if (session.isSignedIn()) { + {{ session.userName() ?? 'signed in' }} + + + } @else { + Sign in + Register + } +
+ +
+ @if (flash.message(); as message) { +

{{ message }}

+ } + @if (flash.error(); as error) { + + } + +
diff --git a/samples/BaGet.Frontend.Angular/src/app/app.routes.ts b/samples/BaGet.Frontend.Angular/src/app/app.routes.ts new file mode 100644 index 000000000..ac2818a0b --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/app.routes.ts @@ -0,0 +1,21 @@ +import { Routes } from '@angular/router'; +import { authGuard } from './session/auth.guard'; + +/** + * `sign-in`, `confirm-email` and `reset-password` are the routes BaGet's emails link to (`Frontend:SpaLinks`, + * `{Frontend:SpaBasePath}/confirm-email?userId=&code=[&email=]`, `.../reset-password?userId=&code=`). + */ +export const routes: Routes = [ + { path: '', pathMatch: 'full', redirectTo: 'packages' }, + { path: 'packages', loadComponent: () => import('./pages/packages').then((m) => m.Packages) }, + { path: 'packages/:id', loadComponent: () => import('./pages/package-detail').then((m) => m.PackageDetail) }, + { path: 'packages/:id/:version', loadComponent: () => import('./pages/package-detail').then((m) => m.PackageDetail) }, + { path: 'sign-in', loadComponent: () => import('./pages/sign-in').then((m) => m.SignIn) }, + { path: 'sign-in/external', loadComponent: () => import('./pages/external-sign-in').then((m) => m.ExternalSignIn) }, + { path: 'register', loadComponent: () => import('./pages/register').then((m) => m.Register) }, + { path: 'forgot-password', loadComponent: () => import('./pages/forgot-password').then((m) => m.ForgotPassword) }, + { path: 'reset-password', loadComponent: () => import('./pages/reset-password').then((m) => m.ResetPassword) }, + { path: 'confirm-email', loadComponent: () => import('./pages/confirm-email').then((m) => m.ConfirmEmail) }, + { path: 'admin/users', canActivate: [authGuard], loadComponent: () => import('./pages/admin-users').then((m) => m.AdminUsers) }, + { path: '**', redirectTo: 'packages' }, +]; diff --git a/samples/BaGet.Frontend.Angular/src/app/app.ts b/samples/BaGet.Frontend.Angular/src/app/app.ts new file mode 100644 index 000000000..dafee60c0 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/app.ts @@ -0,0 +1,19 @@ +import { Component, inject } from '@angular/core'; +import { Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'; +import { Flash } from './api/screens'; +import { SessionService } from './session/session.service'; + +@Component({ + selector: 'app-root', + imports: [RouterOutlet, RouterLink, RouterLinkActive], + templateUrl: './app.html', +}) +export class App { + protected readonly session = inject(SessionService); + protected readonly flash = inject(Flash); + private readonly router = inject(Router); + + protected signOut(everywhere: boolean): void { + this.session.signOut(everywhere).subscribe(() => void this.router.navigate(['/sign-in'])); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/admin-users.ts b/samples/BaGet.Frontend.Angular/src/app/pages/admin-users.ts new file mode 100644 index 000000000..f888055df --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/admin-users.ts @@ -0,0 +1,81 @@ +import { Component, inject } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { startWith, switchMap } from 'rxjs'; +import { ApiClient } from '../api/api-client'; + +/** + * `GET /api/ui/admin/users?q=&p=`: administrators only. The page shows what each status means: + * `SignIn` (401: no or expired session), `Forbidden` (403: signed in, but not an administrator), `Ok` (the list). + * Writes of this screen (create, approve, promote...) are separate POST twins that also ask the administrator's password. + */ +@Component({ + selector: 'app-admin-users', + imports: [FormsModule, RouterLink], + template: ` +

Users

+ @let r = result(); + @if (!r) { +

Loading...

+ } @else if (r.status === 'SignIn') { +

Your session ended. Sign in again.

+ } @else if (r.status === 'Forbidden') { +

{{ (r.errors?.[''] ?? ['Only administrators can see the users.'])[0] }}

+ } @else if (r.status !== 'Ok') { +

{{ (r.errors?.[''] ?? ['The users could not be loaded.'])[0] }}

+ } @else { + @let m = r.model!; + + + + + @if (m.pendingCount) { +

{{ m.pendingCount }} account(s) wait for approval.

+ } + + + + @for (u of m.users ?? []; track u.userName) { + + + + + + + } + +
UserEmailCreatedRole
{{ u.userName }}{{ u.email }}{{ u.created }}{{ u.isAdministrator ? 'administrator' : u.pendingApproval ? 'pending approval' : 'user' }}
+
+ + Page {{ page() }} of {{ (m.pageCount ?? 1) }} + +
+ } + `, +}) +export class AdminUsers { + private readonly api = inject(ApiClient); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + + protected q = this.route.snapshot.queryParamMap.get('q') ?? ''; + protected readonly page = () => Number(this.route.snapshot.queryParamMap.get('p') ?? 1) || 1; + + protected readonly result = toSignal( + this.route.queryParamMap.pipe( + switchMap((p) => + this.api.get('/api/ui/admin/users', { query: { q: p.get('q') ?? undefined, p: Number(p.get('p')) || undefined } }).pipe(startWith(null)), + ), + ), + { initialValue: null }, + ); + + protected search(): void { + void this.router.navigate([], { queryParams: { q: this.q || null, p: null } }); + } + + protected go(page: number): void { + void this.router.navigate([], { queryParams: { p: page > 1 ? page : null }, queryParamsHandling: 'merge' }); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/confirm-email.ts b/samples/BaGet.Frontend.Angular/src/app/pages/confirm-email.ts new file mode 100644 index 000000000..04fab566f --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/confirm-email.ts @@ -0,0 +1,46 @@ +import { Component, inject } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { startWith } from 'rxjs'; +import { ApiClient } from '../api/api-client'; + +/** + * The email link `{SpaBasePath}/confirm-email?userId=&code=[&email=]` -> `GET /api/ui/account/confirmemail` with the same values. + * A made-up link is the same harmless answer (`succeeded: false`). + */ +@Component({ + selector: 'app-confirm-email', + imports: [RouterLink], + template: ` +

Confirm your email

+ @let r = result(); + @if (!r) { +

Confirming...

+ } @else if (r.status === 'Ok' && r.model?.succeeded) { +

+ @if (r.model.emailChanged) { Your new email address is confirmed. } @else { Your email address is confirmed. } + @if (r.model.pendingApproval) { An administrator must still approve the account before you can sign in. } +

+ Sign in + } @else { +

This confirmation link is not valid (any more).

+ Request a new confirmation email + } + `, +}) +export class ConfirmEmail { + private readonly query = inject(ActivatedRoute).snapshot.queryParamMap; + + protected readonly result = toSignal( + inject(ApiClient) + .get('/api/ui/account/confirmemail', { + query: { + userId: this.query.get('userId') ?? undefined, + code: this.query.get('code') ?? undefined, + email: this.query.get('email') ?? undefined, + }, + }) + .pipe(startWith(null)), + { initialValue: null }, + ); +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/external-sign-in.ts b/samples/BaGet.Frontend.Angular/src/app/pages/external-sign-in.ts new file mode 100644 index 000000000..3bd5bd774 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/external-sign-in.ts @@ -0,0 +1,68 @@ +import { Component, inject, signal } from '@angular/core'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { Flash, safeLocalUrl } from '../api/screens'; +import { OIDC_STATE_KEY } from '../session/oidc-state'; +import { SessionService } from '../session/session.service'; + +/** + * Where the server returns after an external provider's sign-in (`returnUrl` of `GET /api/ui/session/external/{provider}`): + * `.../sign-in/external#exchange_token=...&exchange_expires_at=...&user_name=...` or `#notice=...` / `#error=...`. + * The `state` of the query must equal the one saved in `sessionStorage` before the redirect, else nothing is exchanged. The fragment + * is removed from the address bar and the history at once, then the 60-second (single-use) token is exchanged for the session + * (`POST /api/ui/session/exchange`). No session token ever travels in a URL. + */ +@Component({ + selector: 'app-external-sign-in', + imports: [RouterLink], + template: ` +

External sign-in

+ @if (message(); as text) { +

{{ text }}

+ Back to sign-in + } @else { +

Signing in...

+ } + `, +}) +export class ExternalSignIn { + private readonly session = inject(SessionService); + private readonly router = inject(Router); + private readonly route = inject(ActivatedRoute); + private readonly flash = inject(Flash); + + protected readonly message = signal(null); + protected readonly failed = signal(false); + + constructor() { + const fragment = new URLSearchParams(window.location.hash.replace(/^#/, '')); + const state = new URLSearchParams(window.location.search).get('state'); + const expected = sessionStorage.getItem(OIDC_STATE_KEY); + sessionStorage.removeItem(OIDC_STATE_KEY); + // Out of the history and the Referer before anything else happens (the state is spent too). + history.replaceState(null, '', window.location.pathname); + if (!expected || state !== expected) { + this.failed.set(true); + this.message.set('External sign-in refused: the state does not match. Start again.'); + return; + } + + const token = fragment.get('exchange_token'); + const notice = fragment.get('notice'); + const error = fragment.get('error'); + if (!token) { + this.failed.set(!!error || !notice); + this.message.set(error ?? notice ?? 'There is nothing to sign in with.'); + return; + } + this.session.exchange(token).subscribe((outcome) => { + if (outcome.kind === 'signedIn') { + this.flash.clear(); + void this.router.navigateByUrl(safeLocalUrl(this.route.snapshot.queryParamMap.get('returnUrl')) ?? '/packages', { replaceUrl: true }); + } else { + // 'twoFactor' would need the code step of the sign-in page; this sample only reports it. + this.failed.set(true); + this.message.set(outcome.kind === 'twoFactor' ? 'This account needs a second factor: sign in with the password form.' : 'The sign-in link expired or was already used.'); + } + }); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/forgot-password.ts b/samples/BaGet.Frontend.Angular/src/app/pages/forgot-password.ts new file mode 100644 index 000000000..67cd76e3c --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/forgot-password.ts @@ -0,0 +1,67 @@ +import { Component, inject, signal } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; +import { RouterLink } from '@angular/router'; +import { ApiClient } from '../api/api-client'; +import { FieldErrors } from '../api/field-errors'; +import { applyServerErrors } from '../api/screens'; + +/** + * `POST /api/ui/account/forgotpassword` and `POST /api/ui/account/resend-confirmation` take `{ identifier }` (user name or email). + * The answer is the same whether or not an account matches, so the page says "if it exists". + */ +@Component({ + selector: 'app-forgot-password', + imports: [ReactiveFormsModule, RouterLink, FieldErrors], + template: ` +

Forgot your password?

+ @for (message of formErrors(); track message) { + + } + @if (notice(); as text) { +

{{ text }}

+ } +
+ + +
+ + +
+ +

Back to sign-in

+ `, +}) +export class ForgotPassword { + private readonly api = inject(ApiClient); + + protected readonly form = inject(FormBuilder).nonNullable.group({ identifier: ['', Validators.required] }); + protected readonly busy = signal(false); + protected readonly notice = signal(null); + protected readonly formErrors = signal([]); + + protected send(kind: 'forgot' | 'resend'): void { + if (this.form.invalid) { + this.form.markAllAsTouched(); + return; + } + this.busy.set(true); + this.notice.set(null); + const body = this.form.getRawValue(); + const call = kind === 'forgot' + ? this.api.post('/api/ui/account/forgotpassword', { body }) + : this.api.post('/api/ui/account/resend-confirmation', { body }); + call.subscribe((result) => { + this.busy.set(false); + if (result.status === 'Invalid' || result.status === 'Forbidden' || result.status === 'NotFound') { + this.formErrors.set(applyServerErrors(this.form, result)); + } else { + this.formErrors.set([]); + this.notice.set( + kind === 'forgot' + ? 'If an account matches, a reset link is on its way.' + : 'If an unconfirmed account matches, a new confirmation link is on its way.', + ); + } + }); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/package-detail.ts b/samples/BaGet.Frontend.Angular/src/app/pages/package-detail.ts new file mode 100644 index 000000000..92dc2e051 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/package-detail.ts @@ -0,0 +1,62 @@ +import { Component, inject, input } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { RouterLink } from '@angular/router'; +import { combineLatest, startWith, switchMap } from 'rxjs'; +import { ApiClient } from '../api/api-client'; + +/** + * `GET /api/ui/packages/{id}` (latest) or `/api/ui/packages/{id}/{version}`. `id` and `version` come from the route through `withComponentInputBinding()`. + * A missing package is `NotFound` (or `Ok` with `found: false`). + */ +@Component({ + selector: 'app-package-detail', + imports: [RouterLink], + template: ` + @let r = result(); + @if (!r) { +

Loading...

+ } @else if (r.status === 'NotFound' || r.model?.found === false) { +

{{ id() }}

+

This package (or version) does not exist.

+ Back to the list + } @else if (r.status !== 'Ok') { +

{{ (r.errors?.[''] ?? ['The package could not be loaded.'])[0] }}

+ } @else { + @let m = r.model!; +

{{ m.package?.id }} {{ m.package?.version }}

+

{{ m.package?.description }}

+

{{ m.totalDownloads }} downloads - {{ (m.package?.authors ?? []).join(', ') }}

+ + @for (tab of m.installTabs ?? []; track tab.name) { +

{{ tab.name }}

+
{{ (tab.lines ?? []).join('\\n') }}
+ } + +

Versions

+
    + @for (v of m.versions ?? []; track v.version) { +
  • + {{ v.version }} + - {{ v.downloads }} downloads +
  • + } +
+ } + `, +}) +export class PackageDetail { + private readonly api = inject(ApiClient); + + readonly id = input.required(); + readonly version = input(); + + protected readonly result = toSignal( + combineLatest([toObservable(this.id), toObservable(this.version)]).pipe( + switchMap(([id, version]) => (version ? this.api.get('/api/ui/packages/{id}/{version}', { path: { id, version } }) : this.api.get('/api/ui/packages/{id}', { path: { id } })).pipe( + startWith(null), + ), + ), + ), + { initialValue: null }, + ); +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/packages.ts b/samples/BaGet.Frontend.Angular/src/app/pages/packages.ts new file mode 100644 index 000000000..1d43ae5b9 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/packages.ts @@ -0,0 +1,91 @@ +import { Component, inject } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { map, startWith, switchMap } from 'rxjs'; +import { ApiClient } from '../api/api-client'; + +/** The home screen twin: `GET /api/ui/packages?q=&p=&prerelease=&sortBy=` (anonymous). The state lives in the URL. */ +@Component({ + selector: 'app-packages', + imports: [FormsModule, RouterLink], + template: ` +

Packages

+
+ + + + +
+ + @let r = result(); + @if (!r) { +

Loading...

+ } @else if (r.status !== 'Ok') { +

{{ (r.errors?.[''] ?? ['The packages could not be loaded.'])[0] }}

+ } @else { +
    + @for (p of r.model?.packages ?? []; track p.id) { +
  • + {{ p.title || p.id }} + {{ p.version }} - {{ p.totalDownloads }} downloads +
    {{ p.summary || p.description }}
    +
  • + } @empty { +
  • No package found.
  • + } +
+
+ + Page {{ page() }} + +
+ } + `, +}) +export class Packages { + private readonly api = inject(ApiClient); + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + + protected q = this.route.snapshot.queryParamMap.get('q') ?? ''; + protected sort = this.route.snapshot.queryParamMap.get('sortBy') ?? ''; + protected prerelease = this.route.snapshot.queryParamMap.get('prerelease') === 'true'; + + private readonly params = toSignal(this.route.queryParamMap.pipe(map((p) => p)), { requireSync: true }); + protected readonly page = () => Number(this.params().get('p') ?? 1) || 1; + + protected readonly result = toSignal( + this.route.queryParamMap.pipe( + switchMap((p) => + this.api + .get('/api/ui/packages', { + query: { + q: p.get('q') ?? undefined, + p: p.get('p') ?? undefined, + prerelease: p.get('prerelease') === 'true' ? true : undefined, + // The OpenAPI document types the enum as a number; the server binds its name from the query string. + sortBy: (p.get('sortBy') ?? undefined) as never, + }, + }) + .pipe(startWith(null)), + ), + ), + { initialValue: null }, + ); + + protected search(): void { + void this.router.navigate([], { + queryParams: { q: this.q || null, sortBy: this.sort || null, prerelease: this.prerelease ? 'true' : null, p: null }, + }); + } + + protected go(page: number): void { + void this.router.navigate([], { queryParams: { p: page > 1 ? page : null }, queryParamsHandling: 'merge' }); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/register.ts b/samples/BaGet.Frontend.Angular/src/app/pages/register.ts new file mode 100644 index 000000000..4664f023e --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/register.ts @@ -0,0 +1,80 @@ +import { Component, inject, signal } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; +import { Router, RouterLink } from '@angular/router'; +import { ApiClient } from '../api/api-client'; +import { FieldErrors } from '../api/field-errors'; +import { Flash, applyServerErrors, follow } from '../api/screens'; +import { SessionService } from '../session/session.service'; + +/** + * `POST /api/ui/account/register`. Answers `model.session` (tokens: signed in at once) when the account is usable, otherwise the + * flags `confirmationSent` / `awaitingApproval`. `Invalid` carries `errors` per field. `404` = registration is closed. + */ +@Component({ + selector: 'app-register', + imports: [ReactiveFormsModule, RouterLink, FieldErrors], + template: ` +

Register

+ @for (message of formErrors(); track message) { + + } + @if (done(); as text) { +

{{ text }}

+ Sign in + } @else { +
+ + + + + + + + + + + } + `, +}) +export class Register { + private readonly api = inject(ApiClient); + private readonly session = inject(SessionService); + private readonly router = inject(Router); + private readonly flash = inject(Flash); + + protected readonly form = inject(FormBuilder).nonNullable.group({ + userName: ['', Validators.required], + email: [''], + password: ['', Validators.required], + confirmPassword: ['', Validators.required], + }); + protected readonly busy = signal(false); + protected readonly formErrors = signal([]); + protected readonly done = signal(null); + + protected submit(): void { + if (this.form.invalid) { + this.form.markAllAsTouched(); + return; + } + this.busy.set(true); + this.api.post('/api/ui/account/register', { body: this.form.getRawValue() }).subscribe((result) => { + this.busy.set(false); + const model = result.model; + if (result.status === 'Invalid' || result.status === 'Forbidden' || result.status === 'NotFound') { + this.formErrors.set(applyServerErrors(this.form, result)); + if (result.status === 'NotFound') { + this.formErrors.set(['Registration is closed.']); + } + } else if (this.session.adopt(model?.session)) { + follow(this.router, this.flash, result); + } else if (model?.awaitingApproval) { + this.done.set('Account created. An administrator must approve it before you can sign in.'); + } else if (model?.confirmationSent) { + this.done.set('Account created. Follow the link in the email we sent you to confirm your address.'); + } else { + follow(this.router, this.flash, result, ['/sign-in']); + } + }); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/reset-password.ts b/samples/BaGet.Frontend.Angular/src/app/pages/reset-password.ts new file mode 100644 index 000000000..850436c5c --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/reset-password.ts @@ -0,0 +1,68 @@ +import { Component, inject, signal } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { ApiClient } from '../api/api-client'; +import { FieldErrors } from '../api/field-errors'; +import { Flash, applyServerErrors } from '../api/screens'; + +/** + * The email link `{SpaBasePath}/reset-password?userId=&code=`. The `code` is posted back unchanged with the new password + * (`POST /api/ui/account/resetpassword`); a bad or expired code is `Invalid` with the reason in `errors`. + */ +@Component({ + selector: 'app-reset-password', + imports: [ReactiveFormsModule, RouterLink, FieldErrors], + template: ` +

Choose a new password

+ @for (message of formErrors(); track message) { + + } + @if (!userId || !code) { +

This link is incomplete. Ask for a new one.

+ } @else { +
+ + + + + + + } + `, +}) +export class ResetPassword { + private readonly api = inject(ApiClient); + private readonly router = inject(Router); + private readonly flash = inject(Flash); + private readonly query = inject(ActivatedRoute).snapshot.queryParamMap; + + protected readonly userId = this.query.get('userId'); + protected readonly code = this.query.get('code'); + + protected readonly form = inject(FormBuilder).nonNullable.group({ + password: ['', Validators.required], + confirmPassword: ['', Validators.required], + }); + protected readonly busy = signal(false); + protected readonly formErrors = signal([]); + + protected submit(): void { + if (this.form.invalid) { + this.form.markAllAsTouched(); + return; + } + this.busy.set(true); + const { password, confirmPassword } = this.form.getRawValue(); + this.api + .post('/api/ui/account/resetpassword', { body: { userId: this.userId, code: this.code, password, confirmPassword } }) + .subscribe((result) => { + this.busy.set(false); + if (result.status === 'Invalid' || result.status === 'Forbidden' || result.status === 'NotFound') { + this.formErrors.set(applyServerErrors(this.form, result)); + return; + } + this.flash.show(result.next?.message ?? 'Your password was changed. Sign in with the new one.'); + void this.router.navigate(['/sign-in']); + }); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/pages/sign-in.ts b/samples/BaGet.Frontend.Angular/src/app/pages/sign-in.ts new file mode 100644 index 000000000..b96b0ebbf --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/pages/sign-in.ts @@ -0,0 +1,143 @@ +import { Component, inject, signal } from '@angular/core'; +import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { Observable } from 'rxjs'; +import { ApiClient } from '../api/api-client'; +import { FieldErrors } from '../api/field-errors'; +import { Flash, applyServerErrors, safeLocalUrl } from '../api/screens'; +import { OIDC_STATE_KEY } from '../session/oidc-state'; +import { SessionService, SignInOutcome } from '../session/session.service'; + +type Step = 'password' | 'code' | 'recovery'; + +/** + * Sign-in: user name and password, then the authenticator code (or a recovery code) when the account has two-factor. + * `POST /api/ui/session` -> tokens, or `{ twoFactorRequired, twoFactorTicket }` -> `POST /session/two-factor` or `/recovery-code`. + */ +@Component({ + selector: 'app-sign-in', + imports: [ReactiveFormsModule, RouterLink, FieldErrors], + template: ` +

Sign in

+ @for (message of formErrors(); track message) { + + } + + @if (step() === 'password') { +
+ + + + + + +

+ @for (provider of providers(); track provider.id) { + + - + } + Forgot your password? - Register +

+ } @else { +
+ + + + +

+ +

+ } + `, +}) +export class SignIn { + private readonly fb = inject(FormBuilder).nonNullable; + private readonly session = inject(SessionService); + private readonly router = inject(Router); + private readonly route = inject(ActivatedRoute); + private readonly api = inject(ApiClient); + private readonly flash = inject(Flash); + + protected readonly credentials = this.fb.group({ + userName: ['', Validators.required], + password: ['', Validators.required], + }); + protected readonly second = this.fb.group({ code: ['', Validators.required] }); + + protected readonly step = signal('password'); + protected readonly busy = signal(false); + protected readonly formErrors = signal([]); + /** One button per external provider the server offers (the sign-in screen model lists them). */ + protected readonly providers = signal<{ id: string; displayName: string }[]>([]); + private ticket = ''; + + constructor() { + // Anonymous endpoint; an error answer (the client never throws) just means no external buttons. + this.api.get('/api/ui/session/providers').subscribe((result) => this.providers.set(result.model?.providers ?? [])); + } + + protected submitPassword(): void { + if (this.credentials.invalid) { + this.credentials.markAllAsTouched(); + return; + } + const { userName, password } = this.credentials.getRawValue(); + this.run(this.session.signIn(userName, password), this.credentials); + } + + protected submitSecondFactor(): void { + if (this.second.invalid) { + this.second.markAllAsTouched(); + return; + } + const { code } = this.second.getRawValue(); + this.run( + this.step() === 'code' + ? this.session.signInWithTwoFactor(this.ticket, code) + : this.session.signInWithRecoveryCode(this.ticket, code), + this.second, + ); + } + + /** External provider `id`: a browser navigation (not XHR); the server comes back to `sign-in/external#exchange_token=...`. */ + protected signInWithProvider(id: string): void { + // A random state binds the answer to this browser: the callback exchanges only when it comes back unchanged. + const state = Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join(''); + sessionStorage.setItem(OIDC_STATE_KEY, state); + const returnUrl = new URL('sign-in/external', document.baseURI); + returnUrl.searchParams.set('state', state); + window.location.assign(`${this.api.baseUrl}/api/ui/session/external/${encodeURIComponent(id)}?returnUrl=${encodeURIComponent(returnUrl.toString())}`); + } + + private run(outcome$: Observable, form: FormGroup): void { + this.busy.set(true); + this.formErrors.set([]); + outcome$.subscribe((outcome) => { + this.busy.set(false); + switch (outcome.kind) { + case 'signedIn': { + this.flash.clear(); + const target = safeLocalUrl(this.route.snapshot.queryParamMap.get('returnUrl')) ?? '/packages'; + void this.router.navigateByUrl(target); + break; + } + case 'twoFactor': + this.ticket = outcome.ticket; + this.step.set('code'); + break; + case 'failed': + // 401 wrong credentials / code, 403 locked out, awaiting approval or email not confirmed, 400 empty form. + this.formErrors.set(applyServerErrors(form, outcome.result)); + if (!this.formErrors().length && !form.invalid) { + this.formErrors.set(['Sign-in failed.']); + } + break; + } + }); + } +} diff --git a/samples/BaGet.Frontend.Angular/src/app/session/auth.guard.ts b/samples/BaGet.Frontend.Angular/src/app/session/auth.guard.ts new file mode 100644 index 000000000..21f7de407 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/session/auth.guard.ts @@ -0,0 +1,10 @@ +import { inject } from '@angular/core'; +import { CanActivateFn, Router } from '@angular/router'; +import { SessionService } from './session.service'; + +/** Signed-in routes: anyone else goes to the sign-in page, which returns here afterwards. */ +export const authGuard: CanActivateFn = (_route, state) => { + const session = inject(SessionService); + const router = inject(Router); + return session.isSignedIn() || router.createUrlTree(['/sign-in'], { queryParams: { returnUrl: state.url } }); +}; diff --git a/samples/BaGet.Frontend.Angular/src/app/session/oidc-state.ts b/samples/BaGet.Frontend.Angular/src/app/session/oidc-state.ts new file mode 100644 index 000000000..57efa9e98 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/session/oidc-state.ts @@ -0,0 +1,2 @@ +/** `sessionStorage` key of the random `state` saved before the external sign-in redirect and checked on the callback. */ +export const OIDC_STATE_KEY = 'baget.oidc-state'; diff --git a/samples/BaGet.Frontend.Angular/src/app/session/session.interceptor.ts b/samples/BaGet.Frontend.Angular/src/app/session/session.interceptor.ts new file mode 100644 index 000000000..825fffdad --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/session/session.interceptor.ts @@ -0,0 +1,64 @@ +import { HttpContextToken, HttpErrorResponse, HttpInterceptorFn, HttpRequest, HttpResponse } from '@angular/common/http'; +import { inject } from '@angular/core'; +import { Router } from '@angular/router'; +import { catchError, switchMap, tap, throwError } from 'rxjs'; +import { ApiClient } from '../api/api-client'; +import { SessionService } from './session.service'; + +/** Set on the one retry, so a request is never retried twice. */ +const RETRIED = new HttpContextToken(() => false); + +/** `/api/ui/session*` endpoints ignore (and must not trigger a refresh for) the access token: the wrong password is a 401 too. */ +function isSessionEndpoint(url: string): boolean { + return /\/api\/ui\/session(\/|\?|$)/.test(url) && !url.includes('/session/sign-out'); +} + +/** + * Adds `Authorization: Bearer ` to the calls to the API (and to nothing else), keeps the renewed tokens the + * server sends in `X-Session-*` headers, and on a 401 refreshes the session once (single flight, see `SessionService.refresh`) and + * repeats the request. When the refresh is refused the session is over: the person goes to the sign-in page. + */ +export const sessionInterceptor: HttpInterceptorFn = (request, next) => { + const api = inject(ApiClient); + const session = inject(SessionService); + const router = inject(Router); + + if (!api.isApiUrl(request.url)) { + return next(request); + } + + const send = (req: HttpRequest) => { + const token = session.token; + const authorized = token && !isSessionEndpoint(req.url) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req; + return next(authorized).pipe( + tap((event) => { + if (event instanceof HttpResponse) { + session.applyRenewedHeaders(event.headers); + } + }), + ); + }; + + return send(request).pipe( + catchError((error: unknown) => { + const canRefresh = + error instanceof HttpErrorResponse && + error.status === 401 && + !isSessionEndpoint(request.url) && + !request.context.get(RETRIED) && + session.hasRefreshToken; + if (!canRefresh) { + return throwError(() => error); + } + return session.refresh().pipe( + switchMap((renewed) => { + if (renewed) { + return send(request.clone({ context: request.context.set(RETRIED, true) })); + } + void router.navigate(['/sign-in'], { queryParams: { returnUrl: router.url } }); + return throwError(() => error); + }), + ); + }), + ); +}; diff --git a/samples/BaGet.Frontend.Angular/src/app/session/session.service.ts b/samples/BaGet.Frontend.Angular/src/app/session/session.service.ts new file mode 100644 index 000000000..6f164991c --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/app/session/session.service.ts @@ -0,0 +1,155 @@ +import { HttpHeaders } from '@angular/common/http'; +import { Injectable, computed, inject, signal } from '@angular/core'; +import { Observable, finalize, map, of, shareReplay, tap } from 'rxjs'; +import { ApiClient } from '../api/api-client'; +import type { ScreenResult, SessionModel } from '../api/api-types'; + +const REFRESH_KEY = 'baget.refreshToken'; + +export type SignInOutcome = + | { kind: 'signedIn' } + | { kind: 'twoFactor'; ticket: string } + | { kind: 'failed'; result: ScreenResult }; + +/** + * The interactive session of a person (`POST /api/ui/session`). + * + * Where the tokens live (the trade-off): + * - the access token (15 minutes) stays in memory only: a script injected into the page can still use it while the page is open, + * but it is gone with the tab and never written anywhere; + * - the refresh token (14 days) is kept in sessionStorage so a reload or F5 does not sign the person out. sessionStorage is per + * tab and dies with it, but is readable by any script of this origin (XSS), unlike an HttpOnly cookie. If that is not + * acceptable, keep the refresh token in memory too (a reload then signs out) or serve the application from BaGet's own origin and use + * the cookie mode (`POST /api/ui/session/cookie` + `X-XSRF-TOKEN`, see README). + * The server never stores a token: "sign out" forgets them here, "sign out everywhere" changes the account's security stamp. + */ +@Injectable({ providedIn: 'root' }) +export class SessionService { + private readonly api = inject(ApiClient); + + private readonly accessToken = signal(null); + private readonly refreshToken = signal(sessionStorage.getItem(REFRESH_KEY)); + + /** The signed-in user name (the sign-in answers carry it; after a reload it may be unknown until the first answer that does). */ + readonly userName = signal(null); + readonly isSignedIn = computed(() => this.accessToken() !== null); + + private refreshing: Observable | null = null; + + /** The token the interceptor adds, if any. */ + get token(): string | null { + return this.accessToken(); + } + + get hasRefreshToken(): boolean { + return this.refreshToken() !== null; + } + + /** Startup: a refresh token left by a reload is exchanged for an access token before the first guard runs. */ + restore(): Observable { + return this.hasRefreshToken ? this.refresh() : of(false); + } + + signIn(userName: string, password: string): Observable { + return this.api.post('/api/ui/session', { body: { userName, password } }).pipe(map((r) => this.outcome(r))); + } + + signInWithTwoFactor(ticket: string, code: string): Observable { + return this.api.post('/api/ui/session/two-factor', { body: { ticket, code } }).pipe(map((r) => this.outcome(r))); + } + + signInWithRecoveryCode(ticket: string, recoveryCode: string): Observable { + return this.api.post('/api/ui/session/recovery-code', { body: { ticket, recoveryCode } }).pipe(map((r) => this.outcome(r))); + } + + /** The 60-second token an external provider's sign-in left in the URL fragment. */ + exchange(exchangeToken: string): Observable { + return this.api.post('/api/ui/session/exchange', { body: { exchangeToken } }).pipe(map((r) => this.outcome(r))); + } + + /** Takes the tokens of a session answer (the sign-in forms and a registration that signs in at once). */ + adopt(session: SessionModel | null | undefined): boolean { + if (!session?.accessToken || !session.refreshToken) { + return false; + } + this.store(session.accessToken, session.refreshToken, session.userName ?? null); + return true; + } + + /** + * Renews the pair with the refresh token. Single flight: while one refresh runs every caller (several requests failing with + * 401 at once) shares it, because a second use of the same refresh token would just be a second pair. A refused refresh + * (expired, password changed, signed out everywhere, 30-day cap) ends the session locally. + */ + refresh(): Observable { + if (this.refreshing) { + return this.refreshing; + } + const token = this.refreshToken(); + if (!token) { + this.clear(); + return of(false); + } + this.refreshing = this.api.post('/api/ui/session/refresh', { body: { refreshToken: token } }).pipe( + map((result) => { + if (result.status === 'Ok' && this.adopt(result.model)) { + return true; + } + this.clear(); + return false; + }), + finalize(() => (this.refreshing = null)), + shareReplay({ bufferSize: 1, refCount: false }), + ); + return this.refreshing; + } + + /** + * Picks the renewed pair from the response headers. The server sets them when the current session itself changed the account's + * security (password change, two-factor, sign out everywhere): the old tokens are dead, replace them. + */ + applyRenewedHeaders(headers: HttpHeaders): void { + const access = headers.get('X-Session-Access-Token'); + const refresh = headers.get('X-Session-Refresh-Token'); + if (access && refresh) { + this.store(access, refresh, this.userName()); + } + } + + /** Signs out: tells the server (best effort) and forgets the tokens. `everywhere` ends every other session of the account too. */ + signOut(everywhere = false): Observable { + const body = { everywhere, refreshToken: this.refreshToken() ?? undefined }; + return this.api.post('/api/ui/session/sign-out', { body }).pipe( + tap(() => this.clear()), + map(() => undefined), + ); + } + + /** Forgets the session without asking the server (it ended there already, or the page is closing). */ + clear(): void { + this.accessToken.set(null); + this.refreshToken.set(null); + this.userName.set(null); + sessionStorage.removeItem(REFRESH_KEY); + } + + private outcome(result: ScreenResult): SignInOutcome { + const model = result.model; + if (result.status === 'Ok' && model?.twoFactorRequired && model.twoFactorTicket) { + return { kind: 'twoFactor', ticket: model.twoFactorTicket }; + } + if (result.status === 'Ok' && this.adopt(model)) { + return { kind: 'signedIn' }; + } + return { kind: 'failed', result }; + } + + private store(access: string, refresh: string, userName: string | null): void { + this.accessToken.set(access); + this.refreshToken.set(refresh); + sessionStorage.setItem(REFRESH_KEY, refresh); + if (userName) { + this.userName.set(userName); + } + } +} diff --git a/samples/BaGet.Frontend.Angular/src/environments/environment.development.ts b/samples/BaGet.Frontend.Angular/src/environments/environment.development.ts new file mode 100644 index 000000000..e1a39effe --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/environments/environment.development.ts @@ -0,0 +1,4 @@ +/** `ng serve` (http://localhost:4200): BaGet on another origin, which must list this one in `Cors:AllowedOrigins`. */ +export const environment = { + apiBaseUrl: 'http://localhost:6060', +}; diff --git a/samples/BaGet.Frontend.Angular/src/environments/environment.ts b/samples/BaGet.Frontend.Angular/src/environments/environment.ts new file mode 100644 index 000000000..dedf3bddb --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/environments/environment.ts @@ -0,0 +1,7 @@ +/** + * Production settings. `apiBaseUrl` is the origin of the BaGet server; empty = the same origin as this page, which is what + * you want when BaGet serves the built application itself (`Frontend:SpaPath`, `Frontend:SpaBasePath=/app`). + */ +export const environment = { + apiBaseUrl: '', +}; diff --git a/samples/BaGet.Frontend.Angular/src/index.html b/samples/BaGet.Frontend.Angular/src/index.html new file mode 100644 index 000000000..8e79e961a --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/index.html @@ -0,0 +1,13 @@ + + + + + BaGet - Angular sample + + + + + + + + diff --git a/samples/BaGet.Frontend.Angular/src/main.ts b/samples/BaGet.Frontend.Angular/src/main.ts new file mode 100644 index 000000000..5df75f9c8 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/main.ts @@ -0,0 +1,6 @@ +import { bootstrapApplication } from '@angular/platform-browser'; +import { appConfig } from './app/app.config'; +import { App } from './app/app'; + +bootstrapApplication(App, appConfig) + .catch((err) => console.error(err)); diff --git a/samples/BaGet.Frontend.Angular/src/styles.css b/samples/BaGet.Frontend.Angular/src/styles.css new file mode 100644 index 000000000..f347865c3 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/src/styles.css @@ -0,0 +1,21 @@ +body { font-family: system-ui, sans-serif; margin: 0; color: #222; background: #fafafa; } +header { display: flex; gap: 1rem; align-items: center; padding: .6rem 1rem; background: #1f2937; color: #fff; } +header a { color: #cbd5e1; text-decoration: none; } +header a.active, header a.brand { color: #fff; font-weight: 600; } +header nav { display: flex; gap: 1rem; } +.spacer { flex: 1; } +main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } +form { display: grid; gap: .6rem; max-width: 24rem; } +label { display: grid; gap: .2rem; font-weight: 600; } +input, select { padding: .4rem; font: inherit; } +button { padding: .4rem .8rem; font: inherit; cursor: pointer; } +button.link { border: 0; background: none; color: #2563eb; padding: 0; text-decoration: underline; } +.error { color: #b91c1c; } +.notice { color: #166534; } +small.error { display: block; font-weight: 400; } +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; padding: .35rem .5rem; border-bottom: 1px solid #ddd; } +ul.packages { list-style: none; padding: 0; display: grid; gap: .8rem; } +ul.packages li { background: #fff; border: 1px solid #ddd; padding: .6rem .8rem; } +.muted { color: #666; } +.row { display: flex; gap: .5rem; align-items: end; flex-wrap: wrap; } diff --git a/samples/BaGet.Frontend.Angular/tsconfig.app.json b/samples/BaGet.Frontend.Angular/tsconfig.app.json new file mode 100644 index 000000000..cb151e101 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/tsconfig.app.json @@ -0,0 +1,14 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "types": [] + }, + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "src/**/*.spec.ts" + ] +} diff --git a/samples/BaGet.Frontend.Angular/tsconfig.json b/samples/BaGet.Frontend.Angular/tsconfig.json new file mode 100644 index 000000000..930544683 --- /dev/null +++ b/samples/BaGet.Frontend.Angular/tsconfig.json @@ -0,0 +1,30 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compileOnSave": false, + "compilerOptions": { + "strict": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true, + "isolatedModules": true, + "experimentalDecorators": true, + "importHelpers": true, + "target": "ES2022", + "module": "preserve" + }, + "angularCompilerOptions": { + "enableI18nLegacyMessageIdFormat": false, + "strictInjectionParameters": true, + "strictTemplates": true, + "strictInputAccessModifiers": true + }, + "files": [], + "references": [ + { + "path": "./tsconfig.app.json" + } + ] +} diff --git a/samples/BaGet.Frontend.React/.env.example b/samples/BaGet.Frontend.React/.env.example new file mode 100644 index 000000000..eb5d86fc5 --- /dev/null +++ b/samples/BaGet.Frontend.React/.env.example @@ -0,0 +1,3 @@ +# Empty = same origin (served by BaGet under /app, or the Vite dev proxy). +# A separate origin must be listed in BaGet's Cors:AllowedOrigins. +VITE_BAGET_URL= diff --git a/samples/BaGet.Frontend.React/.gitignore b/samples/BaGet.Frontend.React/.gitignore new file mode 100644 index 000000000..0de4ddd35 --- /dev/null +++ b/samples/BaGet.Frontend.React/.gitignore @@ -0,0 +1,4 @@ +node_modules +dist +*.tsbuildinfo +.env.local diff --git a/samples/BaGet.Frontend.React/README.md b/samples/BaGet.Frontend.React/README.md new file mode 100644 index 000000000..7d618f409 --- /dev/null +++ b/samples/BaGet.Frontend.React/README.md @@ -0,0 +1,63 @@ +# BaGet.Frontend.React + +Small React 18 + TypeScript (strict) + Vite single-page app on BaGet's [`/api/ui`](../../docs/ui-api.md). Types come from the OpenAPI document (`openapi-typescript`), calls go through `openapi-fetch` (typed paths). No UI framework. + +| Screen | Route | Twin | +|---|---|---| +| Package list / search | `/` | `GET /api/ui/packages` | +| Package detail | `/packages/:id/:version` | `GET /api/ui/packages/{id}/{version}` | +| Sign in (password, two-factor or recovery code, external fragment) | `/sign-in` | `POST /api/ui/session`, `/session/two-factor`, `/session/recovery-code`, `/session/exchange` | +| Register, forgot / reset password, confirm email | `/register`, `/forgot-password`, `/reset-password`, `/confirm-email` | `/api/ui/account/*` | +| Users (admin; shows 401 SignIn / 403 Forbidden) | `/admin/users` | `GET /api/ui/admin/users` | + +The email routes match `Frontend:SpaLinks` (`{SpaBasePath}/confirm-email`, `/reset-password`, `/sign-in`). + +## Prerequisites + +Node 20+ (or Docker with `node:22-alpine`), and a BaGet with accounts on (the default). + +## BaGet settings + +| Case | Settings | +|---|---| +| Dev, Vite on `http://localhost:5173` | `Cors:AllowedOrigins=http://localhost:5173` (session endpoints refuse browser origins that are not listed); `Frontend:SpaUrl=http://localhost:5173` so emails link to the dev server; `VITE_BAGET_URL=http://localhost:6060` for a direct call, or leave it empty to use the Vite proxy (`BAGET_DEV_PROXY`, default `http://localhost:6060`), which still sends `Origin: http://localhost:5173` | +| Served by BaGet | `Frontend:SpaPath=`, `Frontend:SpaBasePath=/app` (the build's Vite `base`); same origin, so `VITE_BAGET_URL` stays empty and no CORS entry is needed. Emails link to the app with `Frontend:SpaLinks=true` (or `Frontend:Mvc=false`). External sign-in returns must lie under the base path; the app adds a random `state` to the return address and checks it before exchanging the token (each exchange token works once). When the app is hosted elsewhere, set `Frontend:SpaUrl` to its absolute address | +| Other base path | change `base` in `vite.config.ts` and `Frontend:SpaBasePath` together | + +## Commands + +``` +npm install +npm run dev # http://localhost:5173 +npm run build # tsc --noEmit + vite build -> dist/ +npm run lint # tsc --noEmit +npm run smoke -- http://localhost:6060 Admin 'Admin1234!' [origin] # sign in + list packages, no browser +``` + +Without Node: `docker run --rm -v "$PWD:/app" -w /app node:22-alpine sh -c "npm install && npm run build"`. + +## Regenerating the client + +`npm run gen:api` rewrites `src/api/schema.d.ts` from `openapi/ui.json`. To refresh the document: + +``` +curl -H "Authorization: Bearer " http://localhost:6060/openapi/ui.json -o openapi/ui.json +``` + +`` is an administrator's API key with the `admin:api` scope and no repository limit, or the global `ApiKey`; anyone else gets 404. Session tokens do not work there. + +## Notes on the code + +- `src/api/client.ts`: the `openapi-fetch` middleware adds `Authorization: Bearer `, adopts renewed `X-Session-*` headers, and on a 401 refreshes once (shared promise) and replays the request. +- `src/api/screen.ts`: `toScreen` normalises a `ScreenResult` (only 200 is typed in the OpenAPI document; 400/401/403/404 bodies arrive in `error`) and `nextRoute` uses `src/routes.ts` to map `next.screen` `{controller, action}` to a route. +- `src/components/Form.tsx`: field errors and the `""` form-level errors. +- Known mismatch: the document types `status` as an integer but the server sends the name (`"Ok"`); `toScreen` accepts both. + +## Token storage + +| Token | Where | Risk | +|---|---|---| +| Access (15 min) | memory | readable by script injected into the page, gone on reload | +| Refresh (14 days) | `sessionStorage` | survives reloads of the tab, cleared when it closes, readable by XSS | + +Never `localStorage` (shared across tabs, survives restarts) and never a URL (only the 60-second external exchange token travels in a fragment, removed with `history.replaceState` at once). Sign out only forgets the tokens; "Sign out everywhere" changes the account's security stamp and ends every session. For stronger protection serve the app from BaGet's origin and use the cookie mode, or put a backend-for-frontend in front. Escape or sanitise any HTML from the API (`readmeHtml`) before injecting it. diff --git a/samples/BaGet.Frontend.React/index.html b/samples/BaGet.Frontend.React/index.html new file mode 100644 index 000000000..9f347a68c --- /dev/null +++ b/samples/BaGet.Frontend.React/index.html @@ -0,0 +1,12 @@ + + + + + + BaGet + + +
+ + + diff --git a/samples/BaGet.Frontend.React/openapi/ui.json b/samples/BaGet.Frontend.React/openapi/ui.json new file mode 100644 index 000000000..7132e5afb --- /dev/null +++ b/samples/BaGet.Frontend.React/openapi/ui.json @@ -0,0 +1,44455 @@ +{ + "openapi": "3.0.4", + "info": { + "title": "BaGet UI API", + "description": "The JSON twin of every screen of the web UI (/api/ui). Authenticate with an API key as 'Authorization: Bearer ' or the X-NuGet-ApiKey header, or, for a person, with a session token ('Authorization: Bearer bgs.xxx') from POST /api/ui/session (a single-page application on any origin). A same-origin client may use the browser cookie if it sends the antiforgery token of GET /api/ui/antiforgery in the X-XSRF-TOKEN header on every request; the bare cookie and HTTP Basic are not accepted. Administration screens need an administrator's key with the admin:api scope and no repository limit, or an administrator's interactive session (the global ApiKey is refused). Account self-service and package ownership screens need an interactive session; API keys are refused with 403.", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost:6193/" + } + ], + "paths": { + "/api/ui/account/login": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The sign-in form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Signs in. Success sets the session cookie and continues at `next.localUrl` (the local return URL, else the site root), or at the second-factor screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LoginForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LoginForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LoginForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLoginViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/loginwith2fa": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The authenticator code form (back to sign-in without the half-signed-in cookie).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "rememberMe", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Completes the sign-in with an authenticator code.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorLoginForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorLoginForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorLoginForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorLoginViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/loginwithrecoverycode": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The recovery code form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Completes the sign-in with a recovery code (each works once).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RecoveryCodeLoginForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RecoveryCodeLoginForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RecoveryCodeLoginForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRecoveryCodeLoginViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/logout": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The sign-out screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Signs the user out.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/account/register": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The registration form (404 while `Accounts:AllowRegistration` is off).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Creates an account (and signs it in when no confirmation or approval is pending).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RegisterForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RegisterForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RegisterForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRegisterViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/confirmemail": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The target of the links in confirmation emails (a GET that confirms the address, like the page).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "userId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "code", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "email", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfConfirmEmailViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/forgotpassword": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The \"forgot password\" form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Asks for a reset link. The answer is the same whether or not an account matches.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/resetpassword": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The new-password form behind the link of a reset email.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "userId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "code", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AccountApi" + ], + "summary": "Sets the new password from the link; success continues at the sign-in screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResetPasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResetPasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResetPasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfResetPasswordViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/reauthenticate": { + "get": { + "tags": [ + "AccountApi" + ], + "summary": "The \"confirm it is you\" screen (the button that starts the provider's sign-in is browser-only).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReauthenticateViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations": { + "get": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "The organizations of the user.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations/create": { + "post": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "Create an organization.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/CreateOrganizationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/CreateOrganizationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/CreateOrganizationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations/add-member": { + "post": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "Add a member (organization administrators only; 403 otherwise).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AddOrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AddOrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AddOrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/organizations/remove-member": { + "post": { + "tags": [ + "AccountOrganizationsApi" + ], + "summary": "Remove a member (an administrator removes anyone; any member may leave; 403 otherwise).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveOrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveOrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveOrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/packages": { + "get": { + "tags": [ + "AccountPackagesApi" + ], + "summary": "The package IDs the user owns, per repository.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/access": { + "get": { + "tags": [ + "AccountPackagesApi" + ], + "summary": "What the user may do in each repository (optionally for one package ID).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "package", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccountAccessViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/profile": { + "get": { + "tags": [ + "AccountPackagesApi" + ], + "summary": "The user's own profile: continues at `next.localUrl` (`~/profiles/{name}`).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/account/settings": { + "get": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Account settings.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/change-password": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Change the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangePasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangePasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangePasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/change-email": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Change the email address (asks the password again).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangeEmailForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangeEmailForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ChangeEmailForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/unlink-external": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Unlinks the account's login at an external provider (asks the password again; refused when it is the only way to sign in). Linking is browser-only: it redirects to the provider.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UnlinkExternalForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UnlinkExternalForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UnlinkExternalForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/settings/delete": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Delete the account (asks the password again). Success signs the user out.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor": { + "get": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Two-factor authentication (the setup key and QR code while it is off).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor/enable": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Turn two-factor authentication on with a code from the authenticator; the answer carries the recovery codes, once.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorCodeForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorCodeForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TwoFactorCodeForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor/disable": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Turn two-factor authentication off (asks the password again).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/twofactor/reset": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Reset the authenticator (asks the password again).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordConfirmationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfTwoFactorViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/apikeys": { + "get": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "The user's API keys (never their values) and the new-key form.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/apikeys/create": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Creates a key. The answer carries its value (`createdKey`) once.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ApiKeyForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ApiKeyForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ApiKeyForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + } + } + } + }, + "/api/ui/account/apikeys/revoke/{key}": { + "post": { + "tags": [ + "AccountSettingsApi" + ], + "summary": "Revokes a key.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiKeysViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/audit": { + "get": { + "tags": [ + "AdminAuditApi" + ], + "summary": "Lists the entries that match the filter.", + "parameters": [ + { + "name": "actor", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "subject", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "from", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "to", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAuditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups": { + "get": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Lists the groups.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Creates a group and points at it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupCreation" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupCreation" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupCreation" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}": { + "get": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Shows one group, with the member search for q.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/rename": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Renames the group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupRename" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupRename" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupRename" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/add-member": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Adds a user to the group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/remove-member": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Removes a user from the group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupMemberChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/groups/{name}/delete": { + "post": { + "tags": [ + "AdminGroupsApi" + ], + "summary": "Deletes the group with the grants and project roles that name it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfGroupDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/operations": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Lists the operations and their status.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Starts an operation on a repository.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OperationForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OperationForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OperationForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOperationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Lists the pending and quarantined submissions.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation/retry": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Validates the submission again.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation/release": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Indexes the quarantined package although validation failed.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/validation/reject": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Deletes the quarantined package.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SubmissionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/abuse": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Lists the abuse reports (the unresolved ones unless all).", + "parameters": [ + { + "name": "all", + "in": "query", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/abuse/resolve": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Marks a report resolved.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/abuse/reopen": { + "post": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Reopens a resolved report.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AbuseForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAbuseViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/cluster": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "The cluster status; `?refresh=true` runs the health checks again.", + "parameters": [ + { + "name": "refresh", + "in": "query", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfClusterViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/formats": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "The package formats this server can host.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfFormatsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/access-unavailable": { + "get": { + "tags": [ + "AdminOperationsApi" + ], + "summary": "Why the access screens are not available: the configured database has no access model.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAccessUnavailableViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations": { + "get": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Lists the organizations.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminOrganizationsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}": { + "get": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Shows one organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/rename": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Renames the organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationRenameForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationRenameForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationRenameForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/delete": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Deletes the organization (refused while it owns packages).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/add-member": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Adds a user to the organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/set-admin": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Makes a member an administrator of the organization, or not.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/organizations/{name}/remove-member": { + "post": { + "tags": [ + "AdminOrganizationsApi" + ], + "summary": "Removes a member from the organization.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OrganizationMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfOrganizationDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/packages": { + "get": { + "tags": [ + "AdminPackagesApi" + ], + "summary": "Lists the ownerless IDs of every repository, pageNumber being one-based.", + "parameters": [ + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/admin/packages": { + "get": { + "tags": [ + "AdminPackagesApi" + ], + "summary": "Lists the ownerless IDs of every repository, pageNumber being one-based.", + "parameters": [ + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions": { + "get": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Lists the permission targets.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Creates a target and points at it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/preview": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Previews the form patterns without saving anything.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/restore-built-ins": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Re-creates the built-in groups and targets that are missing (the upgrade defaults).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}": { + "get": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Shows one target. principalType and principalName pre-fill the grant form.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "testPackage", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "principalType", + "in": "query", + "schema": { + "$ref": "#/components/schemas/PrincipalType" + } + }, + { + "name": "principalName", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/preview": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Previews the form patterns (and the test package) without saving anything.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/save": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Replaces the target's patterns.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PermissionTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/set-grant": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Gives a principal the ticked actions through the target, replacing an earlier grant to it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GrantForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GrantForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GrantForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/remove-grant": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Removes a principal's grant.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/permissions/{name}/delete": { + "post": { + "tags": [ + "AdminPermissionsApi" + ], + "summary": "Deletes the target and its grants.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPermissionDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects": { + "get": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Lists the projects the caller may open.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Creates a project (server administrators only) and points at it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectCreation" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectCreation" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectCreation" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}": { + "get": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Shows one project.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/set-member": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Gives a user or group a role in the project, replacing an earlier one.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectMemberForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectMemberForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectMemberForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/remove-member": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Takes a user or group out of the project.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalRemoval" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/assign-repository": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Puts a repository in the project (server administrators only); it leaves any project it was in.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/unassign-repository": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Takes a repository out of the project (server administrators only).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectRepositoryForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/create-target": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Creates a permission target that applies only to the project's repositories.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/preview": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Previews the new target's patterns without saving anything.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectTargetForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/projects/{name}/delete": { + "post": { + "tags": [ + "AdminProjectsApi" + ], + "summary": "Deletes the project (server administrators only) with its members and targets; the repositories stay.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProjectDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories": { + "get": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Lists the repositories (narrowed by format, kind, q) and describes the create forms.", + "parameters": [ + { + "name": "format", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "kind", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a local NuGet repository (`name`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/create/format": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a local repository of a format other than NuGet (`name`, `format`, `fields`, `anonymousRead`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/create/virtual": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a virtual repository with no members (`name`, `format`, `anonymousRead`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/create/remote": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Creates a remote repository (`name`, `format`, `remote`, `anonymousRead`, `password`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryCreateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoriesViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}": { + "get": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Shows one repository.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Saves the repository (`anonymousRead`; a remote one also `remote` and `password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/maven-settings": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Saves the policy of a local Maven repository (`policy`, `redeploy`, `snapshotBuilds`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/test": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Asks a remote repository's upstream with the unsaved `remote` values and saves nothing (`password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/purge": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Deletes everything a remote repository cached (`password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/purge-package": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Deletes one cached package of a remote repository (`packageId`, `packageVersion`, `password`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/add-member": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Adds a member at the end of a virtual repository (`member`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/remove-member": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Removes a member of a virtual repository (`member`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/move-member": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Moves a member of a virtual repository up or down (`member`, `direction`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/deploy": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Sets the member of a virtual repository that receives uploads (`deploy`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/preview": { + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Shows where a package version would come from in a virtual repository (`previewPackageId`, `previewVersion`).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryEditRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryEditViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/repositories/{name}/delete": { + "get": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Shows what deleting the repository does.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminRepositoriesApi" + ], + "summary": "Deletes the repository (refused while it holds packages or is a member of a virtual repository).", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRepositoryDeleteViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings": { + "get": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Shows the settings; section is the id of the section to show.", + "parameters": [ + { + "name": "section", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Saves the settings of one section: the body names the section, the password and the fields (`v:<key>` values, `reset:<key>`,\r\n`clear:<key>`, `copyData`), each an array of strings.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/copy-status": { + "get": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "The progress of the database copy.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDatabaseCopyStatusView" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/save-provider": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Adds or changes a named OpenID Connect provider (password in the body; takes effect after a restart; a blank secret keeps the saved one).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SignInProviderForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SignInProviderForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SignInProviderForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/remove-provider": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Removes a named OpenID Connect provider saved on this screen (takes effect after a restart).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveSignInProviderForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveSignInProviderForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoveSignInProviderForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/set-log-level": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Sets the lowest level logged for one source.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/remove-log-level": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Removes a per-source level saved on this screen.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/LogLevelForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/settings/test-telemetry": { + "post": { + "tags": [ + "AdminSettingsApi" + ], + "summary": "Sends one test span to the posted, unsaved telemetry endpoint (`v:Telemetry:Otlp:*` fields) and answers the outcome; nothing is saved.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SettingsSubmission" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAdminSettingsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Lists the users, filtered by q (user name contains), one page of them.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/approve": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Enables a self-registered account that waits for approval.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/promote": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Makes a user an administrator.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/demote": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Removes a user's administrator flag.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/reset-password": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Replaces a user's password with a generated one, which the answer carries once (`generatedPassword`).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/send-reset-link": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Mails a user a password reset link.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserChange" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/create": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Creates an account (typed, generated or invited password). A generated password is in the answer once.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserCreation" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserCreation" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserCreation" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUsersViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Shows one account. package is a package ID to evaluate the effective permissions for.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "package", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/approve": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Enables the account when it waits for approval.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/revoke-key": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Revokes one of the account's API keys.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserKeyForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserKeyForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserKeyForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/add-group": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Adds the account to a group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/remove-group": { + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Removes the account from a group.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserGroupForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserDetailViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/delete": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Shows what deleting the account does.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Deletes the account after the administrator's password.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserDeletionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserDeletionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserDeletionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDeleteUserViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/users/{name}/packages": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Lists the package IDs one user owns.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/admin/users/{name}/packages": { + "get": { + "tags": [ + "AdminUsersApi" + ], + "summary": "Lists the package IDs one user owns.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUserPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/contact-owners": { + "get": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "The form's state; 404 when the package has no owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "Sends the message to the owners (400 with the field errors when the message is missing or too long).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/contact-owners": { + "get": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "The form's state; 404 when the package has no owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ContactOwnersApi" + ], + "summary": "Sends the message to the owners (400 with the field errors when the message is missing or too long).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ContactOwnersForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfContactOwnersViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/{image}": { + "get": { + "tags": [ + "DockerManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/{image}": { + "get": { + "tags": [ + "DockerManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/delete-tag/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a tag, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/delete-tag/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a tag, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/delete-manifest/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a manifest with its tags, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/delete-manifest/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes a manifest with its tags, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/prune/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Removes the layers no manifest uses, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/prune/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Removes the layers no manifest uses, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-manage/delete-image/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes the whole image, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-manage/delete-image/{image}": { + "post": { + "tags": [ + "DockerManageApi" + ], + "summary": "Deletes the whole image, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DockerManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}": { + "get": { + "tags": [ + "MavenManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}": { + "get": { + "tags": [ + "MavenManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/add-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/add-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/remove-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/remove-owner": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/delete-file": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one file of the chosen version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-file": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one file of the chosen version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/delete-version": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-version": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes one version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/delete-artifact": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes the whole artifact, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-artifact": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes the whole artifact, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-manage/{group}/{artifact}/cleanup": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes old snapshot builds of a version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/cleanup": { + "post": { + "tags": [ + "MavenManageApi" + ], + "summary": "Deletes old snapshot builds of a version, after the password.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenManageForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/{id}": { + "get": { + "tags": [ + "NpmManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/{id}": { + "get": { + "tags": [ + "NpmManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/add-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/add-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/remove-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/remove-owner/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/set-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Points a dist-tag at a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/set-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Points a dist-tag at a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/remove-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a dist-tag.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/remove-tag/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a dist-tag.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageTagForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/deprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/deprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/undeprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/undeprecate/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/unpublish/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes one version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/unpublish/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes one version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-manage/unpublish-all/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes every version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-manage/unpublish-all/{id}": { + "post": { + "tags": [ + "NpmManageApi" + ], + "summary": "Unpublishes every version, after the password is confirmed.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmManageUnpublishForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmManageViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage": { + "get": { + "tags": [ + "PackageManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage": { + "get": { + "tags": [ + "PackageManageApi" + ], + "summary": "The screen.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/add-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/add-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/remove-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/remove-owner": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes an owner.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageOwnerForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/unlist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Unlists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/unlist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Unlists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/relist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Relists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/relist": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Relists a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes a version as the server is configured to (unlist or permanent).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes a version as the server is configured to (unlist or permanent).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/hard-delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes a version (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes a version (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageHardDeleteForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/hard-delete-all": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes every version and the owners (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete-all": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Permanently deletes every version and the owners (administrators, after the password).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManagePasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/deprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/deprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deprecates a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecateForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/undeprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/undeprecate": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a version's deprecation.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/add-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds a vulnerability to a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/add-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Adds a vulnerability to a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/remove-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a vulnerability from a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/remove-vulnerability": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Removes a vulnerability from a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageRemoveVulnerabilityForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/set-verified": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Marks or unmarks the ID as verified (administrators).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/set-verified": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Marks or unmarks the ID as verified (administrators).", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVerifiedForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/delete-symbols": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes the PDBs recorded for a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/delete-symbols": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Deletes the PDBs recorded for a version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageVersionForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/manage/resolve-report": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Resolves an abuse report.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/manage/resolve-report": { + "post": { + "tags": [ + "PackageManageApi" + ], + "summary": "Resolves an abuse report.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageReportForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageManageScreen" + } + } + } + } + } + } + }, + "/api/ui/profiles/{name}": { + "get": { + "tags": [ + "ProfileApi" + ], + "summary": "The profile named name; 404 when neither a user nor an organization has it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/profiles/{name}": { + "get": { + "tags": [ + "ProfileApi" + ], + "summary": "The profile named name; 404 when neither a user nor an organization has it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfProfileViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication": { + "get": { + "tags": [ + "ReplicationApi" + ], + "summary": "Lists the replications and the form that creates one.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Creates a replication and opens it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}": { + "get": { + "tags": [ + "ReplicationApi" + ], + "summary": "Shows one replication with its log.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/save": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Saves the settings.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/test": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Tests the connection with the typed settings; saves nothing.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/run": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Starts a run.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/resume": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Starts a run that continues the last interrupted or failed one.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/stop": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Asks the running replication to stop; it ends as interrupted and can be resumed.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/replication/{key}/delete": { + "post": { + "tags": [ + "ReplicationApi" + ], + "summary": "Deletes the configuration with its log.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReplicationConfigViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention": { + "get": { + "tags": [ + "RetentionApi" + ], + "summary": "Lists the policies and the form that creates one.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Creates a policy and opens it.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}": { + "get": { + "tags": [ + "RetentionApi" + ], + "summary": "Shows one policy, its last run and report.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/save": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Saves the rules.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/dry-run": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Starts a dry run: the report of what a run would delete.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/run": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Starts a run that deletes.", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/{key}/delete": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Deletes the policy (what it deleted stays deleted).", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionPolicyViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/holds": { + "get": { + "tags": [ + "RetentionApi" + ], + "summary": "Lists the legal holds (of `?repository=` only, when given).", + "parameters": [ + { + "name": "repository", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/holds/add": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Places a hold.", + "parameters": [ + { + "name": "repository", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/retention/holds/remove": { + "post": { + "tags": [ + "RetentionApi" + ], + "summary": "Lifts a hold.", + "parameters": [ + { + "name": "repository", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldRemoval" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldRemoval" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionHoldRemoval" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfRetentionHoldsViewModel" + } + } + } + } + } + } + }, + "/api/ui/scan-artifact": { + "get": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Shows the form (and the stored result) of the version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "name", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Scans the version now (or queues it, for an image) and shows the outcome.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/scan-artifact": { + "get": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Shows the form (and the stored result) of the version.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "name", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "ScanArtifactApi" + ], + "summary": "Scans the version now (or queues it, for an image) and shows the outcome.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanArtifactForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning": { + "get": { + "tags": [ + "ScanningApi" + ], + "summary": "The overview of every repository and project.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanningViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/{name}": { + "get": { + "tags": [ + "ScanningApi" + ], + "summary": "The dashboard of a repository: `?min=` is the lowest severity listed (0 to 3), `?p=` the page.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "min", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/{name}/policy": { + "post": { + "tags": [ + "ScanningApi" + ], + "summary": "Saves the repository policy; empty values remove it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/{name}/scan": { + "post": { + "tags": [ + "ScanningApi" + ], + "summary": "Starts a scan of every artifact of the repository in the background.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanRepositoryViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/projects/{name}": { + "get": { + "tags": [ + "ScanningApi" + ], + "summary": "The scanning policy of a project.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/scanning/projects/{name}/policy": { + "post": { + "tags": [ + "ScanningApi" + ], + "summary": "Saves the project policy; empty values remove it.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyBody" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfScanProjectViewModel" + } + } + } + } + } + } + }, + "/api/ui/session": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Signs in with the user name and password. Answers the tokens, or `twoFactorRequired` with a short-lived `twoFactorTicket` for\r\n`/session/two-factor` or `/session/recovery-code`. 401 for wrong credentials, 403 for a locked, unapproved or unconfirmed account.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignInForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignInForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignInForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/two-factor": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Completes a sign-in with a code of the authenticator app.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionTwoFactorForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionTwoFactorForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionTwoFactorForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/recovery-code": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Completes a sign-in with a recovery code (each works once).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRecoveryCodeForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRecoveryCodeForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRecoveryCodeForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/refresh": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Exchanges the refresh token for a new pair of tokens (the authentication time is kept; the session ends `Accounts:SessionMaxLifetime` after the sign-in).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRefreshForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRefreshForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionRefreshForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/exchange": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Exchanges the 60-second `exchange_token` of an external sign-in's redirect for the tokens (or the two-factor ticket).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionExchangeForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionExchangeForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionExchangeForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/sign-out": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Ends the session: the client forgets its tokens. With `everywhere` the account's security stamp changes and every token and cookie\r\nsession of the account stops working. The caller is the access token, or the refresh token in the body.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignOutForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignOutForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionSignOutForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/session/cookie": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Signs in with the cookie (same origin only; needs the antiforgery token of `GET /api/ui/antiforgery` fetched while signed out, so a cross-site page cannot\r\nsign a visitor in): the rules of `POST /session`, the second factor in the same endpoint (`ticket` with `code` or `recoveryCode`), but the answer holds no tokens.\r\nFetch the antiforgery token again afterwards: it is bound to the signed-in user.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionCookieForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionCookieForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionCookieForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionModel" + } + } + } + } + } + } + }, + "/api/ui/session/cookie/sign-out": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Signs the cookie session out (same origin; send the cookie with the antiforgery header). 401 for anything but a cookie session.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfEmptyScreen" + } + } + } + } + } + } + }, + "/api/ui/session/providers": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "The external sign-in providers a client can offer before anyone is signed in (the sign-in screen's model is interactive-only): their ids, to put in\r\n`/session/external/{id}`, and the names for the buttons. An empty list when none is configured.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfSessionProvidersModel" + } + } + } + } + } + } + }, + "/api/ui/antiforgery": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "The antiforgery request token for a same-origin client that uses the cookie session: send it in the `X-XSRF-TOKEN` header (every method). It\r\nis bound to the signed-in user, so fetch it again after signing in or out. Also sets the antiforgery cookie.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfAntiforgeryTokenModel" + } + } + } + } + } + } + }, + "/api/ui/account/resend-confirmation": { + "post": { + "tags": [ + "SessionApi" + ], + "summary": "Mails a new confirmation link to an account whose address is not confirmed. The answer is the same whether or not an account matches or the mail was allowed\r\n(one per account per ten minutes, and per client); 404 without outgoing mail.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ForgotPasswordForm" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfForgotPasswordViewModel" + } + } + } + } + } + } + }, + "/api/ui/session/external/{provider}": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "Starts the sign-in with the external provider (a browser navigation, not a fetch). The result comes back in the URL fragment of\r\nreturnUrl, which must lie under `Frontend:SpaBasePath` of this server, or be an address of an origin listed in `Cors:AllowedOrigins`.", + "parameters": [ + { + "name": "provider", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { } + } + } + } + } + }, + "/api/ui/session/external-callback": { + "get": { + "tags": [ + "SessionApi" + ], + "summary": "The provider's answer: redirects to returnUrl with, in the URL fragment, `exchange_token` (+ `exchange_expires_at`, `user_name`), to exchange within\r\na minute at `POST /api/ui/session/exchange`, or `notice` (account created, not usable yet) or `error`. No token of the session itself is ever put in a URL.", + "parameters": [ + { + "name": "returnUrl", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { } + } + } + } + } + }, + "/api/ui/packages/{id}/validation": { + "get": { + "tags": [ + "ValidationStatusApi" + ], + "summary": "The submissions of the ID.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/validation": { + "get": { + "tags": [ + "ValidationStatusApi" + ], + "summary": "The submissions of the ID.", + "description": "Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfValidationStatusViewModel" + } + } + } + } + } + } + }, + "/api/ui/admin/api": { + "get": { + "tags": [ + "ApiCatalogApi" + ], + "summary": "The operations of the REST API.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfApiCatalogViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-images": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "The image list with a search box and the client commands.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-images": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "The image list with a search box and the client commands.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/docker-images/{image}": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "One image: tags, manifests, and with `digest` one manifest in full.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "digest", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactType", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/docker-images/{image}": { + "get": { + "tags": [ + "DockerBrowseApi" + ], + "summary": "One image: tags, manifests, and with `digest` one manifest in full.", + "parameters": [ + { + "name": "image", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "digest", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactType", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfDockerImageViewModel" + } + } + } + } + } + } + }, + "/api/ui/home": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "The front page of the repository, or the results when the query asks for something.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/home": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "The front page of the repository, or the results when the query asks for something.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/packages": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "One page of the package list.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages": { + "get": { + "tags": [ + "IndexApi" + ], + "summary": "One page of the package list.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "packageType", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "framework", + "in": "query", + "schema": { + "type": "string", + "default": "any" + } + }, + { + "name": "prerelease", + "in": "query", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "sortBy", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SearchSort" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfIndexScreen" + } + } + } + } + } + } + }, + "/api/ui/privacy": { + "get": { + "tags": [ + "LegalApi" + ], + "summary": "The Privacy Policy.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + } + } + } + }, + "/api/ui/terms": { + "get": { + "tags": [ + "LegalApi" + ], + "summary": "The Terms of Use.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfLegalScreen" + } + } + } + } + } + } + }, + "/api/ui/maven-artifacts": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The artifact list with a search box and the client configuration.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-artifacts": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The artifact list with a search box and the client configuration.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactsViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-artifacts/{group}/{artifact}/{version}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}/{version}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-upload": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The upload form's state.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "Deploys the chosen files under the given coordinates.", + "parameters": [ + { + "name": "groupId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "packaging", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "classifier", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "allOf": [ + { + "type": "object", + "properties": { + "file": { + "$ref": "#/components/schemas/IFormFile" + } + } + }, + { + "type": "object", + "properties": { + "pom": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + ] + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-upload": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "The upload form's state.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "Deploys the chosen files under the given coordinates.", + "parameters": [ + { + "name": "groupId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "artifactId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "packaging", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "classifier", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "allOf": [ + { + "type": "object", + "properties": { + "file": { + "$ref": "#/components/schemas/IFormFile" + } + } + }, + { + "type": "object", + "properties": { + "pom": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + ] + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-packages": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The package list with a search box.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-packages": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The package list with a search box.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "p", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "format": "int32", + "default": 1 + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackagesViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-packages/{id}": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "One package: readme, versions, dist-tags, install commands.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-packages/{id}": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "One package: readme, versions, dist-tags, install commands.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmPackageViewModel" + } + } + } + } + } + } + }, + "/api/ui/npm-upload": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The upload form's state.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "Publishes the chosen tarball with the dist-tag tag (default `latest`).", + "parameters": [ + { + "name": "tag", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/npm-upload": { + "get": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "The upload form's state.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + }, + "post": { + "tags": [ + "NpmBrowseApi" + ], + "summary": "Publishes the chosen tarball with the dist-tag tag (default `latest`).", + "parameters": [ + { + "name": "tag", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfNpmUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/{version}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/{version}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}/{version}/report-abuse": { + "get": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "The empty form.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + }, + "post": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "Records the report.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}/{version}/report-abuse": { + "get": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "The empty form.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + }, + "post": { + "tags": [ + "ReportAbuseApi" + ], + "summary": "Records the report.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfReportAbuseScreen" + } + } + } + } + } + } + }, + "/api/ui/stats": { + "get": { + "tags": [ + "StatisticsApi" + ], + "summary": "The feed's statistics.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/stats": { + "get": { + "tags": [ + "StatisticsApi" + ], + "summary": "The feed's statistics.", + "parameters": [ + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfStatisticsViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload": { + "get": { + "tags": [ + "UploadApi" + ], + "summary": "Step one: the form.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload": { + "get": { + "tags": [ + "UploadApi" + ], + "summary": "Step one: the form.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload/stage": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Stages the chosen file and describes what it contains.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload/stage": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Stages the chosen file and describes what it contains.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "apiKey", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/IFormFile" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload/submit": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Publishes the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload/submit": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Publishes the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/upload/cancel": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Discards the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/upload/cancel": { + "post": { + "tags": [ + "UploadApi" + ], + "summary": "Discards the staged upload.", + "parameters": [ + { + "name": "id", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadTokenRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfUploadViewModel" + } + } + } + } + } + } + }, + "/api/ui/maven-artifacts/{group}/{artifact}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}": { + "get": { + "tags": [ + "MavenBrowseApi" + ], + "summary": "One artifact: versions, files, POM, the dependency to copy.", + "parameters": [ + { + "name": "group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "artifact", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfMavenArtifactViewModel" + } + } + } + } + } + } + }, + "/api/ui/packages/{id}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + }, + "/api/ui/r/{repo}/packages/{id}": { + "get": { + "tags": [ + "PackageApi" + ], + "summary": "Shows the package.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "400": { + "description": "Invalid: the input was refused. The body still holds the screen's model and the errors by field (\"\" = the whole form).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "401": { + "description": "SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "403": { + "description": "Forbidden: the caller may not do this.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + }, + "404": { + "description": "NotFound: no such screen or item, or the caller may not know it exists.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScreenResultOfPackageScreen" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "AbuseForm": { + "required": [ + "key", + "all" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The report's number.", + "format": "int32" + }, + "all": { + "type": "boolean", + "description": "Whether the list to come back to shows the resolved reports too." + } + }, + "description": "A decision on an abuse report." + }, + "AbuseReportSummary": { + "required": [ + "key", + "repository", + "packageId", + "packageVersion", + "reason", + "details", + "reporterEmail", + "created", + "resolved" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repository": { + "type": "string" + }, + "packageId": { + "type": "string", + "nullable": true + }, + "packageVersion": { + "type": "string", + "nullable": true + }, + "reason": { + "type": "string", + "nullable": true + }, + "details": { + "type": "string", + "nullable": true + }, + "reporterEmail": { + "type": "string", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "resolved": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "isResolved": { + "type": "boolean" + } + }, + "description": "An abuse report with the name of its repository." + }, + "AbuseViewModel": { + "type": "object", + "properties": { + "all": { + "type": "boolean", + "description": "Show the resolved reports too." + }, + "isSupported": { + "type": "boolean", + "description": "Whether reports are stored with the configured database." + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AbuseReportSummary" + }, + "description": "The reports, newest first." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + } + }, + "description": "What the abuse reports screen (`/admin/abuse`) shows: the reports of every repository." + }, + "AccessAction": { + "enum": [ + "None", + "Read", + "Annotate", + "Deploy", + "Delete", + "Manage", + "All" + ], + "type": "string", + "description": "What a permission grants. Independent flags: AccessAction.Deploy does not imply AccessAction.Read, as in\r\nArtifactory. Package ownership (IPackageAuthorizationService) is a second, separate requirement\r\nfor the actions that change an existing package ID." + }, + "AccessAuditEntry": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "created": { + "type": "string", + "format": "date-time" + }, + "actor": { + "type": "string", + "description": "The user name that made the change; null for the server itself.", + "nullable": true + }, + "action": { + "type": "string", + "description": "What happened, such as `group.create` or `grant.set`.", + "nullable": true + }, + "subject": { + "type": "string", + "description": "What it happened to (a group, target or repository name).", + "nullable": true + }, + "details": { + "type": "string", + "description": "JSON with the details (never credentials).", + "nullable": true + } + }, + "description": "One change to the access model." + }, + "AccessExplanation": { + "required": [ + "actions", + "override", + "reasons" + ], + "type": "object", + "properties": { + "actions": { + "$ref": "#/components/schemas/AccessAction" + }, + "override": { + "type": "string", + "description": "A rule that grants everything or bypasses the model (administrator, global API key, no\r\n access model), instead of Reasons; null when the grants decide.", + "nullable": true + }, + "reasons": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccessReason" + }, + "description": "The grants and project roles that apply to the caller." + } + }, + "description": "What a caller may do in a repository, and why (Task<AccessExplanation> IAccessEvaluator.ExplainAsync(BaGetPrincipal? principal, RepositoryInfo repository, string? packageId, CancellationToken cancellationToken))." + }, + "AccessReason": { + "required": [ + "source", + "principalType", + "principalId", + "principal", + "granted", + "effective", + "packages", + "note" + ], + "type": "object", + "properties": { + "source": { + "type": "string", + "description": "Where it comes from, such as `Permission target 'Anyone reads every repository'`." + }, + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string", + "description": "The principal's id (user id, group or organization key)." + }, + "principal": { + "type": "string", + "description": "The principal in words (a user name, `group Developers`, `organization Contoso`)." + }, + "granted": { + "$ref": "#/components/schemas/AccessAction" + }, + "effective": { + "$ref": "#/components/schemas/AccessAction" + }, + "packages": { + "type": "string", + "description": "The package filter of the target, such as `Contoso.* except Contoso.Internal.*`; null for all.", + "nullable": true + }, + "note": { + "type": "string", + "description": "Why AccessAction AccessReason.Effective differs from AccessAction AccessReason.Granted, if it does.", + "nullable": true + } + }, + "description": "One grant or project role behind an access decision, for the admin pages that explain it." + }, + "AccessUnavailableViewModel": { + "required": [ + "reason" + ], + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "Why the access screens are not available." + } + }, + "description": "What the \"access control unavailable\" screen (`/admin/access-unavailable`) says: why, as the JSON carries it (the page has fixed text)." + }, + "AccountAccessViewModel": { + "type": "object", + "properties": { + "package": { + "type": "string", + "description": "A package ID to evaluate the grants for; empty means the repository as a whole.", + "nullable": true + }, + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryAccessRow" + }, + "description": "The repositories where the user holds some action." + }, + "administeredProjects": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The projects the user administers." + }, + "modelAvailable": { + "type": "boolean", + "description": "Whether the configured database has an access model at all." + } + }, + "description": "The \"My access\" screen: the signed-in user's own effective permissions." + }, + "AccountApiKey": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The key's id (the number the revoke button posts).", + "format": "int32" + }, + "description": { + "type": "string", + "description": "What the key is for.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "What the key may do." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs the key applies to.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When it was created.", + "format": "date-time" + }, + "expires": { + "type": "string", + "description": "When it expires; null = never.", + "format": "date-time", + "nullable": true + } + }, + "description": "One API key as the screen lists it: never the key itself or its hash (only the creation response shows a new key, once)." + }, + "AccountOrganization": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization's name.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the current user administers it." + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccountOrganizationMember" + }, + "description": "The members, by user name.", + "nullable": true + } + }, + "description": "One organization with its members." + }, + "AccountOrganizationMember": { + "required": [ + "userName", + "isAdmin" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The member's user name." + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the member administers the organization." + } + }, + "description": "One member of an organization (a flat record, so the screen's JSON names its fields)." + }, + "AccountPackagesViewModel": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryPackages" + }, + "description": "The owned packages of each repository that has any, `default` first." + }, + "isEmpty": { + "type": "boolean", + "description": "Whether the user owns nothing in any repository." + }, + "showRepositoryNames": { + "type": "boolean", + "description": "Whether the list needs repository headings: more than the default repository holds packages of the user." + } + }, + "description": "The \"My packages\" screen: the packages the user owns in each repository." + }, + "AddOrganizationMemberForm": { + "type": "object", + "properties": { + "organization": { + "type": "string", + "description": "The organization.", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The user to add.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the new member administers the organization." + } + }, + "description": "What the \"add a member\" form posts." + }, + "AdminDeletionPreview": { + "required": [ + "apiKeys", + "directPackageIds", + "soleOwnedPackages", + "organizations" + ], + "type": "object", + "properties": { + "apiKeys": { + "type": "integer", + "description": "How many API keys go.", + "format": "int32" + }, + "directPackageIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Package IDs the user owns directly." + }, + "soleOwnedPackages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SoleOwnedPackage" + }, + "description": "The subset nobody else owns, in every repository." + }, + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrganizationOutcome" + }, + "description": "What happens to each organization the user belongs to." + } + }, + "description": "What deleting a user as an administrator would remove or change." + }, + "AdminJobState": { + "enum": [ + "Running", + "Succeeded", + "Failed" + ], + "type": "string" + }, + "AdminJobStatus": { + "type": "object", + "properties": { + "operation": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/AdminJobState" + }, + "actor": { + "type": "string", + "nullable": true + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "message": { + "type": "string", + "description": "The result on success, the exception type and message on failure.", + "nullable": true + } + }, + "description": "The last run of an operation on a repository. In memory: a restart forgets it." + }, + "AdminOrganizationsViewModel": { + "type": "object", + "properties": { + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrganizationSummary" + }, + "description": "The organizations, by name." + } + }, + "description": "What the organizations screen (`/admin/organizations`) lists: every organization with its members and packages." + }, + "AdminPackageRow": { + "required": [ + "package", + "owners" + ], + "type": "object", + "properties": { + "package": { + "$ref": "#/components/schemas/OwnedPackage" + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of its owners; empty for an ownerless ID." + }, + "repositoryName": { + "type": "string", + "description": "The repository the ID is in; ownership and versions are per repository.", + "default": "default" + } + }, + "description": "A package ID as the administrator pages list it." + }, + "AdminPackagesViewModel": { + "type": "object", + "properties": { + "pageNumber": { + "type": "integer", + "description": "One-based page number (the `p` query value).", + "format": "int32" + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminPackageRow" + }, + "description": "The ownerless IDs on this page." + }, + "showRepository": { + "type": "boolean", + "description": "Whether a Repository column is worth showing: some listed ID is outside the default repository." + }, + "pageCount": { + "type": "integer", + "description": "The number of pages.", + "format": "int32" + } + }, + "description": "What the ownerless packages screen (`/admin/packages`) shows: the package IDs nobody owns, in every repository." + }, + "AdminSettingsViewModel": { + "type": "object", + "properties": { + "sectionList": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SettingsSection" + }, + "description": "The same sections as IReadOnlyList<IGrouping<string, SettingState>> AdminSettingsViewModel.Sections, each with its key and DOM id, as the JSON carries them.", + "nullable": true + }, + "overridesPath": { + "type": "string", + "description": "The file the settings are saved to.", + "nullable": true + }, + "pendingRestart": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The keys changed since startup that only apply after a restart." + }, + "errors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the last save was refused." + }, + "errorSection": { + "type": "string", + "description": "The section the IReadOnlyList<string> AdminSettingsViewModel.Errors belong to.", + "nullable": true + }, + "logLevels": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LogLevelOverride" + }, + "description": "The per-source log levels (`Serilog:MinimumLevel:Override`) shown under the Serilog section." + }, + "logLevelNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The level names offered for a source.", + "nullable": true + }, + "signInProviders": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SignInProviderView" + }, + "description": "The named OpenID Connect providers (`Accounts:OpenIdConnectProviders`) shown in the \"Sign-in providers\" panel of the Accounts section. No secret is carried." + }, + "loadError": { + "type": "string", + "description": "Why the overrides file could not be read, or null.", + "nullable": true + }, + "telemetrySignals": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TelemetrySignalReport" + }, + "description": "The state of each telemetry signal for the Telemetry section, or null when the host exports no telemetry.", + "nullable": true + }, + "hostExportsTelemetry": { + "type": "boolean", + "description": "True when this host exports telemetry (registers ITelemetryDiagnostics). When false the Telemetry\r\nsection stays editable (the settings file may be shared with a host that does export) but a note says it has no effect here." + }, + "telemetryTest": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TelemetryTestOutcome" + } + ] + }, + "canCopyDatabase": { + "type": "boolean", + "description": "Whether the running database is relational, so a change of database can copy the data (the \"Copy all data\" option of the\r\nDatabase section)." + }, + "copyTargetTypes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The `Database:Type` values a copy can target; the option is hidden for any other type." + }, + "copyStatus": { + "$ref": "#/components/schemas/DatabaseCopyStatus" + }, + "selectedId": { + "type": "string", + "description": "The DOM id (slug) of the section shown; every other section is rendered `hidden`. Chosen by the workflow: the failed\r\nsection, else the Telemetry section after \"Test connection\", else the `?section=` value, else the first section. The URL\r\nfragment is only known to the browser, so the page's script applies it on load unless bool AdminSettingsViewModel.SelectionLocked." + }, + "selectionLocked": { + "type": "boolean", + "description": "True when the server picked the section for a reason the URL fragment must not override (a failed save, a connection test)." + }, + "message": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the server settings screen (`/admin/settings`) shows: every registered setting by section and the state of the last save." + }, + "AntiforgeryTokenModel": { + "type": "object", + "properties": { + "headerName": { + "type": "string", + "description": "The header to send the token in (`X-XSRF-TOKEN`).", + "nullable": true + }, + "requestToken": { + "type": "string", + "description": "The request token. It is bound to the signed-in user: ask again after signing in or out.", + "nullable": true + } + }, + "description": "What `GET /api/ui/antiforgery` answers: the request token to send with a cookie session." + }, + "ApiCatalogViewModel": { + "required": [ + "endpoints", + "apiBase", + "confirmHeader" + ], + "type": "object", + "properties": { + "endpoints": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ApiEndpointSummary" + }, + "description": "Every operation, ordered by path." + }, + "apiBase": { + "type": "string", + "description": "The address of the API on this server." + }, + "confirmHeader": { + "type": "string", + "description": "The header that carries the password of the owner." + }, + "openApiUrl": { + "type": "string", + "description": "Where the OpenAPI document is.", + "nullable": true + } + }, + "description": "What the REST API page shows (also the model of its JSON twin)." + }, + "ApiEndpointSummary": { + "required": [ + "method", + "path", + "summary", + "uiScreen", + "confirm" + ], + "type": "object", + "properties": { + "method": { + "type": "string", + "description": "The HTTP method." + }, + "path": { + "type": "string", + "description": "The path template (`/api/v1/groups/{name}`)." + }, + "summary": { + "type": "string", + "description": "What the operation does." + }, + "uiScreen": { + "$ref": "#/components/schemas/ScreenRef" + }, + "confirm": { + "type": "boolean", + "description": "Whether the owner's password is asked (the confirmation header)." + } + }, + "description": "One operation of the REST API as the page (and the JSON twin) lists it: flat, with no reflection objects." + }, + "ApiKeyForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it.", + "nullable": true + }, + "description": { + "maxLength": 256, + "minLength": 0, + "type": "string", + "description": "What the key is for.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The scopes of the new key." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs the key applies to." + }, + "expiresInDays": { + "maximum": 3650, + "minimum": 1, + "type": "integer", + "description": "Days until the key expires; none = never.", + "format": "int32", + "nullable": true + }, + "repositoryKeys": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "description": "The keys of the repositories the new key is limited to; none (the default) means every repository." + } + }, + "description": "What the new-key form posts (and the body of `POST /api/ui/account/apikeys`)." + }, + "ApiKeysViewModel": { + "type": "object", + "properties": { + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories offered in the picker: those the user can read. Empty (picker hidden) where the server holds\r\nthe default repository only." + }, + "keys": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccountApiKey" + }, + "description": "The user's keys." + }, + "keyRepositories": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "The names of the repositories each key (by key id) is limited to." + }, + "createdKey": { + "type": "string", + "description": "The key just created. Shown once: only its hash is kept.", + "nullable": true + }, + "allScopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The scopes the new-key form offers: the package scopes, plus string ApiKeyScopes.Admin (the REST API under\r\n`/api/v1`) for an administrator." + }, + "password": { + "type": "string", + "description": "The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it.", + "nullable": true + }, + "description": { + "maxLength": 256, + "minLength": 0, + "type": "string", + "description": "What the key is for.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The scopes of the new key." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs the key applies to." + }, + "expiresInDays": { + "maximum": 3650, + "minimum": 1, + "type": "integer", + "description": "Days until the key expires; none = never.", + "format": "int32", + "nullable": true + }, + "repositoryKeys": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "description": "The keys of the repositories the new key is limited to; none (the default) means every repository." + } + }, + "description": "The API keys screen: the new-key form's fields it repeats and the user's keys. A request binds ApiKeyForm, never this type,\r\nso the outputs cannot be set from outside." + }, + "AuditViewModel": { + "type": "object", + "properties": { + "actorFilter": { + "type": "string", + "description": "The user name that made the change.", + "nullable": true + }, + "subject": { + "type": "string", + "description": "Part of what the change was done to (a group, target, project or repository name).", + "nullable": true + }, + "from": { + "type": "string", + "description": "First day, `yyyy-MM-dd`.", + "nullable": true + }, + "to": { + "type": "string", + "description": "Last day, `yyyy-MM-dd`.", + "nullable": true + }, + "entries": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccessAuditEntry" + }, + "description": "The matching entries." + }, + "filterError": { + "type": "string", + "description": "Why the filter was not applied, if a date could not be read.", + "nullable": true + } + }, + "description": "What the access audit screen (`/admin/audit`) shows: the filter and the matching entries." + }, + "ChangeEmailForm": { + "type": "object", + "properties": { + "newEmail": { + "type": "string", + "description": "The new address.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password, asked again (an account without one needs a fresh provider sign-in instead).", + "nullable": true + } + }, + "description": "What the change-email form posts." + }, + "ChangePasswordForm": { + "type": "object", + "properties": { + "currentPassword": { + "type": "string", + "description": "The current password (an account without one sets its first after signing in again with its provider).", + "nullable": true + }, + "newPassword": { + "type": "string", + "description": "The new password.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The new password again.", + "nullable": true + } + }, + "description": "What the change-password form posts (the body of `POST /api/ui/account/settings/change-password`)." + }, + "ClusterStatus": { + "required": [ + "enabled", + "thisNode", + "backend", + "backendReachable", + "nodes", + "leases", + "gateReason", + "readiness" + ], + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether this node is in a cluster." + }, + "thisNode": { + "type": "string", + "description": "This node's name." + }, + "backend": { + "type": "string", + "description": "The store, without credentials.", + "nullable": true + }, + "backendReachable": { + "type": "boolean", + "description": "Whether the store answered." + }, + "nodes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NodeInfo" + }, + "description": "The nodes with a recent heartbeat, this one included." + }, + "leases": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LeaseInfo" + }, + "description": "The job leases held now." + }, + "gateReason": { + "type": "string", + "description": "Why the cluster is read-only, or null.", + "nullable": true + }, + "readiness": { + "$ref": "#/components/schemas/ReadinessReport" + } + }, + "description": "What the cluster page shows." + }, + "ClusterViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ClusterStatus" + } + }, + "description": "What the cluster screen (`/admin/cluster`) shows: nodes, leases, shared state and health." + }, + "ConfirmEmailViewModel": { + "type": "object", + "properties": { + "succeeded": { + "type": "boolean", + "description": "Whether the link was valid." + }, + "emailChanged": { + "type": "boolean", + "description": "Whether the link changed the address of an existing account." + }, + "pendingApproval": { + "type": "boolean", + "description": "Whether the account still waits for an administrator (`Accounts:RequireApproval`) after the confirmation." + } + }, + "description": "The result of following the link of a confirmation email." + }, + "ContactOwnersForm": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "The message to send to the owners.", + "nullable": true + }, + "copyToSelf": { + "type": "boolean", + "description": "Whether the sender also gets a copy." + } + }, + "description": "The fields of the contact-owners form as the screen receives them (a page's form post or the JSON body of the twin). It carries no\r\nvalidation attributes: the use case validates by itself (ContactOwnersViewModel holds the rules), so a page's model\r\nbinding does not report the same error a second time." + }, + "ContactOwnersViewModel": { + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "maxLength": 4000, + "minLength": 0, + "type": "string", + "description": "The message to send to the owners.", + "nullable": true + }, + "copyToSelf": { + "type": "boolean", + "description": "Whether the sender also gets a copy." + }, + "packageId": { + "type": "string", + "description": "The package ID as stored, which is the only text that reaches the subject.", + "nullable": true + }, + "sent": { + "type": "boolean", + "description": "Whether the message was sent." + }, + "error": { + "type": "string", + "description": "Why the message was not sent, or null.", + "nullable": true + }, + "senderHasEmail": { + "type": "boolean", + "description": "Replies come to the sender's address, so there must be one, and it must be confirmed: an unconfirmed address could be anyone's." + } + }, + "description": "The contact-owners screen (`/packages/{id}/contact-owners`): the two form fields (string? ContactOwnersViewModel.Message,\r\nbool ContactOwnersViewModel.CopyToSelf, bound on POST) and what the screen shows; filled by the screen's workflow." + }, + "CreateOrganizationForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization's name.", + "nullable": true + } + }, + "description": "What the \"create an organization\" form posts." + }, + "DatabaseCopyPhase": { + "enum": [ + "Idle", + "Queued", + "Checking", + "Migrating", + "Copying", + "Verifying", + "SavingSettings", + "RollingBack", + "Succeeded", + "Failed" + ], + "type": "string", + "description": "The stage a database copy is in." + }, + "DatabaseCopyStatus": { + "required": [ + "phase", + "table", + "tableRowsCopied", + "tableRowsTotal", + "tablesDone", + "tablesTotal", + "rowsCopied", + "rowsTotal", + "errors", + "message" + ], + "type": "object", + "properties": { + "phase": { + "$ref": "#/components/schemas/DatabaseCopyPhase" + }, + "table": { + "type": "string", + "description": "The table being copied, or null.", + "nullable": true + }, + "tableRowsCopied": { + "type": "integer", + "description": "Rows of Table copied so far.", + "format": "int64" + }, + "tableRowsTotal": { + "type": "integer", + "description": "Rows of Table in the source.", + "format": "int64" + }, + "tablesDone": { + "type": "integer", + "description": "Tables completed.", + "format": "int32" + }, + "tablesTotal": { + "type": "integer", + "description": "Tables to copy.", + "format": "int32" + }, + "rowsCopied": { + "type": "integer", + "description": "Rows copied over all tables.", + "format": "int64" + }, + "rowsTotal": { + "type": "integer", + "description": "Rows to copy over all tables.", + "format": "int64" + }, + "errors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the copy was refused or failed." + }, + "message": { + "type": "string", + "description": "A one-line summary of the current state.", + "nullable": true + }, + "isActive": { + "type": "boolean", + "description": "A copy is queued or running." + }, + "isFinished": { + "type": "boolean", + "description": "The copy ended, either way." + }, + "restartRequired": { + "type": "boolean", + "description": "The copy succeeded: the settings are saved and the process must restart to use them." + } + }, + "description": "A snapshot of the copy's progress, as shown by the Settings page. Holds no connection string." + }, + "DatabaseCopyStatusView": { + "required": [ + "phase", + "active", + "finished", + "succeeded", + "restartRequired", + "table", + "tableRowsCopied", + "tableRowsTotal", + "tablesDone", + "tablesTotal", + "rowsCopied", + "rowsTotal", + "message", + "errors" + ], + "type": "object", + "properties": { + "phase": { + "type": "string", + "description": "The stage, by name." + }, + "active": { + "type": "boolean", + "description": "A copy is queued or running." + }, + "finished": { + "type": "boolean", + "description": "The copy ended, either way." + }, + "succeeded": { + "type": "boolean", + "description": "The copy succeeded." + }, + "restartRequired": { + "type": "boolean", + "description": "The settings are saved and the process must restart to use them." + }, + "table": { + "type": "string", + "description": "The table being copied, or null.", + "nullable": true + }, + "tableRowsCopied": { + "type": "integer", + "description": "Rows of the table copied so far.", + "format": "int64" + }, + "tableRowsTotal": { + "type": "integer", + "description": "Rows of the table in the source.", + "format": "int64" + }, + "tablesDone": { + "type": "integer", + "description": "Tables completed.", + "format": "int32" + }, + "tablesTotal": { + "type": "integer", + "description": "Tables to copy.", + "format": "int32" + }, + "rowsCopied": { + "type": "integer", + "description": "Rows copied over all tables.", + "format": "int64" + }, + "rowsTotal": { + "type": "integer", + "description": "Rows to copy over all tables.", + "format": "int64" + }, + "message": { + "type": "string", + "description": "A one-line summary of the current state.", + "nullable": true + }, + "errors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the copy was refused or failed." + } + }, + "description": "The progress of the database copy as the Settings page polls it (`?handler=CopyStatus`): the properties are those the page's script reads\r\n(`phase` as the phase name, `active`, `finished`, `succeeded`, `restartRequired` ...). Holds no connection string." + }, + "DeleteUserViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The user to delete (route).", + "nullable": true + }, + "soleOwned": { + "type": "string", + "description": "\"keep\" (default) or \"delete\": what to do with the IDs only this user owns." + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AdminDeletionPreview" + } + ] + }, + "lastAdministrator": { + "type": "boolean", + "description": "Whether the user is the server's only administrator." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Read-only mode: the account may go, but package files are not deleted." + }, + "error": { + "type": "string", + "description": "Why the deletion was refused.", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the delete-user screen (`/admin/users/{name}/delete`) shows: what the deletion would remove or change." + }, + "DeletionBlockers": { + "required": [ + "lastOwnerPackageIds", + "organizations" + ], + "type": "object", + "properties": { + "lastOwnerPackageIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Package IDs the user is the only direct owner of, in any repository (ownership is per repository, so the same\r\nID in two repositories counts once each). Same rule as\r\nTask<OwnerChangeResult> PackageOwnershipService.RemoveOwnerAsync(string? packageId, string ownerName, CancellationToken cancellationToken): an owned ID keeps an owner." + }, + "organizations": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Organizations the user is the last administrator of while others still belong to it, or\r\nthat own packages and so cannot be left without anyone to run them. Same rule as\r\nTask<bool> PackageOwnershipService.RemoveMemberAsync(string organizationName, string userId, CancellationToken cancellationToken)." + }, + "lastAdministrator": { + "type": "boolean", + "description": "The user is the server's only administrator, so deleting them would leave nobody able to\r\nchange the settings.", + "default": false + }, + "lastOwnerPackages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SoleOwnedPackage" + }, + "description": "Per-repository detail of IReadOnlyList<string?> DeletionBlockers.LastOwnerPackageIds; never null.", + "nullable": true + }, + "any": { + "type": "boolean", + "description": "Whether anything blocks the deletion." + } + }, + "description": "What stops a user from deleting their account." + }, + "DependencyGroupModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "nullable": true + }, + "dependencies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DependencyModel" + }, + "nullable": true + } + } + }, + "DependencyModel": { + "type": "object", + "properties": { + "packageId": { + "type": "string", + "nullable": true + }, + "versionSpec": { + "type": "string", + "nullable": true + } + } + }, + "DockerImagesViewModel": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The page, from 1.", + "format": "int32" + }, + "result": { + "$ref": "#/components/schemas/OciImagePage" + }, + "host": { + "type": "string", + "description": "The registry host as a Docker client writes it (`host:port`)." + }, + "isHttp": { + "type": "boolean", + "description": "Whether the registry is reached over plain http (the Docker daemon then needs it as an insecure registry)." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name, the first path segment of every image reference." + }, + "isRemote": { + "type": "boolean", + "description": "Whether the repository caches an upstream registry (it takes no pushes)." + }, + "isVirtual": { + "type": "boolean", + "description": "Whether the repository merges other repositories (a push goes to its deploy repository)." + }, + "hasNext": { + "type": "boolean", + "description": "Whether another page follows." + }, + "commandTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + } + }, + "description": "What the Docker front page (`/docker-images`) shows: this page of images and the commands for the client." + }, + "DockerImageViewModel": { + "type": "object", + "properties": { + "image": { + "type": "string", + "description": "The image name from the address (it may contain slashes).", + "nullable": true + }, + "digest": { + "type": "string", + "description": "The manifest to show in full (`?digest=`), or null for the overview.", + "nullable": true + }, + "artifactType": { + "type": "string", + "description": "Narrows the referrers to one artifact type (`?artifactType=`); empty keeps them all.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with: 200, or 404 when the image or manifest does not exist (the page then explains).", + "format": "int32" + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciImageInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciManifestDetail" + } + ] + }, + "referrers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciDescriptor" + }, + "description": "The manifests whose `subject` is the chosen manifest (signatures, SBOMs). Empty without a selection." + }, + "host": { + "type": "string", + "description": "The registry host as a Docker client writes it." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name." + }, + "isRemote": { + "type": "boolean", + "description": "Whether the repository caches an upstream registry (it takes no pushes)." + }, + "canManage": { + "type": "boolean", + "description": "Whether the signed-in user holds Delete on the image, so the manage page is offered." + }, + "pullTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + }, + "registryUrl": { + "type": "string", + "description": "The address of the registry API for the image (what a script calls)." + } + }, + "description": "What the page of one Docker image (`/docker-images/{image}`, `?digest=` for a manifest) shows." + }, + "DockerManageForm": { + "type": "object", + "properties": { + "tag": { + "type": "string", + "description": "The tag to delete (`DeleteTag`).", + "nullable": true + }, + "digest": { + "type": "string", + "description": "The manifest digest to delete (`DeleteManifest`).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of the Docker management handlers; every one asks for the caller's password." + }, + "DockerManageViewModel": { + "type": "object", + "properties": { + "image": { + "type": "string", + "description": "The image name from the address (it may contain slashes).", + "nullable": true + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciImageInfo" + } + ] + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? DockerManageViewModel.Message reports a refusal." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the user has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + } + }, + "description": "What the Docker image management screen (`/docker-manage/{**image}`) shows; filled by the screen's workflow." + }, + "EffectiveScanPolicy": { + "required": [ + "values", + "from", + "name" + ], + "type": "object", + "properties": { + "values": { + "$ref": "#/components/schemas/ScanPolicyValues" + }, + "from": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicyScope" + } + ] + }, + "name": { + "type": "string", + "description": "The repository or project name it is stored for, or null.", + "nullable": true + } + }, + "description": "The policy in force for a repository: its own, else its project's, else none." + }, + "EmptyScreen": { + "type": "object", + "description": "The model of a screen that shows nothing but itself (the sign-out button), or of an action that only continues elsewhere." + }, + "ExternalLoginStatus": { + "required": [ + "id", + "displayName", + "linked" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id." + }, + "displayName": { + "type": "string", + "description": "The provider's name." + }, + "linked": { + "type": "boolean", + "description": "Whether the account has a linked login at this provider." + } + }, + "description": "A configured external provider as the account settings list it for one user." + }, + "ExternalProviderInfo": { + "required": [ + "id", + "displayName" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id: the value a form or `/api/ui/session/external/{provider}` names it by." + }, + "displayName": { + "type": "string", + "description": "The name on the button." + } + }, + "description": "An external sign-in provider as a screen offers it (one button per provider)." + }, + "FeedStatistics": { + "type": "object", + "properties": { + "packageIds": { + "type": "integer", + "format": "int32" + }, + "packageVersions": { + "type": "integer", + "format": "int32" + }, + "downloads": { + "type": "integer", + "format": "int64" + }, + "topPackages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDownloads" + }, + "description": "The most downloaded package IDs, all versions together.", + "nullable": true + }, + "recentVersions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDownloads" + }, + "description": "The most recently published versions.", + "nullable": true + } + } + }, + "ForgotPasswordForm": { + "required": [ + "identifier" + ], + "type": "object", + "properties": { + "identifier": { + "type": "string", + "description": "The user name or email address.", + "nullable": true + } + }, + "description": "What the \"forgot password\" form posts." + }, + "ForgotPasswordViewModel": { + "required": [ + "identifier" + ], + "type": "object", + "properties": { + "sent": { + "type": "boolean", + "description": "Whether the request was answered (always the same answer, see the use case)." + }, + "identifier": { + "type": "string", + "description": "The user name or email address.", + "nullable": true + } + }, + "description": "The \"forgot password\" screen. A request binds ForgotPasswordForm, never this type." + }, + "FormatCreateField": { + "required": [ + "name", + "label" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The key in the dictionary string? IFormatModule.CreateSettings(IReadOnlyDictionary<string, string?> fields) receives." + }, + "label": { + "type": "string", + "description": "The visible label." + }, + "help": { + "type": "string", + "description": "One line of explanation, or null.", + "nullable": true + }, + "required": { + "type": "boolean", + "description": "Whether an empty value is refused by the form.", + "default": false + }, + "options": { + "type": "array", + "items": { + "type": "string" + }, + "description": "For a choice: the allowed values; null for free text.", + "nullable": true + } + }, + "description": "An input of the create form a format contributes." + }, + "FormatLink": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "A stable identifier (`browse`, `upload`); becomes the CSS class `repository-{id}`.", + "nullable": true + }, + "label": { + "type": "string", + "description": "The visible text.", + "nullable": true + }, + "controller": { + "type": "string", + "description": "The MVC controller (without the suffix) of the screen it opens; null for a path link.", + "nullable": true + }, + "action": { + "type": "string", + "description": "The action of that controller that shows the screen; null for a path link.", + "nullable": true + }, + "path": { + "type": "string", + "description": "A path under the repository base; null for a screen link.", + "nullable": true + }, + "needsUploads": { + "type": "boolean", + "description": "Shown only for repositories that take uploads (not a remote one, nor a virtual one without a deploy repository)." + } + }, + "description": "A link a format contributes to the administration of a repository: to one of its screens or to a path under its base." + }, + "FormatRow": { + "required": [ + "module", + "repositories", + "capabilities" + ], + "type": "object", + "properties": { + "module": { + "$ref": "#/components/schemas/IFormatModule" + }, + "repositories": { + "type": "integer", + "description": "How many repositories use it.", + "format": "int32" + }, + "capabilities": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The capabilities its services implement." + } + }, + "description": "One format with what it offers, as the formats screen lists it." + }, + "FormatsViewModel": { + "type": "object", + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatRow" + }, + "description": "The formats." + } + }, + "description": "What the formats screen (`/admin/formats`) lists: the package formats this server can host." + }, + "FrameworkGroup": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The family (.NET, .NET Core, .NET Standard, .NET Framework, Other).", + "nullable": true + }, + "declared": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Frameworks the package ships assets for.", + "nullable": true + }, + "computed": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Frameworks the package works with without declaring them.", + "nullable": true + } + }, + "description": "The frameworks of one package, as the package page's Frameworks tab shows them." + }, + "GrantForm": { + "required": [ + "principalType", + "principalName", + "actions", + "password" + ], + "type": "object", + "properties": { + "principalType": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalType" + } + ] + }, + "principalName": { + "type": "string", + "description": "The principal's name.", + "nullable": true + }, + "actions": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The ticked AccessAction names (`Read`, `Annotate`, `Deploy`, `Delete`, `Manage`); none removes the grant.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Giving a principal the ticked actions through a permission target, replacing an earlier grant to it." + }, + "GrantInfo": { + "required": [ + "target", + "principalType", + "principalId", + "principal", + "actions" + ], + "type": "object", + "properties": { + "target": { + "type": "string" + }, + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string" + }, + "principal": { + "type": "string" + }, + "actions": { + "$ref": "#/components/schemas/AccessAction" + } + }, + "description": "A grant, with the target and principal in words." + }, + "GroupCreation": { + "required": [ + "name", + "description" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The group's name.", + "nullable": true + }, + "description": { + "type": "string", + "description": "What the group is for, or null.", + "nullable": true + } + }, + "description": "A new group." + }, + "GroupDetails": { + "required": [ + "group", + "members", + "grants" + ], + "type": "object", + "properties": { + "group": { + "$ref": "#/components/schemas/GroupSummary" + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupMemberInfo" + } + }, + "grants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GrantInfo" + } + } + }, + "description": "A group with its members and the grants naming it." + }, + "GroupDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The group name (route).", + "nullable": true + }, + "q": { + "type": "string", + "description": "User-name search for the member picker (contains).", + "nullable": true + }, + "group": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/GroupDetails" + } + ] + }, + "found": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupMemberInfo" + }, + "description": "The users found by string? GroupDetailViewModel.Q, not yet members." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the group screen (`/admin/groups/{name}`) shows: the group, its members and the member search." + }, + "GroupMemberChange": { + "required": [ + "userId", + "password" + ], + "type": "object", + "properties": { + "userId": { + "type": "string", + "description": "The user's id (string GroupMemberInfo.UserId).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Adding a user to a group or removing them." + }, + "GroupMemberInfo": { + "required": [ + "userId", + "userName" + ], + "type": "object", + "properties": { + "userId": { + "type": "string" + }, + "userName": { + "type": "string" + } + }, + "description": "A member of a group." + }, + "GroupRename": { + "required": [ + "newName" + ], + "type": "object", + "properties": { + "newName": { + "type": "string", + "description": "The new name.", + "nullable": true + } + }, + "description": "Renaming a group." + }, + "GroupSummary": { + "required": [ + "key", + "name", + "description", + "isBuiltIn", + "memberCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string", + "nullable": true + }, + "isBuiltIn": { + "type": "boolean" + }, + "memberCount": { + "type": "integer", + "format": "int32" + } + }, + "description": "A group as the admin pages list it." + }, + "GroupsViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new group name.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The new group description.", + "nullable": true + }, + "groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupSummary" + }, + "description": "The groups." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the groups screen (`/admin/groups`) shows: the groups and the new-group form." + }, + "HealthProbe": { + "required": [ + "name", + "healthy", + "detail" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "`database`, `storage` or `cluster`." + }, + "healthy": { + "type": "boolean", + "description": "Whether it answered." + }, + "detail": { + "type": "string", + "description": "A short, credential-free note (the exception type when it failed).", + "nullable": true + }, + "informational": { + "type": "boolean", + "description": "The probe is reported but a failure does not make the node unready (the shared store: a node keeps serving without it).", + "default": false + } + }, + "description": "One probe of the readiness check." + }, + "HtmlString": { + "required": [ + "value" + ], + "type": "object", + "properties": { + "value": { + "type": "string", + "nullable": true + } + } + }, + "IAdminOperation": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The stable id used in forms and status (`catalog-rebuild`).", + "nullable": true + }, + "title": { + "type": "string", + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "requiresConfirmation": { + "type": "boolean", + "description": "Whether the operation deletes data, so the Operations page asks the administrator's password again before it starts it (as the\r\nother destructive pages do). Default: no." + } + }, + "description": "A long-running maintenance operation an administrator can start from the web UI for one repository\r\n(what the `catalog rebuild` and `import downloads` commands do). Registered as a singleton." + }, + "IFormatModule": { + "type": "object", + "properties": { + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "displayName": { + "type": "string", + "description": "The name shown to people: `NuGet`, `npm`.", + "nullable": true + }, + "routePrefix": { + "type": "string", + "description": "The path segment (or segments, without slashes at the ends) every route of the format starts with, after the repository\r\nbase: `npm`. Empty for NuGet, whose routes were there first.", + "nullable": true + }, + "feedPath": { + "type": "string", + "description": "The address a client is configured with, relative to the repository base (`r/{repo}/`, or the root for the default\r\nrepository): `v3/index.json` for NuGet, `npm/` for npm.", + "nullable": true + }, + "creatableKinds": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "description": "The kinds of repository that can be created through IRepositoryService without a dedicated administration\r\nservice (a virtual repository is created with its members by IVirtualRepositoryAdministration and is not\r\nlisted here). Kinds not listed are refused for this format.", + "nullable": true + }, + "supportsVirtual": { + "type": "boolean", + "description": "Whether virtual repositories of this format exist (Task<RepositoryInfo> IVirtualRepositoryAdministration.CreateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null, bool anonymousRead = true, RepositoryFormat format = RepositoryFormat.NuGet)): the format's\r\nreads then merge the members, and a write goes to the deploy repository. False for a format that has not implemented the\r\nmerge." + }, + "requiresStreamingStorage": { + "type": "boolean", + "description": "Whether the format stores blobs too large to buffer (Docker layers) and so needs a store that is an\r\nIStreamingStorageService. A repository of such a format is refused at creation when the configured store\r\ncannot stream (IStreamingStorageService StreamingStorage.Require(IStorageService? storage, string purpose))." + }, + "storageFolders": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The top-level storage folders the format writes below a repository's string RepositoryStorage.Prefix(RepositoryInfo repository)\r\n(`packages`, `symbols`…). Two modules may not claim the same folder, nor string RepositoryStorage.ReposFolder:\r\nFormatRegistry refuses the registration, since a collision would let one format read another's files.", + "nullable": true + }, + "createFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatCreateField" + }, + "description": "What the administrator fills in to create a repository of this format, on top of the name. Empty when a name is all that\r\nis needed.", + "nullable": true + } + }, + "description": "One package format (NuGet, npm, later Maven and OCI) as the common code sees it: what its repositories are called and where\r\nthey live, which kinds a repository of it can have, the UI it contributes, and how its artifacts are counted and purged.\r\nA module only describes the format; what it does per request is a set of services registered beside it\r\n(IFormatIndexer, IFormatSearchProvider, IFormatRetentionHooks,\r\nIFormatScanner, looked up with T? FormatServices.GetFormatService<T>(IServiceProvider provider, RepositoryFormat format)) and the format's own controllers,\r\nwhose routes go through `BaGetEndpointBuilder.MapRoute` with the module's RepositoryFormat IFormatModule.Format." + }, + "IFormFile": { + "type": "string", + "format": "binary" + }, + "IndexScreen": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The 1-based page of results.", + "format": "int32" + }, + "packageType": { + "type": "string", + "description": "The package type filter, `any` for none." + }, + "framework": { + "type": "string", + "description": "The target framework filter, `any` for none." + }, + "prerelease": { + "type": "boolean", + "description": "Whether prerelease versions are included." + }, + "sortBy": { + "$ref": "#/components/schemas/SearchSort" + }, + "supportedSorts": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchSort" + }, + "description": "The orders the search provider can apply on the server; with only the default there is nothing to choose." + }, + "isHome": { + "type": "boolean", + "description": "True for the front page: the repository's root with no search. Everything else lists packages." + }, + "totals": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/FeedStatistics" + } + ] + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchResult" + }, + "description": "The page of results (empty on the front page)." + }, + "lastUpdated": { + "type": "object", + "additionalProperties": { + "type": "string", + "format": "date-time" + }, + "description": "When each listed package ID was last published, by ID; empty when unsupported." + } + }, + "description": "What the front page and the package list show: the search that was asked for and its results." + }, + "InstallSnippet": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The tool the tab is for.", + "nullable": true + }, + "prefix": { + "type": "string", + "description": "A shell prompt shown before the first line; not part of the copied text.", + "nullable": true + }, + "lines": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The lines to copy.", + "nullable": true + } + }, + "description": "One tab of the \"install / configure / push\" commands of a package, artifact or image page (one tool per tab)." + }, + "JsonObject": { + "type": "object" + }, + "LeaseInfo": { + "required": [ + "job", + "node", + "since" + ], + "type": "object", + "properties": { + "job": { + "type": "string", + "description": "The job's name." + }, + "node": { + "type": "string", + "description": "The holder." + }, + "since": { + "type": "string", + "description": "When it was acquired (UTC).", + "format": "date-time" + } + }, + "description": "A lease as stored: the holder's node, a token that tells two holders of one node apart, and when it was taken." + }, + "LegalScreen": { + "required": [ + "title", + "contentHtml" + ], + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "The heading and page title." + }, + "contentHtml": { + "type": "string", + "description": "The operator's Markdown file as HTML (raw HTML in the source is escaped, script links neutralised: HtmlString? ReadmeMarkdown.ToSafeHtml(string? markdown))." + } + }, + "description": "What a legal page (Terms of Use, Privacy Policy) shows: its heading and the operator's Markdown rendered to safe HTML." + }, + "LoginForm": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed: a screen's model leaves it empty.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the sign-in form posts (and the body of `POST /api/ui/account/login`)." + }, + "LoginViewModel": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "allowRegistration": { + "type": "boolean", + "description": "Whether the registration link is shown." + }, + "hasExternalProvider": { + "type": "boolean", + "description": "Whether sign-in with an external provider is offered (any provider in IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders)." + }, + "externalProviderName": { + "type": "string", + "description": "The first provider's display name (kept for clients that offer one button); see IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders.", + "nullable": true + }, + "externalProviders": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalProviderInfo" + }, + "description": "The configured external providers, one sign-in button each." + }, + "emailIsConfigured": { + "type": "boolean", + "description": "Whether mail is configured (the forgot-password link is shown)." + }, + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "notice": { + "type": "string", + "description": "The notice to show.", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed: a screen's model leaves it empty.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The sign-in screen: the form fields it repeats and what it shows. A request never binds this type (the form is LoginForm), so\r\nthe outputs cannot be set from outside; string? LoginForm.Password is always empty." + }, + "LogLevelForm": { + "required": [ + "source", + "level", + "password" + ], + "type": "object", + "properties": { + "source": { + "type": "string", + "description": "The source (a namespace prefix).", + "nullable": true + }, + "level": { + "type": "string", + "description": "The level (ignored when removing).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Setting or removing the lowest level logged for one source." + }, + "LogLevelOverride": { + "required": [ + "source", + "level", + "inOverridesFile" + ], + "type": "object", + "properties": { + "source": { + "type": "string", + "description": "The namespace or type name prefix." + }, + "level": { + "type": "string", + "description": "Verbose, Debug, Information, Warning, Error or Fatal." + }, + "inOverridesFile": { + "type": "boolean", + "description": "True when the Settings overrides file holds it, so it can be removed from here; false when only a configuration file or the environment sets it." + } + }, + "description": "One `Serilog:MinimumLevel:Override:{Source}` entry: the lowest level logged for a source (a namespace or type\r\nname prefix such as `Microsoft.AspNetCore`)." + }, + "MavenArtifactInfo": { + "required": [ + "groupId", + "artifactId", + "created", + "modified", + "versions" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id." + }, + "artifactId": { + "type": "string", + "description": "The artifact id." + }, + "created": { + "type": "string", + "description": "The first deploy (UTC).", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenVersionSummary" + }, + "description": "Its versions, highest first." + }, + "latest": { + "$ref": "#/components/schemas/MavenVersionSummary" + }, + "name": { + "type": "string", + "description": "`group:artifact`.", + "nullable": true + } + }, + "description": "An artifact with its versions, newest first." + }, + "MavenArtifactsViewModel": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The page, from 1.", + "format": "int32" + }, + "result": { + "$ref": "#/components/schemas/MavenSearchPage" + }, + "settings": { + "$ref": "#/components/schemas/MavenRepositorySettings" + }, + "repositoryUrl": { + "type": "string", + "description": "The address Maven is configured with for this repository." + }, + "kind": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "repositoryName": { + "type": "string", + "description": "The repository's name, which is the `id` in `settings.xml` and the POM." + }, + "hasNext": { + "type": "boolean", + "description": "Whether another page follows." + }, + "configurationTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + } + }, + "description": "What the Maven front page (`/maven-artifacts`) shows: this page of search results and the client configuration." + }, + "MavenArtifactViewModel": { + "type": "object", + "properties": { + "group": { + "type": "string", + "description": "The group id from the address.", + "nullable": true + }, + "artifact": { + "type": "string", + "description": "The artifact id from the address.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version from the address; the latest when absent.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with: 200, or 404 when the artifact or version does not exist (the page then explains).", + "format": "int32" + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenArtifactInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenVersionDetail" + } + ] + }, + "repositoryUrl": { + "type": "string", + "description": "The address Maven is configured with for this repository." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name (the `id` in `settings.xml`)." + }, + "installTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The owners, when accounts are on; empty otherwise." + }, + "canManage": { + "type": "boolean", + "description": "Whether the signed-in user can open the manage page (an owner or an administrator)." + } + }, + "description": "What the page of one Maven artifact (`/maven-artifacts/{group}/{artifact}/{version?}`) shows." + }, + "MavenDeployment": { + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id.", + "nullable": true + }, + "artifactId": { + "type": "string", + "description": "The artifact id.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "packaging": { + "type": "string", + "description": "The packaging, the extension of the main file when it has no other (default `jar`).", + "nullable": true + }, + "classifier": { + "type": "string", + "description": "The classifier of the main file, or null.", + "nullable": true + }, + "extension": { + "type": "string", + "description": "The extension of the main file (default: the packaging).", + "nullable": true + }, + "file": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Stream" + } + ] + }, + "pom": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Stream" + } + ] + } + }, + "description": "What the upload page hands to Task<MavenResult> IMavenRepository.DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken)." + }, + "MavenFileDetail": { + "required": [ + "fileName", + "classifier", + "extension", + "size", + "sha1", + "md5", + "sha256", + "sha512", + "created", + "snapshotTimestamp", + "snapshotBuild" + ], + "type": "object", + "properties": { + "fileName": { + "type": "string", + "description": "The file name." + }, + "classifier": { + "type": "string", + "description": "The classifier, or null.", + "nullable": true + }, + "extension": { + "type": "string", + "description": "The extension." + }, + "size": { + "type": "integer", + "description": "Bytes.", + "format": "int64" + }, + "sha1": { + "type": "string", + "description": "SHA-1 hex." + }, + "md5": { + "type": "string", + "description": "MD5 hex." + }, + "sha256": { + "type": "string", + "description": "SHA-256 hex." + }, + "sha512": { + "type": "string", + "description": "SHA-512 hex." + }, + "created": { + "type": "string", + "description": "When stored (UTC).", + "format": "date-time" + }, + "snapshotTimestamp": { + "type": "string", + "description": "The snapshot build timestamp, or null.", + "nullable": true + }, + "snapshotBuild": { + "type": "integer", + "description": "The snapshot build number, or 0.", + "format": "int32" + } + }, + "description": "A file of a version as the pages list it." + }, + "MavenManageForm": { + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization (`AddOwner`, `RemoveOwner`).", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version whose files are listed, and the one a handler acts on (`DeleteFile`, `DeleteVersion`, `Cleanup`).", + "nullable": true + }, + "fileName": { + "type": "string", + "description": "The file to delete (`DeleteFile`).", + "nullable": true + }, + "keep": { + "type": "string", + "description": "How many snapshot builds to keep (`Cleanup`).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password, for the deleting handlers.", + "nullable": true + } + }, + "description": "The form of the Maven management handlers: the chosen version and what the handler needs." + }, + "MavenManageViewModel": { + "type": "object", + "properties": { + "group": { + "type": "string", + "description": "The group id from the address.", + "nullable": true + }, + "artifact": { + "type": "string", + "description": "The artifact id from the address.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version whose files are listed (`?version=`), or null.", + "nullable": true + }, + "info": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenArtifactInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenVersionDetail" + } + ] + }, + "owners": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageOwner" + }, + "description": "The artifact's owners." + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? MavenManageViewModel.Message reports a refusal." + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is an administrator." + }, + "actingAsAdministrator": { + "type": "boolean", + "description": "Whether the user manages the artifact only as an administrator (they are not an owner)." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the user has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "name": { + "type": "string", + "description": "`group:artifact`.", + "nullable": true + } + }, + "description": "What the Maven artifact management screen (`/maven-manage/{group}/{artifact}`) shows; filled by the screen's workflow." + }, + "MavenPolicy": { + "enum": [ + "Releases", + "Snapshots", + "Both" + ], + "type": "string", + "description": "Which versions a local Maven repository accepts." + }, + "MavenPomDependency": { + "required": [ + "groupId", + "artifactId", + "version", + "scope", + "optional" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id." + }, + "artifactId": { + "type": "string", + "description": "The artifact id." + }, + "version": { + "type": "string", + "description": "The version, or null (managed elsewhere).", + "nullable": true + }, + "scope": { + "type": "string", + "description": "The scope, or null (compile).", + "nullable": true + }, + "optional": { + "type": "boolean", + "description": "Whether the dependency is optional." + } + }, + "description": "A dependency a POM declares (versions and scopes as written; properties are not resolved)." + }, + "MavenPomInfo": { + "required": [ + "groupId", + "artifactId", + "version", + "packaging", + "name", + "description", + "url", + "parent", + "dependencies" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id (the parent's when the POM has none).", + "nullable": true + }, + "artifactId": { + "type": "string", + "description": "The artifact id.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version (the parent's when the POM has none).", + "nullable": true + }, + "packaging": { + "type": "string", + "description": "The packaging, `jar` by default." + }, + "name": { + "type": "string", + "description": "The `name`.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The `description`.", + "nullable": true + }, + "url": { + "type": "string", + "description": "The project `url`.", + "nullable": true + }, + "parent": { + "type": "string", + "description": "The parent as `group:artifact:version`, or null.", + "nullable": true + }, + "dependencies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenPomDependency" + }, + "description": "The declared dependencies, in order." + } + }, + "description": "What the search and the pages read from a POM." + }, + "MavenRepositorySettings": { + "type": "object", + "properties": { + "policy": { + "$ref": "#/components/schemas/MavenPolicy" + }, + "allowRedeploy": { + "type": "boolean", + "description": "Whether a release file that exists may be deployed again (replaced). The caller then also needs the Delete action, as\r\nArtifactory's Delete/Overwrite does. Default false: a release is immutable. Snapshots are never refused for this." + }, + "maxSnapshotBuilds": { + "type": "integer", + "description": "How many timestamped builds of a snapshot version are kept: when a deploy brings a newer build, older ones beyond this\r\nnumber are deleted. Zero keeps all (clean up on the artifact's page).", + "format": "int32" + } + }, + "description": "The settings of a local Maven repository, kept as JSON in string? Repository.Settings (no schema of their own)." + }, + "MavenSearchHit": { + "required": [ + "groupId", + "artifactId", + "version", + "name", + "description", + "modified" + ], + "type": "object", + "properties": { + "groupId": { + "type": "string", + "description": "The group id." + }, + "artifactId": { + "type": "string", + "description": "The artifact id." + }, + "version": { + "type": "string", + "description": "The newest version (a release if there is one), or null.", + "nullable": true + }, + "name": { + "type": "string", + "description": "The POM's name of it, or null.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The POM's description of it, or null.", + "nullable": true + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "coordinateName": { + "type": "string", + "description": "`group:artifact`.", + "nullable": true + } + }, + "description": "A search hit." + }, + "MavenSearchPage": { + "required": [ + "total", + "hits" + ], + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "All matches.", + "format": "int32" + }, + "hits": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenSearchHit" + }, + "description": "This page." + } + }, + "description": "A page of hits." + }, + "MavenUploadViewModel": { + "type": "object", + "properties": { + "accountsEnabled": { + "type": "boolean", + "description": "Whether accounts are on (the uploader then signs in)." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server is read-only." + }, + "signedIn": { + "type": "boolean", + "description": "Whether the visitor is signed in." + }, + "needsApiKey": { + "type": "boolean", + "description": "Without accounts there is no user to own an upload, so the uploader proves itself with the API key." + }, + "nothingCanAuthenticate": { + "type": "boolean", + "description": "Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed." + }, + "canUpload": { + "type": "boolean", + "description": "Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in." + }, + "repositoryUrl": { + "type": "string", + "description": "The address Maven is configured with for this repository." + }, + "repositoryName": { + "type": "string", + "description": "The repository's name (the `id` in `settings.xml`)." + }, + "settings": { + "$ref": "#/components/schemas/MavenRepositorySettings" + }, + "message": { + "type": "string", + "description": "What happened, for the page to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? MavenUploadViewModel.Message reports a failure." + }, + "deployedName": { + "type": "string", + "description": "The artifact just deployed (`group:artifact`), so the page can link to it.", + "nullable": true + }, + "deployedVersion": { + "type": "string", + "description": "The version just deployed.", + "nullable": true + }, + "posted": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenDeployment" + } + ] + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with (200, or the refusal's).", + "format": "int32" + } + }, + "description": "What the Maven upload page (`/maven-upload`) shows, before and after a deployment." + }, + "MavenVersionDetail": { + "required": [ + "summary", + "files", + "pom", + "pomText" + ], + "type": "object", + "properties": { + "summary": { + "$ref": "#/components/schemas/MavenVersionSummary" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MavenFileDetail" + }, + "description": "Its files, by name." + }, + "pom": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenPomInfo" + } + ] + }, + "pomText": { + "type": "string", + "description": "The POM text (for the view), or null.", + "nullable": true + } + }, + "description": "One version with its files and POM." + }, + "MavenVersionSummary": { + "required": [ + "version", + "isSnapshot", + "name", + "description", + "packaging", + "created", + "modified", + "fileCount", + "size", + "builds" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version." + }, + "isSnapshot": { + "type": "boolean", + "description": "Whether it is a snapshot." + }, + "name": { + "type": "string", + "description": "The POM's name, or null.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The POM's description, or null.", + "nullable": true + }, + "packaging": { + "type": "string", + "description": "The POM's packaging, or null.", + "nullable": true + }, + "created": { + "type": "string", + "description": "The first file (UTC).", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "fileCount": { + "type": "integer", + "description": "Files of the version.", + "format": "int32" + }, + "size": { + "type": "integer", + "description": "Bytes of the version.", + "format": "int64" + }, + "builds": { + "type": "integer", + "description": "For a snapshot: how many timestamped builds it holds.", + "format": "int32" + } + }, + "description": "A version as the artifact page lists it." + }, + "NodeInfo": { + "required": [ + "id", + "started", + "seen", + "version", + "ready", + "problem", + "gateClosed" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The node's name." + }, + "started": { + "type": "string", + "description": "When it started (UTC).", + "format": "date-time" + }, + "seen": { + "type": "string", + "description": "Its latest heartbeat (UTC).", + "format": "date-time" + }, + "version": { + "type": "string", + "description": "The BaGet version it runs." + }, + "ready": { + "type": "boolean", + "description": "Whether its last readiness check passed." + }, + "problem": { + "type": "string", + "description": "What failed, when it did not.", + "nullable": true + }, + "gateClosed": { + "type": "boolean", + "description": "Whether its read-only gate is closed." + } + }, + "description": "A node as it publishes itself." + }, + "NpmManageDeprecateForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "message": { + "type": "string", + "description": "The deprecation message (`Deprecate` only).", + "nullable": true + } + }, + "description": "The form of `Deprecate` and `Undeprecate`." + }, + "NpmManageOwnerForm": { + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization.", + "nullable": true + } + }, + "description": "The form of the npm management handlers that name an owner." + }, + "NpmManageTagForm": { + "type": "object", + "properties": { + "tag": { + "type": "string", + "description": "The dist-tag.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version it points at (not used by `RemoveTag`).", + "nullable": true + } + }, + "description": "The form of `SetTag`." + }, + "NpmManageUnpublishForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version (`Unpublish` only).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of `Unpublish` (one version) and `UnpublishAll` (the version is ignored); the password confirms." + }, + "NpmManageViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package name from the address.", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmPackageInfo" + } + ] + }, + "owners": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageOwner" + }, + "description": "The package's owners." + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? NpmManageViewModel.Message reports a refusal." + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is an administrator." + }, + "actingAsAdministrator": { + "type": "boolean", + "description": "Whether the user manages the package only as an administrator (they are not an owner)." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the user has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "unpublishWindow": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": "string", + "description": "How long after publishing a version its owner may unpublish it with Deploy alone." + } + }, + "description": "What the npm package management screen (`/npm-manage/{*id}`) shows; filled by the screen's workflow." + }, + "NpmPackageInfo": { + "required": [ + "name", + "created", + "modified", + "distTags", + "versions" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name (`@scope/name` for a scoped package)." + }, + "created": { + "type": "string", + "description": "The first publish.", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change.", + "format": "date-time" + }, + "distTags": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Tag to version." + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NpmVersionInfo" + }, + "description": "Every version, oldest first by semantic version." + }, + "latest": { + "$ref": "#/components/schemas/NpmVersionInfo" + }, + "revision": { + "type": "string", + "description": "The document revision clients send back on a write (`?write=true` reads, `/-rev/{rev}` writes): changes with every change of the package.", + "nullable": true + } + }, + "description": "A package with its versions and dist-tags, as stored." + }, + "NpmPackagesViewModel": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search text.", + "nullable": true + }, + "pageIndex": { + "type": "integer", + "description": "The page, from 1.", + "format": "int32" + }, + "result": { + "$ref": "#/components/schemas/NpmSearchPage" + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "hasNext": { + "type": "boolean", + "description": "Whether another page follows." + } + }, + "description": "What the npm front page (`/npm-packages`) shows: this page of search results and the registry address." + }, + "NpmPackageViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package name from the address.", + "nullable": true + }, + "requestedVersion": { + "type": "string", + "description": "The version asked for with `?version=`; the latest when absent or unknown.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with: 200, or 404 when the package does not exist (the page then explains).", + "format": "int32" + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmPackageInfo" + } + ] + }, + "selected": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/NpmVersionInfo" + } + ] + }, + "readme": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/HtmlString" + } + ] + }, + "selectedTags": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The dist-tags that point at the selected version." + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "tarballUrl": { + "type": "string", + "description": "Where the selected version's tarball is.", + "nullable": true + }, + "installTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + } + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The owners, when accounts are on; empty otherwise." + }, + "canManage": { + "type": "boolean", + "description": "Whether the signed-in user can open the manage page (an owner or an administrator)." + } + }, + "description": "What the page of one npm package (`/npm-packages/{name}`) shows." + }, + "NpmSearchHit": { + "required": [ + "name", + "version", + "description", + "keywords", + "modified" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name." + }, + "version": { + "type": "string", + "description": "The latest version.", + "nullable": true + }, + "description": { + "type": "string", + "description": "Its description.", + "nullable": true + }, + "keywords": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Its keywords." + }, + "modified": { + "type": "string", + "description": "The last change.", + "format": "date-time" + } + }, + "description": "One package in a search result." + }, + "NpmSearchPage": { + "required": [ + "total", + "hits" + ], + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "All matches.", + "format": "int32" + }, + "hits": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NpmSearchHit" + }, + "description": "This page, ordered by name." + } + }, + "description": "A page of packages." + }, + "NpmUploadViewModel": { + "type": "object", + "properties": { + "accountsEnabled": { + "type": "boolean", + "description": "Whether accounts are on (the uploader then signs in)." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server is read-only." + }, + "signedIn": { + "type": "boolean", + "description": "Whether the visitor is signed in." + }, + "needsApiKey": { + "type": "boolean", + "description": "Without accounts there is no user to own an upload, so the uploader proves itself with the API key." + }, + "nothingCanAuthenticate": { + "type": "boolean", + "description": "Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed." + }, + "canUpload": { + "type": "boolean", + "description": "Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in." + }, + "registryUrl": { + "type": "string", + "description": "The address npm is configured with for this repository." + }, + "publishLines": { + "type": "array", + "items": { + "type": "string" + } + }, + "message": { + "type": "string", + "description": "What happened, for the page to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? NpmUploadViewModel.Message reports a failure." + }, + "publishedName": { + "type": "string", + "description": "The package just published, so the page can link to it.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with (200, or the refusal's).", + "format": "int32" + } + }, + "description": "What the npm upload page (`/npm-upload`) shows, before and after a publish." + }, + "NpmVersionInfo": { + "required": [ + "version", + "published", + "deprecated", + "tarballSize", + "integrity", + "shasum", + "manifest" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version string as published." + }, + "published": { + "type": "string", + "description": "When it was published.", + "format": "date-time" + }, + "deprecated": { + "type": "string", + "description": "The deprecation message, or null.", + "nullable": true + }, + "tarballSize": { + "type": "integer", + "description": "Bytes of the tarball.", + "format": "int64" + }, + "integrity": { + "type": "string", + "description": "The tarball's SRI string (`sha512-…`)." + }, + "shasum": { + "type": "string", + "description": "The tarball's SHA-1 in hex." + }, + "manifest": { + "$ref": "#/components/schemas/JsonObject" + }, + "description": { + "type": "string", + "description": "The manifest's `description`, or null.", + "nullable": true + }, + "readme": { + "type": "string", + "description": "The manifest's `readme`, or null.", + "nullable": true + }, + "license": { + "type": "string", + "description": "The manifest's `license` when it is a string, or null.", + "nullable": true + }, + "keywords": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The manifest's `keywords` that are strings.", + "nullable": true + } + }, + "description": "One published version as stored." + }, + "NuGetVersion": { + "type": "object", + "properties": { + "version": { + "pattern": "^\\d+(\\.\\d+){1,3}$", + "type": "string", + "nullable": true + }, + "isLegacyVersion": { + "type": "boolean" + }, + "revision": { + "type": "integer", + "format": "int32" + }, + "isSemVer2": { + "type": "boolean" + }, + "originalVersion": { + "type": "string", + "nullable": true + }, + "major": { + "type": "integer", + "format": "int32" + }, + "minor": { + "type": "integer", + "format": "int32" + }, + "patch": { + "type": "integer", + "format": "int32" + }, + "releaseLabels": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "release": { + "type": "string", + "nullable": true + }, + "isPrerelease": { + "type": "boolean" + }, + "hasMetadata": { + "type": "boolean" + }, + "metadata": { + "type": "string", + "nullable": true + } + } + }, + "OciDescriptor": { + "required": [ + "mediaType", + "digest", + "size", + "artifactType", + "annotations" + ], + "type": "object", + "properties": { + "mediaType": { + "type": "string", + "description": "The referrer's media type." + }, + "digest": { + "type": "string", + "description": "Its digest." + }, + "size": { + "type": "integer", + "description": "Its size.", + "format": "int64" + }, + "artifactType": { + "type": "string", + "description": "Its artifact type, or null.", + "nullable": true + }, + "annotations": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Its annotations, or null.", + "nullable": true + } + }, + "description": "A descriptor in a referrers index." + }, + "OciGcItem": { + "required": [ + "kind", + "subject", + "bytes", + "image" + ], + "type": "object", + "properties": { + "kind": { + "$ref": "#/components/schemas/OciGcItemKind" + }, + "subject": { + "type": "string", + "description": "A digest or a session reference." + }, + "bytes": { + "type": "integer", + "description": "Bytes it frees (0 for a session).", + "format": "int64" + }, + "image": { + "type": "string", + "description": "The image it belonged to, if any.", + "nullable": true + } + }, + "description": "One thing a garbage collection removes." + }, + "OciGcItemKind": { + "enum": [ + "ExpiredUpload", + "UnreferencedLayer", + "OrphanBlob", + "OrphanFile" + ], + "type": "string", + "description": "What a garbage collection found (or, outside a dry run, removed)." + }, + "OciGcReport": { + "required": [ + "dryRun", + "repository", + "expiredUploads", + "unreferencedLayers", + "blobs", + "orphanFiles", + "bytes", + "items", + "itemsTruncated", + "note" + ], + "type": "object", + "properties": { + "dryRun": { + "type": "boolean", + "description": "Whether nothing was changed (the numbers are what a run would remove)." + }, + "repository": { + "type": "string", + "description": "The repository." + }, + "expiredUploads": { + "type": "integer", + "description": "Upload sessions discarded.", + "format": "int32" + }, + "unreferencedLayers": { + "type": "integer", + "description": "Image-to-layer links dropped (a layer two images hold counts twice).", + "format": "int32" + }, + "blobs": { + "type": "integer", + "description": "Blobs (rows and files) removed: those no image holds after the links are dropped, orphan rows included.", + "format": "int32" + }, + "orphanFiles": { + "type": "integer", + "description": "Files under the blob folder with no row, removed.", + "format": "int32" + }, + "bytes": { + "type": "integer", + "description": "Bytes freed by the blobs and orphan files, as far as they are known (an orphan file's size is not).", + "format": "int64" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciGcItem" + }, + "description": "The first of the things removed (the list is capped)." + }, + "itemsTruncated": { + "type": "boolean", + "description": "Whether there are more than Items holds." + }, + "note": { + "type": "string", + "description": "Something the run could not do (the store cannot list files), or null.", + "nullable": true + }, + "summary": { + "type": "string", + "description": "One line for the Operations page and the audit log.", + "nullable": true + } + }, + "description": "The outcome of one garbage collection of a repository." + }, + "OciImageInfo": { + "required": [ + "name", + "created", + "modified", + "tags", + "manifests", + "size", + "unreferencedBlobs" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The image name." + }, + "created": { + "type": "string", + "description": "When the first upload arrived (UTC).", + "format": "date-time" + }, + "modified": { + "type": "string", + "description": "The last change (UTC).", + "format": "date-time" + }, + "tags": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciTagInfo" + }, + "description": "The tags, by name." + }, + "manifests": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciManifestSummary" + }, + "description": "The manifests, newest first." + }, + "size": { + "type": "integer", + "description": "Bytes of the distinct blobs the image holds.", + "format": "int64" + }, + "unreferencedBlobs": { + "type": "integer", + "description": "Blobs held by the image that no manifest uses.", + "format": "int32" + } + }, + "description": "An image with its tags and manifests (the image page)." + }, + "OciImagePage": { + "required": [ + "total", + "images" + ], + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "All images that matched and may be read.", + "format": "int32" + }, + "images": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciImageSummary" + }, + "description": "The page." + } + }, + "description": "A page of OciImageSummary." + }, + "OciImageSummary": { + "required": [ + "name", + "tags", + "manifests", + "size", + "modified" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The image name." + }, + "tags": { + "type": "integer", + "description": "Number of tags.", + "format": "int32" + }, + "manifests": { + "type": "integer", + "description": "Number of manifests (including indexes).", + "format": "int32" + }, + "size": { + "type": "integer", + "description": "Bytes of the distinct blobs the image holds.", + "format": "int64" + }, + "modified": { + "type": "string", + "description": "The last manifest or tag change (UTC).", + "format": "date-time" + } + }, + "description": "An image as the browse page lists it." + }, + "OciLayerInfo": { + "required": [ + "digest", + "size", + "mediaType" + ], + "type": "object", + "properties": { + "digest": { + "type": "string", + "description": "The digest." + }, + "size": { + "type": "integer", + "description": "The size announced by the manifest.", + "format": "int64" + }, + "mediaType": { + "type": "string", + "description": "The media type." + } + }, + "description": "A layer, config or other blob a manifest lists." + }, + "OciManifestDetail": { + "required": [ + "summary", + "json", + "config", + "layers", + "platforms", + "annotations" + ], + "type": "object", + "properties": { + "summary": { + "$ref": "#/components/schemas/OciManifestSummary" + }, + "json": { + "type": "string", + "description": "The manifest document, pretty-printed for display (the stored bytes are unchanged)." + }, + "config": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciLayerInfo" + } + ] + }, + "layers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciLayerInfo" + }, + "description": "The layers in order (empty for an index)." + }, + "platforms": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OciPlatformInfo" + }, + "description": "The entries of an index (empty for a single-image manifest)." + }, + "annotations": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The manifest's annotations." + } + }, + "description": "One manifest in full (the manifest page)." + }, + "OciManifestSummary": { + "required": [ + "digest", + "mediaType", + "size", + "isIndex", + "created", + "tags", + "artifactType", + "subjectDigest", + "platform", + "layerCount", + "contentSize" + ], + "type": "object", + "properties": { + "digest": { + "type": "string", + "description": "Its digest." + }, + "mediaType": { + "type": "string", + "description": "Its media type." + }, + "size": { + "type": "integer", + "description": "Bytes of the manifest document.", + "format": "int64" + }, + "isIndex": { + "type": "boolean", + "description": "Whether it is an index of platform manifests." + }, + "created": { + "type": "string", + "description": "When it was first pushed to the image (UTC).", + "format": "date-time" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The tags that point at it." + }, + "artifactType": { + "type": "string", + "description": "Its artifact type, or null.", + "nullable": true + }, + "subjectDigest": { + "type": "string", + "description": "The digest it refers to, or null.", + "nullable": true + }, + "platform": { + "type": "string", + "description": "For a single-image manifest, its platform when the config says so (`linux/amd64`); otherwise null.", + "nullable": true + }, + "layerCount": { + "type": "integer", + "description": "Number of layers (0 for an index).", + "format": "int32" + }, + "contentSize": { + "type": "integer", + "description": "Bytes of the config and layers (the children are not summed for an index).", + "format": "int64" + } + }, + "description": "A manifest as the image page lists it." + }, + "OciPlatformInfo": { + "required": [ + "digest", + "mediaType", + "size", + "os", + "architecture", + "variant", + "present" + ], + "type": "object", + "properties": { + "digest": { + "type": "string", + "description": "The child manifest." + }, + "mediaType": { + "type": "string", + "description": "The child's media type." + }, + "size": { + "type": "integer", + "description": "The child's size.", + "format": "int64" + }, + "os": { + "type": "string", + "description": "The operating system, or null.", + "nullable": true + }, + "architecture": { + "type": "string", + "description": "The architecture, or null.", + "nullable": true + }, + "variant": { + "type": "string", + "description": "The variant (`v7`), or null.", + "nullable": true + }, + "present": { + "type": "boolean", + "description": "Whether the child manifest is in this image." + }, + "platform": { + "type": "string", + "description": "The platform as one string: `linux/arm64/v8` (or `unknown` for an entry with none).", + "nullable": true + } + }, + "description": "A platform entry of an index." + }, + "OciTagInfo": { + "required": [ + "name", + "digest", + "updated" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The tag." + }, + "digest": { + "type": "string", + "description": "The manifest it points at." + }, + "updated": { + "type": "string", + "description": "When it was created or moved (UTC).", + "format": "date-time" + } + }, + "description": "A tag of an image." + }, + "OperationForm": { + "required": [ + "operation", + "repository", + "password" + ], + "type": "object", + "properties": { + "operation": { + "type": "string", + "description": "The operation's name (`catalog-rebuild`).", + "nullable": true + }, + "repository": { + "type": "string", + "description": "The repository it runs on.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (asked for operations that delete data).", + "nullable": true + } + }, + "description": "Starting a maintenance operation." + }, + "OperationRow": { + "required": [ + "operation", + "repository", + "status" + ], + "type": "object", + "properties": { + "operation": { + "$ref": "#/components/schemas/IAdminOperation" + }, + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "status": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AdminJobStatus" + } + ] + } + }, + "description": "One row of the operations screen: an operation on a repository." + }, + "OperationsViewModel": { + "type": "object", + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OperationRow" + }, + "description": "The operations available on this server, for every repository." + }, + "anyRunning": { + "type": "boolean", + "description": "Whether any job is running (the page refreshes itself)." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the operations screen (`/admin/operations`) shows: the maintenance operations and the status of each." + }, + "Organization": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + } + }, + "description": "An account that several users own packages through." + }, + "OrganizationDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization's name (route).", + "nullable": true + }, + "organization": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Organization" + } + ] + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrganizationMemberRow" + }, + "description": "Its members, by name." + }, + "ownedPackageIds": { + "type": "integer", + "description": "How many package IDs it owns, in every repository.", + "format": "int32" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the organization screen (`/admin/organizations/{name}`) shows: the organization, its members and the last action." + }, + "OrganizationMemberForm": { + "required": [ + "userName", + "isAdmin", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The member's user name.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the member administers the organization (ignored when removing)." + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Adding a member to an organization, changing their administrator flag or removing them." + }, + "OrganizationMemberRow": { + "required": [ + "userName", + "isAdmin" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "isAdmin": { + "type": "boolean", + "description": "Whether the member administers the organization." + } + }, + "description": "A member as the organization page lists them." + }, + "OrganizationOutcome": { + "required": [ + "name", + "outcome" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The organization.", + "nullable": true + }, + "outcome": { + "type": "string", + "description": "A sentence for the confirmation page." + } + }, + "description": "What happens to one organization when an administrator deletes a member." + }, + "OrganizationRenameForm": { + "required": [ + "newName", + "password" + ], + "type": "object", + "properties": { + "newName": { + "type": "string", + "description": "The new name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Renaming an organization." + }, + "OrganizationSummary": { + "required": [ + "name", + "created", + "members", + "administrators", + "packageIds" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When it was created.", + "format": "date-time" + }, + "members": { + "type": "integer", + "description": "How many members it has.", + "format": "int32" + }, + "administrators": { + "type": "integer", + "description": "How many of them administer it.", + "format": "int32" + }, + "packageIds": { + "type": "integer", + "description": "How many package IDs it owns, counted per repository.", + "format": "int32" + } + }, + "description": "An organization as the administrator's list shows it." + }, + "OrganizationsViewModel": { + "type": "object", + "properties": { + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccountOrganization" + }, + "description": "The organizations the user belongs to." + }, + "message": { + "type": "string", + "description": "The answer to the last action.", + "nullable": true + } + }, + "description": "The signed-in user's organizations screen." + }, + "OwnedPackage": { + "type": "object", + "properties": { + "id": { + "type": "string", + "nullable": true + }, + "latestVersion": { + "type": "string", + "description": "The highest version, listed or not, or null when no version remains.", + "nullable": true + }, + "latestVersionIsListed": { + "type": "boolean" + }, + "versionCount": { + "type": "integer", + "format": "int32" + }, + "downloads": { + "type": "integer", + "format": "int64" + } + }, + "description": "One owned package ID, summarised across its versions." + }, + "Package": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "id": { + "type": "string", + "nullable": true + }, + "version": { + "$ref": "#/components/schemas/NuGetVersion" + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "downloads": { + "type": "integer", + "format": "int64" + }, + "hasReadme": { + "type": "boolean" + }, + "hasEmbeddedIcon": { + "type": "boolean" + }, + "isPrerelease": { + "type": "boolean" + }, + "releaseNotes": { + "type": "string", + "nullable": true + }, + "language": { + "type": "string", + "nullable": true + }, + "listed": { + "type": "boolean" + }, + "minClientVersion": { + "type": "string", + "nullable": true + }, + "published": { + "type": "string", + "description": "The time at which the package was published, in UTC.", + "format": "date-time" + }, + "requireLicenseAcceptance": { + "type": "boolean" + }, + "semVerLevel": { + "$ref": "#/components/schemas/SemVerLevel" + }, + "summary": { + "type": "string", + "nullable": true + }, + "title": { + "type": "string", + "nullable": true + }, + "iconUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "projectUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "repositoryUrl": { + "type": "string", + "format": "uri", + "nullable": true + }, + "repositoryType": { + "type": "string", + "nullable": true + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "rowVersion": { + "type": "string", + "description": "Used for optimistic concurrency.", + "format": "byte", + "nullable": true + }, + "dependencies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDependency" + }, + "nullable": true + }, + "packageTypes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageType" + }, + "nullable": true + }, + "targetFrameworks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TargetFramework" + }, + "nullable": true + }, + "deprecation": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageDeprecation" + } + ] + }, + "vulnerabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageVulnerability" + }, + "description": "The known vulnerabilities affecting this version.", + "nullable": true + }, + "normalizedVersionString": { + "type": "string", + "nullable": true + }, + "originalVersionString": { + "type": "string", + "nullable": true + }, + "iconUrlString": { + "type": "string", + "nullable": true + }, + "licenseUrlString": { + "type": "string", + "nullable": true + }, + "projectUrlString": { + "type": "string", + "nullable": true + }, + "repositoryUrlString": { + "type": "string", + "nullable": true + } + } + }, + "PackageDeletionBehavior": { + "enum": [ + "Unlist", + "HardDelete" + ], + "type": "string", + "description": "How BaGet should interpret package deletion requests.\r\nSee: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package" + }, + "PackageDependency": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "id": { + "type": "string", + "description": "The dependency's package ID. Null if this is a dependency group without any dependencies.", + "nullable": true + }, + "versionRange": { + "type": "string", + "description": "The dependency's package version. Null if this is a dependency group without any dependencies.", + "nullable": true + }, + "targetFramework": { + "type": "string", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + } + }, + "PackageDependent": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The dependent package id.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description of the dependent package.", + "nullable": true + }, + "totalDownloads": { + "type": "integer", + "description": "The total downloads for the dependent package.", + "format": "int64" + } + }, + "description": "A package that depends on the queried package." + }, + "PackageDeprecation": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "reasons": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why the package was deprecated. The protocol defines \"Legacy\", \"CriticalBugs\"\r\nand \"Other\"; a package may carry more than one.", + "nullable": true + }, + "message": { + "type": "string", + "description": "Free text explaining the deprecation. Optional.", + "nullable": true + }, + "alternatePackageId": { + "type": "string", + "description": "The ID of the package to use instead. Null if none was suggested.", + "nullable": true + }, + "alternateVersionRange": { + "type": "string", + "description": "The versions of the alternate package that may be used, or \"*\" for any.\r\nNull if no alternate package was suggested.", + "nullable": true + }, + "packageKey": { + "type": "integer", + "description": "The key of the deprecated package version. Nullable so that the relationship\r\nstays optional in the database: a required one would need a foreign key change,\r\nwhich SQLite cannot make in place.", + "format": "int32", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + }, + "description": "A package version marked as deprecated.\r\nSee: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation" + }, + "PackageDetails": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The normalized version.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description.", + "nullable": true + }, + "releaseNotes": { + "type": "string", + "description": "The release notes.", + "nullable": true + }, + "projectUrl": { + "type": "string", + "description": "The project website, or an empty string.", + "nullable": true + }, + "repositoryUrl": { + "type": "string", + "description": "The source repository, or an empty string.", + "nullable": true + }, + "downloads": { + "type": "integer", + "description": "The downloads of this version.", + "format": "int64" + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The authors." + } + }, + "description": "What the package page shows about the version it displays (a flat copy of the stored package, with no navigation properties)." + }, + "PackageDownloads": { + "type": "object", + "properties": { + "id": { + "type": "string", + "nullable": true + }, + "version": { + "type": "string", + "description": "Null when the downloads are a whole package ID's.", + "nullable": true + }, + "downloads": { + "type": "integer", + "format": "int64" + }, + "published": { + "type": "string", + "format": "date-time", + "nullable": true + } + } + }, + "PackageManageDeprecateForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "reasons": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The reasons (at least one of `Legacy`, `CriticalBugs`, `Other`).", + "nullable": true + }, + "message": { + "type": "string", + "description": "Free text, optional.", + "nullable": true + }, + "alternatePackageId": { + "type": "string", + "description": "The package to use instead, optional.", + "nullable": true + }, + "alternateVersionRange": { + "type": "string", + "description": "The versions of it that may be used, optional (needs string? PackageManageDeprecateForm.AlternatePackageId).", + "nullable": true + } + }, + "description": "The form of `Deprecate`." + }, + "PackageManageDeprecation": { + "required": [ + "reasons", + "message", + "alternatePackageId", + "alternateVersionRange" + ], + "type": "object", + "properties": { + "reasons": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Why (`Legacy`, `CriticalBugs`, `Other`)." + }, + "message": { + "type": "string", + "description": "Free text, or null.", + "nullable": true + }, + "alternatePackageId": { + "type": "string", + "description": "The package to use instead, or null.", + "nullable": true + }, + "alternateVersionRange": { + "type": "string", + "description": "The versions of it that may be used, or null.", + "nullable": true + } + }, + "description": "A version's deprecation." + }, + "PackageManageHardDeleteForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of a permanent deletion of a version (administrators; the password confirms)." + }, + "PackageManageOwner": { + "required": [ + "ownerName", + "isVerified" + ], + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization name.", + "nullable": true + }, + "isVerified": { + "type": "boolean", + "description": "Whether the ID is reserved for this owner." + } + }, + "description": "An owner of a package ID." + }, + "PackageManageOwnerForm": { + "type": "object", + "properties": { + "ownerName": { + "type": "string", + "description": "The user or organization.", + "nullable": true + } + }, + "description": "The form of a handler that names an owner." + }, + "PackageManagePasswordForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The caller's password.", + "nullable": true + } + }, + "description": "The form of a handler that only asks for the password." + }, + "PackageManageRemoveVulnerabilityForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "key": { + "type": "integer", + "description": "The vulnerability's key.", + "format": "int32" + } + }, + "description": "The form of `RemoveVulnerability`." + }, + "PackageManageReport": { + "required": [ + "key", + "packageVersion", + "reason", + "details", + "reporterEmail" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The report's key (what `ResolveReport` takes).", + "format": "int32" + }, + "packageVersion": { + "type": "string", + "description": "The reported version.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "The reason given.", + "nullable": true + }, + "details": { + "type": "string", + "description": "The details given.", + "nullable": true + }, + "reporterEmail": { + "type": "string", + "description": "Where to reply, if the reporter gave an address.", + "nullable": true + } + }, + "description": "An open abuse report." + }, + "PackageManageReportForm": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The report's key.", + "format": "int32" + } + }, + "description": "The form of `ResolveReport`." + }, + "PackageManageScreen": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID from the address.", + "nullable": true + }, + "owners": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageOwner" + }, + "description": "The ID's owners." + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageVersion" + }, + "description": "The ID's versions, newest first, unlisted ones included." + }, + "reports": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageReport" + }, + "description": "The open abuse reports against the ID." + }, + "message": { + "type": "string", + "description": "The outcome of the last action.", + "nullable": true + }, + "hasValidation": { + "type": "boolean", + "description": "Whether validation has submissions for the ID." + }, + "isVerified": { + "type": "boolean", + "description": "Whether the ID is verified (reserved)." + }, + "symbols": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageSymbol" + } + }, + "description": "The PDBs indexed from each version's symbol package, by normalized version." + }, + "symbolsSupported": { + "type": "boolean", + "description": "Whether the database records symbols per package version." + }, + "severityNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The severity names a vulnerability can have, by their protocol number." + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the caller is an administrator." + }, + "actingAsAdministrator": { + "type": "boolean", + "description": "Whether the caller manages this ID only as an administrator (not as an owner)." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the caller has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "deletionBehavior": { + "$ref": "#/components/schemas/PackageDeletionBehavior" + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server refuses writes." + } + }, + "description": "What the package management screen (`/packages/{id}/manage`) shows, as plain data (the JSON model of `/api/ui/packages/{id}/manage`).\r\nThe page's own `ManageViewModel` is built from it for the view." + }, + "PackageManageSymbol": { + "required": [ + "fileName", + "key" + ], + "type": "object", + "properties": { + "fileName": { + "type": "string", + "description": "The PDB file name." + }, + "key": { + "type": "string", + "description": "Its signature key." + } + }, + "description": "An indexed PDB of a version." + }, + "PackageManageVerifiedForm": { + "type": "object", + "properties": { + "verified": { + "type": "boolean", + "description": "Whether the ID is verified." + } + }, + "description": "The form of `SetVerified`." + }, + "PackageManageVersion": { + "required": [ + "version", + "normalizedVersion", + "downloads", + "listed", + "deprecation", + "vulnerabilities" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version as published (original text)." + }, + "normalizedVersion": { + "type": "string", + "description": "The normalized version, which the forms post back.", + "nullable": true + }, + "downloads": { + "type": "integer", + "description": "The download count.", + "format": "int64" + }, + "listed": { + "type": "boolean", + "description": "Whether the version is listed." + }, + "deprecation": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageManageDeprecation" + } + ] + }, + "vulnerabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageManageVulnerability" + }, + "description": "Its vulnerabilities." + } + }, + "description": "One version of the ID." + }, + "PackageManageVersionForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The (normalized) version.", + "nullable": true + } + }, + "description": "The form of a handler that names a version." + }, + "PackageManageVulnerability": { + "required": [ + "key", + "advisoryUrl", + "severity", + "versionRange", + "source" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The row's key (what `RemoveVulnerability` takes).", + "format": "int32" + }, + "advisoryUrl": { + "type": "string", + "description": "The advisory.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "0 low, 1 moderate, 2 high, 3 critical.", + "format": "int32" + }, + "versionRange": { + "type": "string", + "description": "The affected range, or null.", + "nullable": true + }, + "source": { + "type": "string", + "description": "Null for a manual entry, `osv` for one the scanner wrote (not editable here).", + "nullable": true + } + }, + "description": "A vulnerability recorded for a version." + }, + "PackageManageVulnerabilityForm": { + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The version.", + "nullable": true + }, + "advisoryUrl": { + "type": "string", + "description": "The advisory URL.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "0 low, 1 moderate, 2 high, 3 critical.", + "format": "int32" + }, + "versionRange": { + "type": "string", + "description": "The affected range, optional.", + "nullable": true + } + }, + "description": "The form of `AddVulnerability`." + }, + "PackageOwner": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "packageId": { + "type": "string", + "nullable": true + }, + "ownerName": { + "type": "string", + "description": "A user name or an organization name.", + "nullable": true + }, + "isVerified": { + "type": "boolean", + "description": "Set by the server's administrator to mark the ID as reserved for this owner,\r\nwhich search reports as \"verified\"." + } + }, + "description": "An owner of every version of a package ID." + }, + "PackageScreen": { + "type": "object", + "properties": { + "found": { + "type": "boolean", + "description": "False when the package (or any listed version of it) does not exist; PackageDetails PackageScreen.Package then only names the ID." + }, + "package": { + "$ref": "#/components/schemas/PackageDetails" + }, + "isDotnetTemplate": { + "type": "boolean", + "description": "The package is a dotnet template." + }, + "isDotnetTool": { + "type": "boolean", + "description": "The package is a dotnet tool." + }, + "lastUpdated": { + "type": "string", + "description": "When any version was last published.", + "format": "date-time" + }, + "totalDownloads": { + "type": "integer", + "description": "Downloads of every version.", + "format": "int64" + }, + "usedBy": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDependent" + }, + "description": "The packages that depend on this one." + }, + "dependencyGroups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DependencyGroupModel" + }, + "description": "The dependencies, by framework." + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageVersionEntry" + }, + "description": "The listed versions, newest first." + }, + "readmeHtml": { + "type": "string", + "description": "The readme as safe HTML (ReadmeMarkdown), or null.", + "nullable": true + }, + "frameworkGroups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FrameworkGroup" + }, + "description": "The frameworks the package supports, by family." + }, + "installTabs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/InstallSnippet" + }, + "description": "The install commands, one tab per tool." + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Owner names; empty unless accounts are enabled and the package has owners." + }, + "ownerAvatars": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The avatar address of each owner by name; empty when Gravatar is off or accounts are disabled." + }, + "manageUrl": { + "type": "string", + "description": "Where the management page is, when the caller may open it (an owner holding the Manage permission, or an administrator), else null.\r\nThe use case answers an application-relative address (`~/packages/…`); the controller resolves it against the path base.", + "nullable": true + }, + "iconUrl": { + "type": "string", + "description": "The icon address.", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "description": "The license address, null for a license expression or file.", + "nullable": true + }, + "packageDownloadUrl": { + "type": "string", + "description": "Where the package file is downloaded.", + "nullable": true + }, + "packageExplorerUrl": { + "type": "string", + "description": "This version on nuget.info, the web app of NuGet Package Explorer, as nuget.org links it. nuget.info always downloads from\r\nnuget.org, so the link only works for a package that is also published there.", + "nullable": true + } + }, + "description": "What the package page shows." + }, + "PackageType": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "nullable": true + }, + "version": { + "type": "string", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + } + }, + "PackageValidation": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "submissionId": { + "type": "string", + "nullable": true + }, + "packageId": { + "type": "string", + "nullable": true + }, + "packageVersion": { + "type": "string", + "description": "The normalized version.", + "nullable": true + }, + "packageKey": { + "type": "integer", + "description": "The indexed package, once the submission succeeds. Nullable so that the\r\nrelationship is additive; see PackageDeprecation.", + "format": "int32", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + }, + "type": { + "type": "string", + "description": "The validator's name, or string PackageValidation.IndexType.", + "nullable": true + }, + "state": { + "$ref": "#/components/schemas/PackageValidationState" + }, + "message": { + "type": "string", + "description": "Why the step failed, if it did.", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "completed": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + "description": "One step of validating a pushed package: a validator's verdict, or the final\r\nindexing step. A submission is every row sharing a string? PackageValidation.SubmissionId." + }, + "PackageValidationState": { + "enum": [ + "Pending", + "Succeeded", + "Failed" + ], + "type": "string" + }, + "PackageVersionEntry": { + "required": [ + "version", + "downloads", + "selected", + "lastUpdated" + ], + "type": "object", + "properties": { + "version": { + "type": "string", + "description": "The normalized version." + }, + "downloads": { + "type": "integer", + "description": "Its downloads.", + "format": "int64" + }, + "selected": { + "type": "boolean", + "description": "Whether it is the version shown." + }, + "lastUpdated": { + "type": "string", + "description": "When it was published.", + "format": "date-time" + } + }, + "description": "One row of the versions table of the package page." + }, + "PackageVulnerability": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "advisoryUrl": { + "type": "string", + "description": "The URL of the advisory describing the vulnerability.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "The severity, as the protocol numbers it: 0 low, 1 moderate, 2 high, 3 critical.", + "format": "int32" + }, + "versionRange": { + "type": "string", + "description": "The range of versions the advisory applies to.", + "nullable": true + }, + "source": { + "type": "string", + "description": "Who recorded it: null for an entry set through the metadata API or the Manage page, `osv` for one the vulnerability\r\nscanner wrote from a scan of this version. Setting the list by hand replaces the manual entries only; the next scan\r\nreplaces the scanner's.", + "nullable": true + }, + "packageKey": { + "type": "integer", + "description": "The key of the affected package version. Nullable for the same reason as on\r\nPackageDeprecation.", + "format": "int32", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + }, + "description": "A known vulnerability affecting a package version.\r\nSee: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info" + }, + "PackageVulnerabilityMetadata": { + "type": "object", + "properties": { + "advisoryUrl": { + "type": "string", + "description": "The URL of the advisory describing the vulnerability.", + "nullable": true + }, + "severity": { + "type": "string", + "description": "The severity: \"0\" low, \"1\" moderate, \"2\" high, \"3\" critical. A string in the\r\nregistration metadata, unlike the VulnerabilityInfo resource, which uses a number.", + "nullable": true + } + }, + "description": "A known vulnerability affecting a package version, as it appears in the package's\r\nregistration metadata.\r\n\r\nSee https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#vulnerabilities" + }, + "PasswordConfirmationForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The password, asked again.", + "nullable": true + } + }, + "description": "What a form that only re-asks the password posts (delete the account, turn two-factor off, reset the authenticator)." + }, + "PasswordForm": { + "required": [ + "password" + ], + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "A write that only asks the administrator's password again (approve an account, delete an organization)." + }, + "PatternPreview": { + "required": [ + "repositories", + "testPackage", + "test" + ], + "type": "object", + "properties": { + "repositories": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The NuGet repositories whose names match the repository patterns." + }, + "testPackage": { + "type": "string", + "description": "The package ID typed in the test box, if any.", + "nullable": true + }, + "test": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternTest" + } + ] + } + }, + "description": "The result of previewing repository and package patterns." + }, + "PatternTest": { + "required": [ + "matches", + "explanation" + ], + "type": "object", + "properties": { + "matches": { + "type": "boolean", + "description": "Whether the target applies to the package." + }, + "explanation": { + "type": "string", + "description": "Which pattern decided, in words." + } + }, + "description": "The outcome of PatternTest AccessPatterns.Test(IEnumerable<string>? include, IEnumerable<string>? exclude, string packageId)." + }, + "PermissionDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The target name (route).", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository names or globs, one per line.", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalName": { + "type": "string", + "description": "The user, group or organization name in the grant form.", + "nullable": true + }, + "target": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/TargetDetails" + } + ] + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternPreview" + } + ] + }, + "formActions": { + "$ref": "#/components/schemas/AccessAction" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the permission target screen (`/admin/permissions/{name}`) shows: the patterns, the preview and the grants." + }, + "PermissionsViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new target name.", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository names or `*` globs, one per line.", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line; none means all.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "project": { + "type": "string", + "description": "The project that administers the target, if any.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TargetSummary" + }, + "description": "The targets." + }, + "projects": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "description": "The projects a target can belong to." + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternPreview" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the permission targets screen (`/admin/permissions`) shows: the targets and the new-target form." + }, + "PermissionTargetForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new target's name (ignored for an existing target: the route names it).", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository names or `*` globs, one per line.", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line; none means all.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "project": { + "type": "string", + "description": "For a new target: the project that administers it, or null.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "principalType": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PrincipalType" + } + ] + }, + "principalName": { + "type": "string", + "description": "For an existing target: the principal name in the grant form (kept across a preview).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (saving the patterns of an existing target).", + "nullable": true + } + }, + "description": "The fields of the permission-target form (new target, or the patterns of an existing one) and its test box." + }, + "PrincipalRemoval": { + "required": [ + "type", + "principalId", + "password" + ], + "type": "object", + "properties": { + "type": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string", + "description": "The principal's id.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Removing a principal's grant or project role." + }, + "PrincipalType": { + "enum": [ + "User", + "Group", + "Organization" + ], + "type": "string", + "description": "Who a PermissionGrant or ProjectMember names." + }, + "ProfileViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The account's name.", + "nullable": true + }, + "isOrganization": { + "type": "boolean", + "description": "Whether the account is an organization." + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageDownloads" + }, + "description": "The owned packages with their downloads." + }, + "members": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The members of an organization." + }, + "isCurrentUser": { + "type": "boolean", + "description": "Whether the profile is the signed-in user's own." + }, + "avatarUrl": { + "type": "string", + "description": "The account's avatar address, or null when Gravatar is off.", + "nullable": true + } + }, + "description": "A user's or an organization's public page: the packages it owns." + }, + "ProjectCreation": { + "required": [ + "name", + "displayName" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The project's name.", + "nullable": true + }, + "displayName": { + "type": "string", + "description": "A name to show, or null.", + "nullable": true + } + }, + "description": "A new project." + }, + "ProjectDetails": { + "required": [ + "project", + "repositories", + "members", + "targets" + ], + "type": "object", + "properties": { + "project": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "repositories": { + "type": "array", + "items": { + "type": "string" + } + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectMemberInfo" + } + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TargetSummary" + } + } + }, + "description": "A project with its repositories, members and targets." + }, + "ProjectDetailViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The project name (route).", + "nullable": true + }, + "project": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectDetails" + } + ] + }, + "assignable": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The NuGet repositories not yet in this project, for the assignment picker." + }, + "targetName": { + "type": "string", + "description": "The new target name.", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository globs of the new target, one per line (they only ever reach the project repositories).", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Include globs of the new target.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Exclude globs of the new target.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PatternPreview" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the project screen (`/admin/projects/{name}`) shows: repositories, members and the project targets." + }, + "ProjectMemberForm": { + "required": [ + "type", + "principalName", + "role", + "password" + ], + "type": "object", + "properties": { + "type": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalName": { + "type": "string", + "description": "The principal's name.", + "nullable": true + }, + "role": { + "$ref": "#/components/schemas/ProjectRole" + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Giving a user or group a role in a project." + }, + "ProjectMemberInfo": { + "required": [ + "principalType", + "principalId", + "principal", + "role" + ], + "type": "object", + "properties": { + "principalType": { + "$ref": "#/components/schemas/PrincipalType" + }, + "principalId": { + "type": "string" + }, + "principal": { + "type": "string" + }, + "role": { + "$ref": "#/components/schemas/ProjectRole" + } + }, + "description": "A member of a project." + }, + "ProjectRepositoryForm": { + "required": [ + "repository", + "password" + ], + "type": "object", + "properties": { + "repository": { + "type": "string", + "description": "The repository's name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "Putting a repository in a project or taking it out." + }, + "ProjectRole": { + "enum": [ + "Viewer", + "Developer", + "Admin" + ], + "type": "string", + "description": "A member's role in a Project, applying to the project's repositories." + }, + "ProjectSummary": { + "required": [ + "key", + "name", + "displayName", + "repositoryCount", + "memberCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + }, + "displayName": { + "type": "string", + "nullable": true + }, + "repositoryCount": { + "type": "integer", + "format": "int32" + }, + "memberCount": { + "type": "integer", + "format": "int32" + } + }, + "description": "A project as the admin pages list it." + }, + "ProjectsViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The new project name.", + "nullable": true + }, + "displayName": { + "type": "string", + "description": "The new project display name.", + "nullable": true + }, + "projects": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "description": "The projects the signed-in user may open." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "isServerAdministrator": { + "type": "boolean", + "description": "Whether the signed-in user is a server administrator." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the projects screen (`/admin/projects`) shows: the projects the user may open and the new-project form." + }, + "ProjectTargetForm": { + "required": [ + "targetName", + "repositoryPatterns", + "includePatterns", + "excludePatterns", + "testPackage" + ], + "type": "object", + "properties": { + "targetName": { + "type": "string", + "description": "The new target's name.", + "nullable": true + }, + "repositoryPatterns": { + "type": "string", + "description": "Repository globs, one per line (they only ever reach the project's repositories).", + "nullable": true + }, + "includePatterns": { + "type": "string", + "description": "Package ID globs the target applies to, one per line.", + "nullable": true + }, + "excludePatterns": { + "type": "string", + "description": "Package ID globs the target leaves out, one per line.", + "nullable": true + }, + "testPackage": { + "type": "string", + "description": "A package ID to test the patterns with.", + "nullable": true + } + }, + "description": "The fields of a project's new permission target and its test box." + }, + "ReadinessReport": { + "required": [ + "checkedAt", + "probes" + ], + "type": "object", + "properties": { + "checkedAt": { + "type": "string", + "description": "When it ran (UTC).", + "format": "date-time" + }, + "probes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HealthProbe" + }, + "description": "Each probe." + }, + "isReady": { + "type": "boolean", + "description": "Every probe that decides readiness answered (an informational probe, the shared store, never takes the node out of rotation)." + }, + "problem": { + "type": "string", + "description": "The failing probes (informational ones too) as one line, or null.", + "nullable": true + } + }, + "description": "The result of the readiness check." + }, + "ReauthenticateViewModel": { + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "providers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalProviderInfo" + }, + "description": "The linked providers to pick from when the account has several (one button each); null otherwise.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after the provider answered; only a local URL is followed.", + "nullable": true + }, + "provider": { + "type": "string", + "description": "The id of the linked provider to sign in again with; empty takes the only linked one (several: the screen offers the choice).", + "nullable": true + } + }, + "description": "The \"confirm it is you\" screen of an account without a password. A request binds ReauthenticateForm, never this type." + }, + "RecoveryCodeLoginForm": { + "required": [ + "recoveryCode" + ], + "type": "object", + "properties": { + "recoveryCode": { + "type": "string", + "description": "The recovery code.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the recovery-code form posts." + }, + "RecoveryCodeLoginViewModel": { + "required": [ + "recoveryCode" + ], + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "recoveryCode": { + "type": "string", + "description": "The recovery code.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The second step of signing in with a recovery code. A request binds RecoveryCodeLoginForm, never this type." + }, + "RegisterForm": { + "required": [ + "userName", + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The wanted user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The password again. Never echoed.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the registration form posts." + }, + "RegisterViewModel": { + "required": [ + "userName", + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "awaitingApproval": { + "type": "boolean", + "description": "Whether the account was created but waits for an administrator (`Accounts:RequireApproval`)." + }, + "confirmationSent": { + "type": "boolean", + "description": "Whether a confirmation link was mailed." + }, + "emailRequired": { + "type": "boolean", + "description": "Whether the screen asks for an email address." + }, + "session": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/SessionModel" + } + ] + }, + "userName": { + "type": "string", + "description": "The wanted user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The password again. Never echoed.", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The registration screen. A request binds RegisterForm, never this type; the passwords are always empty here." + }, + "RemoteCacheOverview": { + "required": [ + "status", + "packageCount", + "packageIdCount" + ], + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/RemoteCacheStatus" + }, + "packageCount": { + "type": "integer", + "description": "Package versions stored.", + "format": "int32" + }, + "packageIdCount": { + "type": "integer", + "description": "Distinct package ids stored.", + "format": "int32" + }, + "storedBytes": { + "type": "integer", + "description": "Bytes of the blobs stored (a Docker repository: its layers); 0 when the format does not report it.", + "format": "int64", + "default": 0 + } + }, + "description": "What a remote repository holds and remembers." + }, + "RemoteCacheStatus": { + "required": [ + "metadataEntries", + "negativeEntries", + "hits", + "misses", + "negativeHits", + "staleServed", + "failures", + "lastSuccessUtc", + "lastFailureUtc", + "failingSinceUtc", + "lastError" + ], + "type": "object", + "properties": { + "metadataEntries": { + "type": "integer", + "description": "Cached answers of the upstream (version lists and metadata), expired ones included until used or purged.", + "format": "int32" + }, + "negativeEntries": { + "type": "integer", + "description": "Remembered \"the upstream does not have it\" answers still in force.", + "format": "int32" + }, + "hits": { + "type": "integer", + "description": "Answers served from the cache.", + "format": "int64" + }, + "misses": { + "type": "integer", + "description": "Questions that went to the upstream.", + "format": "int64" + }, + "negativeHits": { + "type": "integer", + "description": "Questions answered \"not found\" from the negative cache.", + "format": "int64" + }, + "staleServed": { + "type": "integer", + "description": "Expired answers served because the upstream could not be reached.", + "format": "int64" + }, + "failures": { + "type": "integer", + "description": "Failed attempts to reach the upstream.", + "format": "int64" + }, + "lastSuccessUtc": { + "type": "string", + "description": "The last time the upstream answered.", + "format": "date-time", + "nullable": true + }, + "lastFailureUtc": { + "type": "string", + "description": "The last time it could not be reached.", + "format": "date-time", + "nullable": true + }, + "failingSinceUtc": { + "type": "string", + "description": "When the current run of failures began, or null while it answers.", + "format": "date-time", + "nullable": true + }, + "lastError": { + "type": "string", + "description": "What failed, without URLs or credentials.", + "nullable": true + } + }, + "description": "What the cache of one remote repository looks like right now (in memory, per node; resets on restart)." + }, + "RemoteConnectionResult": { + "required": [ + "success", + "message", + "statusCode", + "elapsedMilliseconds" + ], + "type": "object", + "properties": { + "success": { + "type": "boolean", + "description": "Whether the upstream answered as the configured protocol requires." + }, + "message": { + "type": "string", + "description": "What was found or what failed, without URLs or credentials." + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status, when there was an answer.", + "format": "int32", + "nullable": true + }, + "elapsedMilliseconds": { + "type": "integer", + "description": "How long the attempt took.", + "format": "int64" + } + }, + "description": "The outcome of asking an upstream whether it answers." + }, + "RemoteFormModel": { + "type": "object", + "properties": { + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "url": { + "type": "string", + "description": "The upstream URL (V3 `index.json` or V2 feed, or an npm registry's base URL).", + "nullable": true + }, + "protocol": { + "$ref": "#/components/schemas/RemoteProtocol" + }, + "username": { + "type": "string", + "description": "The HTTP Basic user name, if the upstream needs one.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The HTTP Basic password or token; blank keeps the stored one. Input only: a screen never sends it back (the use cases clear it from every model they return).", + "nullable": true + }, + "clearPassword": { + "type": "boolean", + "description": "Remove the stored password on save." + }, + "metadataTtlSeconds": { + "type": "integer", + "description": "How long the upstream's answers are reused, in seconds (0 = ask every time).", + "format": "int32" + }, + "negativeTtlSeconds": { + "type": "integer", + "description": "How long \"not found\" is remembered, in seconds (0 = ask every time).", + "format": "int32" + }, + "downloadTimeoutSeconds": { + "type": "integer", + "description": "The download timeout in seconds.", + "format": "int32" + }, + "offline": { + "type": "boolean", + "description": "Never contact the upstream." + }, + "storeLocally": { + "type": "boolean", + "description": "Keep what is fetched (off = pass-through)." + }, + "hasPassword": { + "type": "boolean", + "description": "For display: whether a password is stored." + }, + "endpointFromMirror": { + "type": "boolean", + "description": "For display: URL, protocol and timeout are fixed because `Mirror:*` sets them." + } + }, + "description": "The fields of a remote repository's upstream settings as the create and edit pages post them (prefix\r\n`Remote`). The password is never rendered back: a blank one on save keeps the stored one." + }, + "RemoteProtocol": { + "enum": [ + "V3", + "V2", + "Npm", + "Maven", + "Docker" + ], + "type": "string", + "description": "The protocol a remote repository's upstream speaks." + }, + "RemoteRepositoryDetail": { + "required": [ + "repository", + "settings", + "hasPassword", + "isMirror" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "settings": { + "$ref": "#/components/schemas/RemoteRepositorySettings" + }, + "hasPassword": { + "type": "boolean", + "description": "Whether a password is stored." + }, + "isMirror": { + "type": "boolean", + "description": "Whether it is the string Repository.MirrorName repository the default repository fetches through while `Mirror:Enabled` is set (its URL, protocol and timeout then come from `Mirror:*`)." + } + }, + "description": "A remote repository as the administration pages edit it." + }, + "RemoteRepositorySettings": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The upstream: a V3 `index.json` URL or a V2 feed URL, the base URL of an npm registry, the root of a Maven repository or the address of a Docker registry (absolute http or https).", + "nullable": true + }, + "protocol": { + "$ref": "#/components/schemas/RemoteProtocol" + }, + "username": { + "type": "string", + "description": "The user name sent with HTTP Basic to the upstream's own host, if any. An npm upstream with a password and no user name\r\ngets the password as a bearer token (npm's `_authToken`) instead. A Docker upstream gets the pair at its token service\r\n(HTTP Basic, the `docker login` flow) or, when it asks for Basic itself, at its own host; a password with no user name\r\nis sent as a ready-made bearer token to the registry's own host.", + "nullable": true + }, + "protectedPassword": { + "type": "string", + "description": "The password as stored (protected). Opaque to everything but RemoteSettingsCodec.", + "nullable": true + }, + "metadataTtlSeconds": { + "type": "integer", + "description": "How long the upstream's version list and metadata of a package are reused before it is asked again. 0 asks\r\nevery time (what the mirror always did).", + "format": "int32" + }, + "negativeTtlSeconds": { + "type": "integer", + "description": "How long \"the upstream does not have it\" (404) is remembered. 0 asks every time.", + "format": "int32" + }, + "offline": { + "type": "boolean", + "description": "Offline mode: the upstream is never contacted; only what is already stored (and cached in memory) is served." + }, + "storeLocally": { + "type": "boolean", + "description": "Whether packages fetched from the upstream are stored (database and files) so later requests, and requests\r\nwhile the upstream is down, are served locally. Off, the repository is a pass-through: metadata comes from the\r\nupstream (cached by int RemoteRepositorySettings.MetadataTtlSeconds), downloads stream through and nothing is kept (so search\r\nand the package pages stay empty)." + }, + "downloadTimeoutSeconds": { + "type": "integer", + "description": "The time before a download from the upstream times out.", + "format": "int32" + } + }, + "description": "What a RepositoryKind.Remote repository knows about its upstream: kept as JSON in\r\nstring? Repository.Settings. The password never appears in clear there: it is stored as\r\nstring? RemoteRepositorySettings.ProtectedPassword (see IRemoteCredentialProtector) and string? RemoteRepositorySettings.Password only\r\nexists in memory." + }, + "RemoveOrganizationMemberForm": { + "type": "object", + "properties": { + "organization": { + "type": "string", + "description": "The organization.", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The member to remove.", + "nullable": true + } + }, + "description": "What the \"remove a member\" (or \"leave\") form posts." + }, + "RemoveSignInProviderForm": { + "required": [ + "id", + "password" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Removing a named OpenID Connect provider saved on the Settings screen." + }, + "ReplicationBody": { + "required": [ + "form", + "password" + ], + "type": "object", + "properties": { + "form": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationForm" + } + ] + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Creating, saving or testing a replication, or any write of it that asks the password." + }, + "ReplicationConfig": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "description": "Unique, AccessNames rules.", + "nullable": true + }, + "repositoryKey": { + "type": "integer", + "description": "The local int Repository.Key: a local (not remote, not virtual) repository.", + "format": "int32" + }, + "direction": { + "$ref": "#/components/schemas/ReplicationDirection" + }, + "peerUrl": { + "type": "string", + "description": "The peer server's base address (`https://other.example/`), not a repository feed.", + "nullable": true + }, + "peerRepository": { + "type": "string", + "description": "The peer's repository (`default` or its name); it must be of the same format.", + "nullable": true + }, + "enabled": { + "type": "boolean", + "description": "A disabled configuration is never run by the schedule or a deploy; a manual run is refused." + }, + "onDeploy": { + "type": "boolean", + "description": "Push only: a deploy to the local repository starts a run (after a short quiet period)." + }, + "scheduleMinutes": { + "type": "integer", + "description": "Run every this many minutes. Null: only when started (or on deploy).", + "format": "int32", + "nullable": true + }, + "propagateDeletes": { + "type": "boolean", + "description": "What was replicated and is later deleted at the source is deleted at the target too (only items this configuration copied)." + }, + "conflict": { + "$ref": "#/components/schemas/ReplicationConflict" + }, + "scheduleStart": { + "type": "string", + "description": "When the schedule was set or the configuration enabled; the first scheduled run is due this long after it.", + "format": "date-time", + "nullable": true + }, + "lastRun": { + "type": "string", + "description": "When the last run started (the schedule counts from the later of this and DateTime? ReplicationConfig.ScheduleStart).", + "format": "date-time", + "nullable": true + }, + "lastResult": { + "type": "string", + "description": "One line about the last run.", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "modified": { + "type": "string", + "format": "date-time" + } + }, + "description": "One replication relationship: a local repository and a repository of another BaGet server, copied in one direction. Not\r\nrepository-scoped (the administrator lists configurations across repositories). Its `RepositoryKey` is a Restrict foreign key, and\r\nso is `ConfigKey` of its runs and ledger: deleting the repository deletes its configurations, runs and ledger first (code, not cascade)." + }, + "ReplicationConfigView": { + "required": [ + "config", + "repository", + "format", + "hasApiKey", + "lastRun" + ], + "type": "object", + "properties": { + "config": { + "$ref": "#/components/schemas/ReplicationConfig" + }, + "repository": { + "type": "string", + "description": "The local repository's name, or null when it no longer exists.", + "nullable": true + }, + "format": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryFormat" + } + ] + }, + "hasApiKey": { + "type": "boolean", + "description": "Whether a key is stored." + }, + "lastRun": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationRun" + } + ] + } + }, + "description": "A configuration with the names the page shows; the API key is never part of it." + }, + "ReplicationConfigViewModel": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The configuration's key (route).", + "format": "int32" + }, + "form": { + "$ref": "#/components/schemas/ReplicationForm" + }, + "view": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationConfigView" + } + ] + }, + "runs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReplicationRun" + }, + "description": "The log, newest first." + }, + "job": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationJobStatus" + } + ] + }, + "test": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ReplicationTestResult" + } + ] + }, + "localItems": { + "type": "integer", + "description": "How many items the local repository holds, or null when it could not be listed.", + "format": "int32", + "nullable": true + }, + "running": { + "type": "boolean", + "description": "Whether a run is going here (the page refreshes itself)." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The local repositories a replication can name." + }, + "resumable": { + "$ref": "#/components/schemas/ReplicationRun" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What one replication's screen (`/admin/replication/{key}`) shows." + }, + "ReplicationConflict": { + "enum": [ + "TargetWins", + "SourceWins" + ], + "type": "string", + "description": "What happens when both sides hold the same item with different content." + }, + "ReplicationDirection": { + "enum": [ + "Push", + "Pull" + ], + "type": "string", + "description": "Which way a ReplicationConfig copies." + }, + "ReplicationForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "nullable": true + }, + "repository": { + "type": "string", + "nullable": true + }, + "direction": { + "$ref": "#/components/schemas/ReplicationDirection" + }, + "peerUrl": { + "type": "string", + "nullable": true + }, + "peerRepository": { + "type": "string", + "nullable": true + }, + "apiKey": { + "type": "string", + "description": "The peer's API key (write only).", + "nullable": true + }, + "clearApiKey": { + "type": "boolean", + "description": "Forget the stored key." + }, + "enabled": { + "type": "boolean" + }, + "onDeploy": { + "type": "boolean" + }, + "scheduleMinutes": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "propagateDeletes": { + "type": "boolean" + }, + "conflict": { + "$ref": "#/components/schemas/ReplicationConflict" + } + }, + "description": "What the replication form posts (`Form.*`): a ReplicationConfig as a person types it. The peer's API key is write\r\nonly: it is never filled back into a page; an empty field keeps the stored key." + }, + "ReplicationJobStatus": { + "type": "object", + "properties": { + "configKey": { + "type": "integer", + "format": "int32" + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "running": { + "type": "boolean", + "description": "True while the run is going." + }, + "refusal": { + "type": "string", + "description": "Why the job did not even begin a run (read-only server, disabled configuration, lease held elsewhere), or null.", + "nullable": true + } + }, + "description": "What the page knows of a replication started since the server began (in memory); the log table is the durable record." + }, + "ReplicationRun": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "configKey": { + "type": "integer", + "description": "The int ReplicationConfig.Key.", + "format": "int32" + }, + "status": { + "$ref": "#/components/schemas/ReplicationRunStatus" + }, + "trigger": { + "type": "string", + "description": "`manual`, `resume`, `schedule` or `deploy`.", + "nullable": true + }, + "actor": { + "type": "string", + "description": "The administrator, or `scheduler`.", + "nullable": true + }, + "resumedFrom": { + "type": "integer", + "description": "The interrupted or failed run this one continues, when started with Resume.", + "format": "int32", + "nullable": true + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "examined": { + "type": "integer", + "description": "Items the plan looked at (both sides listed).", + "format": "int32" + }, + "transferred": { + "type": "integer", + "description": "Items copied to the target.", + "format": "int32" + }, + "skipped": { + "type": "integer", + "description": "Items the target already had.", + "format": "int32" + }, + "deleted": { + "type": "integer", + "description": "Items deleted at the target because they were deleted at the source.", + "format": "int32" + }, + "conflicts": { + "type": "integer", + "description": "Items held differently on both sides that were left alone (target wins) or replaced (source wins).", + "format": "int32" + }, + "failures": { + "type": "integer", + "format": "int32" + }, + "bytes": { + "type": "integer", + "description": "Bytes of artifact content sent or received.", + "format": "int64" + }, + "error": { + "type": "string", + "description": "Why the run failed as a whole, or null.", + "nullable": true + }, + "detail": { + "type": "string", + "description": "The first failures and conflicts, one per line.", + "nullable": true + } + }, + "description": "One run of a configuration: the replication log." + }, + "ReplicationRunStatus": { + "enum": [ + "Running", + "Succeeded", + "Failed", + "Interrupted" + ], + "type": "string", + "description": "How a ReplicationRun ended." + }, + "ReplicationTestResult": { + "required": [ + "ok", + "message", + "elapsedMilliseconds", + "peerFormat", + "peerItems" + ], + "type": "object", + "properties": { + "ok": { + "type": "boolean", + "description": "Whether the peer answered as a BaGet server with this repository." + }, + "message": { + "type": "string", + "description": "A sentence for the administrator (never the key)." + }, + "elapsedMilliseconds": { + "type": "integer", + "description": "How long it took.", + "format": "int64" + }, + "peerFormat": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryFormat" + } + ] + }, + "peerItems": { + "type": "integer", + "description": "How many items it holds, when it answered.", + "format": "int32", + "nullable": true + } + }, + "description": "What Task<ReplicationTestResult> IReplicationAdministration.TestAsync(ReplicationInput input, CancellationToken cancellationToken) found." + }, + "ReplicationViewModel": { + "type": "object", + "properties": { + "form": { + "$ref": "#/components/schemas/ReplicationForm" + }, + "replications": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReplicationConfigView" + }, + "description": "Every replication." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The local repositories a replication can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the replications screen (`/admin/replication`) shows: every replication and the form that creates one." + }, + "ReportAbuseForm": { + "required": [ + "reason", + "details" + ], + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "One of string[] AbuseReport.Reasons.", + "nullable": true + }, + "details": { + "maxLength": 4000, + "minLength": 0, + "type": "string", + "description": "What the reporter saw.", + "nullable": true + }, + "reporterEmail": { + "maxLength": 256, + "minLength": 0, + "type": "string", + "description": "The address of the reporter, optional.", + "nullable": true + } + }, + "description": "What the reporter fills in. The field names (Reason, Details, ReporterEmail) are the contract of the form and of the JSON body." + }, + "ReportAbuseScreen": { + "required": [ + "id", + "version", + "canReport", + "submitted", + "form" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The package version.", + "nullable": true + }, + "canReport": { + "type": "boolean", + "description": "Reports are kept in the database, which Azure Table storage cannot do." + }, + "submitted": { + "type": "boolean", + "description": "True once the report was recorded." + }, + "form": { + "$ref": "#/components/schemas/ReportAbuseForm" + } + }, + "description": "The report-abuse screen: the package it is about, what was typed, and whether the report was recorded." + }, + "RepositoriesViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name for the repository to create.", + "nullable": true + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositorySummary" + }, + "description": "The repositories." + }, + "canCreate": { + "type": "boolean", + "description": "Whether the database can hold more than the default repository." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "description": "Why the last action was refused.", + "nullable": true + }, + "format": { + "type": "string", + "description": "The format to keep selected after a refused creation.", + "nullable": true + }, + "filterFormat": { + "type": "string", + "description": "The format the list is narrowed to (`?format=`), or null.", + "nullable": true + }, + "filterKind": { + "type": "string", + "description": "The kind the list is narrowed to (`?kind=`), or null.", + "nullable": true + }, + "filterName": { + "type": "string", + "description": "The name fragment the list is narrowed to (`?q=`), or null.", + "nullable": true + }, + "allFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "Every format this server knows, for the list filter." + }, + "remoteFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "The formats a remote repository can be created for." + }, + "virtualFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "The formats a virtual repository can be created for." + }, + "otherFormats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryFormatChoice" + }, + "description": "The formats other than NuGet that can be created here, with their form fields." + }, + "deployable": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The virtual repositories that have a deploy repository, so take uploads (a remote one takes none)." + }, + "feeds": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The feed address of each repository, by repository name." + }, + "baseUrls": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The base address of each repository (where its format's routes start, ends with a slash), by repository name." + }, + "links": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatLink" + } + }, + "description": "The links its format contributes for each repository (browse, upload...), without the upload link where it takes none, by repository name." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the repositories screen (`/admin/repositories`) shows: the repositories with their feed addresses, the list filter and\r\nthe create forms. The posted fields of the create forms (string? RepositoriesViewModel.Name, RemoteFormModel RepositoriesViewModel.Remote) live here too, so a refused\r\ncreation shows again what was typed (the typed upstream password excepted: it is never sent back)." + }, + "RepositoryAccessRow": { + "required": [ + "repository", + "explanation" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "explanation": { + "$ref": "#/components/schemas/AccessExplanation" + } + }, + "description": "One repository with what a user may do there and the grants behind it (the account and user pages)." + }, + "RepositoryAccessSummary": { + "required": [ + "repository", + "anonymousRead", + "project", + "modelAvailable", + "holders" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "anonymousRead": { + "type": "boolean", + "description": "The repository's anonymous-read switch." + }, + "project": { + "type": "string", + "description": "The name of the project the repository belongs to, if any.", + "nullable": true + }, + "modelAvailable": { + "type": "boolean", + "description": "False where there is no access model (Azure Table): everyone reads, any authenticated\r\n caller writes, subject to ownership." + }, + "holders": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AccessReason" + }, + "description": "Every grant and project role that applies to the repository." + } + }, + "description": "Who holds what in one repository (Task<RepositoryAccessSummary> IAccessEvaluator.DescribeAsync(RepositoryInfo repository, CancellationToken cancellationToken))." + }, + "RepositoryCreateForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the repository to create.", + "nullable": true + }, + "format": { + "type": "string", + "description": "The format (`Npm`, `Maven`, `Docker`...); blank is NuGet where a format may be omitted.", + "nullable": true + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read the repository. Null: the default (a local or virtual repository is readable by anyone; a remote\r\none only when it has no credentials).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (creating a remote repository asks for it).", + "nullable": true + }, + "fields": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "The format's own create fields (string FormatCreateField.Name to value) of a local repository of a format other than NuGet.", + "nullable": true + } + }, + "description": "The body of the create forms of the repositories screen (`POST /api/ui/admin/repositories` and its `create/...` handlers). Which fields\r\na handler reads is stated on its use case method; the others are ignored." + }, + "RepositoryDeleteViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The repository's name (route).", + "nullable": true + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositorySummary" + } + ] + }, + "referencedBy": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The virtual repositories that list this repository as a member (the deletion is refused while there are any)." + }, + "error": { + "type": "string", + "description": "Why the deletion was refused.", + "nullable": true + } + }, + "description": "What the delete-repository screen (`/admin/repositories/{name}/delete`) shows." + }, + "RepositoryEditRequest": { + "type": "object", + "properties": { + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read the repository." + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "previewPackageId": { + "type": "string", + "description": "The package id to resolve in the preview.", + "nullable": true + }, + "previewVersion": { + "type": "string", + "description": "The package version to resolve in the preview.", + "nullable": true + }, + "packageId": { + "type": "string", + "description": "The package id to purge from the cache.", + "nullable": true + }, + "packageVersion": { + "type": "string", + "description": "The version to purge (blank = every version).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (saving, testing and purging a remote repository ask for it).", + "nullable": true + }, + "member": { + "type": "string", + "description": "The member to add, remove or move.", + "nullable": true + }, + "direction": { + "type": "string", + "description": "`up` or `down`.", + "nullable": true + }, + "deploy": { + "type": "string", + "description": "The member that receives uploads (blank: none).", + "nullable": true + }, + "policy": { + "type": "string", + "description": "The versions a Maven repository accepts (`Releases`, `Snapshots`, `Both`).", + "nullable": true + }, + "redeploy": { + "type": "string", + "description": "Whether a Maven release may be redeployed (`Yes`/`No`).", + "nullable": true + }, + "snapshotBuilds": { + "type": "string", + "description": "How many snapshot builds a Maven repository keeps.", + "nullable": true + } + }, + "description": "The body of every action of the repository screen (`/api/ui/admin/repositories/{name}/...`), the JSON twin of what the page's forms post. Which fields\r\nan action reads is stated on its use case method; the others are ignored." + }, + "RepositoryEditViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The repository's name (route).", + "nullable": true + }, + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read the repository." + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositorySummary" + } + ] + }, + "remote": { + "$ref": "#/components/schemas/RemoteFormModel" + }, + "remoteDetail": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteRepositoryDetail" + } + ] + }, + "mavenSettings": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/MavenRepositorySettings" + } + ] + }, + "cache": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteCacheOverview" + } + ] + }, + "virtualDetail": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/VirtualRepositoryDetail" + } + ] + }, + "memberCandidates": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories that can still be added to a virtual repository." + }, + "referencedBy": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The virtual repositories that list this repository as a member." + }, + "previewPackageId": { + "type": "string", + "description": "The package id to resolve in the preview.", + "nullable": true + }, + "previewVersion": { + "type": "string", + "description": "The package version to resolve in the preview.", + "nullable": true + }, + "preview": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ResolutionPreview" + } + ] + }, + "testResult": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteConnectionResult" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "description": "Why the last action was refused.", + "nullable": true + }, + "packageId": { + "type": "string", + "description": "The package id to purge from the cache.", + "nullable": true + }, + "packageVersion": { + "type": "string", + "description": "The version to purge (blank = every version).", + "nullable": true + }, + "access": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryAccessSummary" + } + ] + }, + "browseScreen": { + "$ref": "#/components/schemas/ScreenRef" + }, + "feedUrl": { + "type": "string", + "description": "The repository's feed address." + }, + "mirrorRepository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RemoteRepositoryDetail" + } + ] + }, + "mirrorActive": { + "type": "boolean", + "description": "Whether `Mirror:Enabled` makes the default repository fetch through RemoteRepositoryDetail? RepositoryEditViewModel.MirrorRepository." + }, + "packageWord": { + "type": "string", + "description": "The name of what a package is called in this repository's format (shown in the labels).", + "nullable": true + }, + "versionWord": { + "type": "string", + "description": "What the \"version\" of a package is called in this repository's format (a Docker image has a tag or a digest).", + "nullable": true + }, + "packageLabel": { + "type": "string", + "description": "The label of the field that names a package (a Docker image is an image name).", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the repository screen (`/admin/repositories/{name}`) shows: the repository, its access summary and, by kind, its\r\nupstream and cache (remote), members and preview (virtual) or Maven settings. The posted fields (anonymous read, upstream, preview\r\nand purge inputs) live here too, so a refused action shows again what was typed." + }, + "RepositoryFormat": { + "enum": [ + "NuGet", + "Npm", + "Maven", + "Docker" + ], + "type": "string", + "description": "The package format a Repository serves. Stored as its name, so a value may be appended\r\nbut never renumbered or renamed." + }, + "RepositoryFormatChoice": { + "required": [ + "format", + "displayName", + "createFields" + ], + "type": "object", + "properties": { + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "displayName": { + "type": "string", + "description": "Its name for people (`npm`, `Maven`)." + }, + "createFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FormatCreateField" + }, + "description": "What the administrator fills in to create a local repository of it, besides the name." + } + }, + "description": "A package format a repository can be created for, with the extra fields its create form asks (the JSON form of an IFormatModule)." + }, + "RepositoryInfo": { + "required": [ + "key", + "name", + "format", + "kind" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The int Repository.Key.", + "format": "int32" + }, + "name": { + "type": "string", + "description": "The string? Repository.Name." + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "kind": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "isDefault": { + "type": "boolean", + "description": "Whether this is the string Repository.DefaultName repository." + }, + "pathPrefix": { + "type": "string", + "description": "The path in front of this repository's routes, feeds and pages, without a leading slash: nothing for the\r\ndefault repository (served at `/`), else `r/{name}/`.", + "nullable": true + } + }, + "description": "What a request, job or command needs to know about the repository it works in: immutable, and small enough to\r\ncopy around." + }, + "RepositoryKind": { + "enum": [ + "Local", + "Remote", + "Virtual" + ], + "type": "string", + "description": "How a Repository gets its content. Stored as its name." + }, + "RepositoryPackages": { + "required": [ + "repository", + "packages" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnedPackage" + } + } + }, + "description": "The packages the user owns in one repository." + }, + "RepositorySummary": { + "required": [ + "key", + "name", + "format", + "kind", + "anonymousRead", + "created", + "packageCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The int Repository.Key.", + "format": "int32" + }, + "name": { + "type": "string", + "description": "The string? Repository.Name." + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "kind": { + "$ref": "#/components/schemas/RepositoryKind" + }, + "anonymousRead": { + "type": "boolean", + "description": "Whether requests without credentials may read it." + }, + "created": { + "type": "string", + "description": "When the repository was created (UTC).", + "format": "date-time" + }, + "packageCount": { + "type": "integer", + "description": "How many package versions it holds.", + "format": "int32" + }, + "isDefault": { + "type": "boolean", + "description": "Whether this is the string Repository.DefaultName repository, which can be neither renamed nor deleted." + } + }, + "description": "A repository as the administration pages list it." + }, + "ResetPasswordForm": { + "required": [ + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "userId": { + "type": "string", + "description": "The account named by the link.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The encoded reset token of the link.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The new password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The new password again. Never echoed.", + "nullable": true + } + }, + "description": "What the new-password form behind a reset link posts." + }, + "ResetPasswordViewModel": { + "required": [ + "password", + "confirmPassword" + ], + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "userId": { + "type": "string", + "description": "The account named by the link.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The encoded reset token of the link.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The new password. Never echoed.", + "nullable": true + }, + "confirmPassword": { + "type": "string", + "description": "The new password again. Never echoed.", + "nullable": true + } + }, + "description": "The screen behind the link of a password reset email. A request binds ResetPasswordForm, never this type." + }, + "ResolutionOutcome": { + "enum": [ + "Stored", + "WouldFetch", + "NotFound", + "Unavailable", + "NotAsked", + "Offline" + ], + "type": "string", + "description": "What asking one member about a package version found." + }, + "ResolutionPreview": { + "required": [ + "packageId", + "version", + "steps", + "answers" + ], + "type": "object", + "properties": { + "packageId": { + "type": "string", + "description": "The package id asked about (`group:artifact` for Maven)." + }, + "version": { + "type": "string", + "description": "The version asked about, as written for the format (a NuGet or npm version in its normalized form; a Maven version as typed)." + }, + "steps": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ResolutionStep" + }, + "description": "The effective members in resolution order and what each found." + }, + "answers": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + } + }, + "description": "Where a package version would come from, member by member." + }, + "ResolutionStep": { + "required": [ + "member", + "outcome" + ], + "type": "object", + "properties": { + "member": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "outcome": { + "$ref": "#/components/schemas/ResolutionOutcome" + } + }, + "description": "One member's part in ResolutionPreview." + }, + "RetentionHoldForm": { + "required": [ + "holdRepository", + "holdName", + "holdVersion", + "reason" + ], + "type": "object", + "properties": { + "holdRepository": { + "type": "string", + "description": "The repository of the hold.", + "nullable": true + }, + "holdName": { + "type": "string", + "description": "The artifact name.", + "nullable": true + }, + "holdVersion": { + "type": "string", + "description": "The version; empty for every version.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "Why (a case number, a ticket).", + "nullable": true + } + }, + "description": "Placing a legal hold." + }, + "RetentionHoldRemoval": { + "required": [ + "key", + "password" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The hold's number.", + "format": "int32" + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Lifting a legal hold." + }, + "RetentionHoldsViewModel": { + "type": "object", + "properties": { + "repository": { + "type": "string", + "description": "Only the holds of this repository (query).", + "nullable": true + }, + "holdRepository": { + "type": "string", + "description": "The repository of the new hold.", + "nullable": true + }, + "holdName": { + "type": "string", + "description": "The artifact name of the new hold.", + "nullable": true + }, + "holdVersion": { + "type": "string", + "description": "The version of the new hold; empty for every version.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "Why (a case number, a ticket).", + "nullable": true + }, + "holds": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionHoldView" + }, + "description": "The holds." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories a hold can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the legal holds screen (`/admin/retention/holds`) shows." + }, + "RetentionHoldView": { + "required": [ + "key", + "repositoryKey", + "repository", + "name", + "version", + "reason", + "createdBy", + "created" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "format": "int32" + }, + "repository": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "reason": { + "type": "string", + "nullable": true + }, + "createdBy": { + "type": "string", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + } + }, + "description": "A legal hold with its repository's name." + }, + "RetentionJobState": { + "enum": [ + "Running", + "Succeeded", + "Failed" + ], + "type": "string" + }, + "RetentionJobStatus": { + "type": "object", + "properties": { + "policyKey": { + "type": "integer", + "format": "int32" + }, + "dryRun": { + "type": "boolean" + }, + "state": { + "$ref": "#/components/schemas/RetentionJobState" + }, + "actor": { + "type": "string", + "description": "The administrator, or `scheduler`.", + "nullable": true + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "report": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionReport" + } + ] + }, + "error": { + "type": "string", + "description": "Why the run failed as a whole, or null.", + "nullable": true + } + }, + "description": "The last run of a policy since the server started (in memory)." + }, + "RetentionOutcome": { + "enum": [ + "Planned", + "Deleted", + "Held", + "Failed" + ], + "type": "string", + "description": "What happened (or, in a dry run, would happen) to one selected version." + }, + "RetentionPolicy": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string", + "description": "Unique, AccessNames rules.", + "nullable": true + }, + "repositoryKey": { + "type": "integer", + "description": "The int Repository.Key the policy applies to, or null when it applies to a project.", + "format": "int32", + "nullable": true + }, + "projectKey": { + "type": "integer", + "description": "The int Project.Key: the policy applies to every repository of the project. Exactly one of the two keys is set.", + "format": "int32", + "nullable": true + }, + "enabled": { + "type": "boolean", + "description": "A disabled policy is never run by the schedule and refuses a manual run (a dry run still reports)." + }, + "namePatterns": { + "type": "string", + "description": "Globs (AccessPatterns, one per line) naming the artifacts the policy looks at (package ids, npm names, Maven\r\n`group:artifact`, image names); empty means every artifact.", + "nullable": true + }, + "keepLast": { + "type": "integer", + "description": "Keep this many newest versions of each artifact (by publish time); older ones are selected. Null: rule off.", + "format": "int32", + "nullable": true + }, + "olderThanDays": { + "type": "integer", + "description": "Select versions published more than this many days ago. Null: rule off.", + "format": "int32", + "nullable": true + }, + "unusedDays": { + "type": "integer", + "description": "Select versions not downloaded for this many days (the publish time counts when never downloaded). Null: rule off.", + "format": "int32", + "nullable": true + }, + "prereleaseOnly": { + "type": "boolean", + "description": "The age and count rules look at prerelease versions (NuGet pre-release, npm prerelease, Maven snapshot) only." + }, + "cacheLimitBytes": { + "type": "integer", + "description": "Remote repositories only: when what the repository cached is larger than this many bytes, the least recently used versions are\r\nselected until it fits. Null: rule off.", + "format": "int64", + "nullable": true + }, + "untaggedAfterDays": { + "type": "integer", + "description": "Docker only: select manifests no tag, index or referrer relationship points at that were pushed more than this many days ago.\r\nNull: rule off.", + "format": "int32", + "nullable": true + }, + "collectGarbage": { + "type": "boolean", + "description": "Docker only: run the garbage collection (IOciGarbageCollector) after the rules, to free the blobs." + }, + "scheduleHours": { + "type": "integer", + "description": "Run every this many hours (a real run, by the background worker). Null: only when an administrator starts it.", + "format": "int32", + "nullable": true + }, + "scheduleStart": { + "type": "string", + "description": "When the schedule was set or the policy enabled; the first scheduled run is due this long after it.", + "format": "date-time", + "nullable": true + }, + "lastRun": { + "type": "string", + "description": "When the last real run started (the schedule counts from the later of this and DateTime? RetentionPolicy.ScheduleStart).", + "format": "date-time", + "nullable": true + }, + "lastResult": { + "type": "string", + "description": "One line about the last real run.", + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time" + }, + "unusedSince": { + "type": "string", + "description": "Since when the unused rule has been watching the policy's scope (set when the rule is enabled or changed, or the repository,\r\nproject or name patterns change; null on rows that predate it, which fall back to DateTime RetentionPolicy.Created). A version never\r\ndownloaded counts as unused from the later of its publication and this time: downloads are recorded only while watched.", + "format": "date-time", + "nullable": true + }, + "modified": { + "type": "string", + "format": "date-time" + } + }, + "description": "A retention policy: which stored versions of one repository (or of every repository of a project) are deleted, and when.\r\nA version is deleted when any enabled rule selects it and no RetentionHold covers it. Not repository-scoped:\r\nthe administrator lists policies across repositories. `RepositoryKey` and `ProjectKey` are optional Restrict foreign keys;\r\ndeleting a repository or a project deletes its policies first." + }, + "RetentionPolicyBody": { + "required": [ + "form", + "password" + ], + "type": "object", + "properties": { + "form": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyForm" + } + ] + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Creating or saving a retention policy, or any write of it that asks the password." + }, + "RetentionPolicyForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "nullable": true + }, + "scopeKind": { + "type": "string", + "description": "`repository` or `project`.", + "nullable": true + }, + "scopeName": { + "type": "string", + "description": "The repository or project name.", + "nullable": true + }, + "enabled": { + "type": "boolean" + }, + "namePatterns": { + "type": "string", + "nullable": true + }, + "keepLast": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "olderThanDays": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "unusedDays": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "prereleaseOnly": { + "type": "boolean" + }, + "cacheLimitMb": { + "type": "integer", + "description": "The remote cache limit in MiB.", + "format": "int64", + "nullable": true + }, + "untaggedAfterDays": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "collectGarbage": { + "type": "boolean" + }, + "scheduleHours": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What the policy form posts (`Form.*`): the rules of a RetentionPolicy in the units a person types\r\n(the cache limit in MiB). RetentionPolicyInput RetentionPolicyForm.ToInput(int key) turns it into the administration's input." + }, + "RetentionPolicyView": { + "required": [ + "policy", + "repository", + "project", + "targets" + ], + "type": "object", + "properties": { + "policy": { + "$ref": "#/components/schemas/RetentionPolicy" + }, + "repository": { + "type": "string", + "description": "The repository name, when it applies to one.", + "nullable": true + }, + "project": { + "type": "string", + "description": "The project name, when it applies to a project.", + "nullable": true + }, + "targets": { + "type": "integer", + "description": "How many repositories it currently applies to.", + "format": "int32" + } + }, + "description": "A policy with the name of what it applies to." + }, + "RetentionPolicyViewModel": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The policy's key (route).", + "format": "int32" + }, + "form": { + "$ref": "#/components/schemas/RetentionPolicyForm" + }, + "view": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionPolicyView" + } + ] + }, + "status": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RetentionJobStatus" + } + ] + }, + "running": { + "type": "boolean", + "description": "Whether a run is in progress (the page refreshes itself)." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories a policy can name." + }, + "projectNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of the projects a policy can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What one retention policy's screen (`/admin/retention/{key}`) shows." + }, + "RetentionReport": { + "type": "object", + "properties": { + "policyKey": { + "type": "integer", + "format": "int32" + }, + "policyName": { + "type": "string" + }, + "dryRun": { + "type": "boolean", + "description": "Whether nothing was changed." + }, + "started": { + "type": "string", + "format": "date-time" + }, + "finished": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionRepositoryReport" + }, + "nullable": true + }, + "selected": { + "type": "integer", + "format": "int32" + }, + "deleted": { + "type": "integer", + "format": "int32" + }, + "held": { + "type": "integer", + "format": "int32" + }, + "failed": { + "type": "integer", + "format": "int32" + }, + "bytes": { + "type": "integer", + "format": "int64" + }, + "summary": { + "type": "string", + "description": "One line for the policy page, the job status and the audit log.", + "nullable": true + } + }, + "description": "The result of running (or dry-running) a policy over its repositories." + }, + "RetentionReportItem": { + "required": [ + "repository", + "name", + "version", + "published", + "lastDownloaded", + "size", + "rules", + "outcome", + "error" + ], + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "published": { + "type": "string", + "format": "date-time" + }, + "lastDownloaded": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "size": { + "type": "integer", + "format": "int64", + "nullable": true + }, + "rules": { + "type": "string" + }, + "outcome": { + "$ref": "#/components/schemas/RetentionOutcome" + }, + "error": { + "type": "string", + "nullable": true + } + }, + "description": "One version in a report." + }, + "RetentionRepositoryReport": { + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "examined": { + "type": "integer", + "description": "Versions looked at (matching the policy's name patterns).", + "format": "int32" + }, + "selected": { + "type": "integer", + "description": "Versions selected by a rule and not held (dry run: to be deleted).", + "format": "int32" + }, + "deleted": { + "type": "integer", + "description": "Versions deleted (always 0 in a dry run).", + "format": "int32" + }, + "held": { + "type": "integer", + "description": "Versions a rule selected that a legal hold kept.", + "format": "int32" + }, + "failed": { + "type": "integer", + "description": "Versions whose deletion failed.", + "format": "int32" + }, + "bytes": { + "type": "integer", + "description": "Bytes of the deleted versions (dry run: of the selected ones), as far as known.", + "format": "int64" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionReportItem" + }, + "nullable": true + }, + "itemsTruncated": { + "type": "boolean" + }, + "notes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Rules that did not apply, and similar remarks.", + "nullable": true + }, + "garbageCollection": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/OciGcReport" + } + ] + }, + "error": { + "type": "string", + "description": "Why the repository could not be processed, or null.", + "nullable": true + } + }, + "description": "The part of a RetentionReport that concerns one repository." + }, + "RetentionViewModel": { + "type": "object", + "properties": { + "form": { + "$ref": "#/components/schemas/RetentionPolicyForm" + }, + "policies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetentionPolicyView" + }, + "description": "Every policy." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The repositories a policy can name." + }, + "projectNames": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of the projects a policy can name." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the retention policies screen (`/admin/retention`) shows: every policy and the form that creates one." + }, + "ScanArtifactForm": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image).", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version (Docker: the manifest digest).", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where the link back goes (a local address only).", + "nullable": true + } + }, + "description": "The body of the scan twin's POST: the artifact and version to scan, and where the link back goes." + }, + "ScanEngineStatus": { + "required": [ + "available", + "engine", + "reason" + ], + "type": "object", + "properties": { + "available": { + "type": "boolean", + "description": "Whether a scan can run." + }, + "engine": { + "type": "string", + "description": "What scans the repository's artifacts (`OSV.dev`, `OSV offline copy`, `Trivy`), or null.", + "nullable": true + }, + "reason": { + "type": "string", + "description": "Why it cannot, or null. Safe to show.", + "nullable": true + } + }, + "description": "Whether the repository of the request can be scanned now, and by what." + }, + "ScanFinding": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "resultKey": { + "type": "integer", + "description": "The int ScanResult.Key. Required; deleting the result deletes its findings.", + "format": "int32" + }, + "vulnerabilityId": { + "type": "string", + "description": "The advisory id (`GHSA-…`, `CVE-…`), as the source names it.", + "nullable": true + }, + "component": { + "type": "string", + "description": "The component that is vulnerable: the artifact itself or one of its dependencies (package, OS package…).", + "nullable": true + }, + "componentVersion": { + "type": "string", + "description": "The version of string? ScanFinding.Component.", + "nullable": true + }, + "severity": { + "type": "integer", + "description": "0 low, 1 moderate, 2 high, 3 critical (the numbering of NuGet's vulnerability resource).", + "format": "int32" + }, + "summary": { + "type": "string", + "description": "A one-line description from the source, or null.", + "nullable": true + }, + "advisoryUrl": { + "type": "string", + "description": "Where the advisory is described (an absolute http(s) URL).", + "nullable": true + }, + "fixedVersion": { + "type": "string", + "description": "The first version that fixes it, when the source says.", + "nullable": true + } + }, + "description": "One vulnerability a scan found in an artifact or one of its components." + }, + "ScanningProjectRow": { + "required": [ + "project", + "hasPolicy" + ], + "type": "object", + "properties": { + "project": { + "$ref": "#/components/schemas/ProjectSummary" + }, + "hasPolicy": { + "type": "boolean", + "description": "Whether it has a scanning policy of its own." + } + }, + "description": "One project of the scanning overview." + }, + "ScanningRepositoryRow": { + "required": [ + "repository", + "summary", + "policy" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "summary": { + "$ref": "#/components/schemas/ScanSummary" + }, + "policy": { + "$ref": "#/components/schemas/EffectiveScanPolicy" + } + }, + "description": "One repository of the scanning overview." + }, + "ScanningSettingsView": { + "required": [ + "enabled", + "scanOnDeploy", + "osvUrl", + "osvOfflinePath", + "rescanInterval" + ], + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether artifacts are scanned." + }, + "scanOnDeploy": { + "type": "boolean", + "description": "Whether a stored version is queued for a scan at once." + }, + "osvUrl": { + "type": "string", + "description": "The OSV API root." + }, + "osvOfflinePath": { + "type": "string", + "description": "The offline copy of the OSV data, or null.", + "nullable": true + }, + "rescanInterval": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": "string", + "description": "The age after which an artifact is scanned again (zero or negative: never)." + } + }, + "description": "The scanning options the overview shows." + }, + "ScanningViewModel": { + "type": "object", + "properties": { + "settings": { + "$ref": "#/components/schemas/ScanningSettingsView" + }, + "trivyConfigured": { + "type": "boolean", + "description": "Whether Trivy is configured (container images are scanned)." + }, + "repositories": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanningRepositoryRow" + }, + "description": "The repositories that can hold artifacts (virtual ones hold none)." + }, + "projects": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanningProjectRow" + }, + "description": "The projects." + } + }, + "description": "What the vulnerability scanning overview (`/admin/scanning`) shows." + }, + "ScanPolicy": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The repository this policy is for, or null for a project policy.", + "format": "int32", + "nullable": true + }, + "projectKey": { + "type": "integer", + "description": "The project this policy is for, or null for a repository policy.", + "format": "int32", + "nullable": true + }, + "warnSeverity": { + "type": "integer", + "description": "Findings at or above this severity (0..3) are shown as a warning. Null: no warning.", + "format": "int32", + "nullable": true + }, + "blockDownloadSeverity": { + "type": "integer", + "description": "A version with a finding at or above this severity cannot be downloaded (403 with the reason). Null: never.", + "format": "int32", + "nullable": true + }, + "blockDeploySeverity": { + "type": "integer", + "description": "A deploy whose artifact or declared dependencies have a finding at or above this severity is refused (403). Null: never.", + "format": "int32", + "nullable": true + }, + "blockUnscanned": { + "type": "boolean", + "description": "Whether a version that has not been scanned (yet, or at all) cannot be downloaded." + }, + "modified": { + "type": "string", + "description": "When the policy was last saved (UTC).", + "format": "date-time" + }, + "modifiedBy": { + "type": "string", + "description": "The administrator who saved it, or null.", + "nullable": true + } + }, + "description": "What a repository (or a project's repositories) does about findings: a threshold severity per action, or none (null) for\r\nthe action. A repository's own policy wins over its project's. Exactly one of int? ScanPolicy.RepositoryKey and\r\nint? ScanPolicy.ProjectKey is set." + }, + "ScanPolicyBody": { + "required": [ + "warn", + "blockDownload", + "blockDeploy", + "blockUnscanned", + "password" + ], + "type": "object", + "properties": { + "warn": { + "type": "string", + "description": "Warn from this severity (0 to 3, or empty).", + "nullable": true + }, + "blockDownload": { + "type": "string", + "description": "Refuse downloads from this severity.", + "nullable": true + }, + "blockDeploy": { + "type": "string", + "description": "Refuse deploys from this severity.", + "nullable": true + }, + "blockUnscanned": { + "type": "boolean", + "description": "Refuse downloads of versions that were not scanned." + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Saving the scanning policy of a repository or project (empty values remove it)." + }, + "ScanPolicyScope": { + "enum": [ + "Repository", + "Project" + ], + "type": "string" + }, + "ScanPolicyValues": { + "required": [ + "warnSeverity", + "blockDownloadSeverity", + "blockDeploySeverity", + "blockUnscanned" + ], + "type": "object", + "properties": { + "warnSeverity": { + "type": "integer", + "description": "Show a warning from this severity (0 low … 3 critical).", + "format": "int32", + "nullable": true + }, + "blockDownloadSeverity": { + "type": "integer", + "description": "Refuse downloads from this severity.", + "format": "int32", + "nullable": true + }, + "blockDeploySeverity": { + "type": "integer", + "description": "Refuse deploys from this severity.", + "format": "int32", + "nullable": true + }, + "blockUnscanned": { + "type": "boolean", + "description": "Refuse downloads of versions that were not scanned." + }, + "isEmpty": { + "type": "boolean", + "description": "Whether nothing is enabled." + } + }, + "description": "The thresholds of a policy; null disables the action." + }, + "ScanProjectViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The project's name (route).", + "nullable": true + }, + "project": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ProjectDetails" + } + ] + }, + "own": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicy" + } + ] + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the scanning policy of a project (`/admin/scanning/projects/{name}`) shows." + }, + "ScanRepositoryViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The repository's name (route).", + "nullable": true + }, + "minSeverity": { + "type": "integer", + "description": "The lowest severity listed (0 low ... 3 critical).", + "format": "int32" + }, + "pageNumber": { + "type": "integer", + "description": "The page of the list, from 1.", + "format": "int32" + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + }, + "summary": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanSummary" + } + ] + }, + "effective": { + "$ref": "#/components/schemas/EffectiveScanPolicy" + }, + "own": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanPolicy" + } + ] + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanResult" + }, + "description": "The versions with findings on this page." + }, + "hasMore": { + "type": "boolean", + "description": "Whether there is another page." + }, + "job": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/AdminJobStatus" + } + ] + }, + "packageLinks": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ScreenLink" + }, + "description": "The package screen of each finding's version (by int ScanResult.Key), when its format has one." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the scanning dashboard of one repository (`/admin/scanning/{name}`) shows." + }, + "ScanResult": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "repositoryKey": { + "type": "integer", + "description": "The owning repository; see IRepositoryScoped.", + "format": "int32" + }, + "name": { + "type": "string", + "description": "The artifact name (see the class remarks). At most `ScanLimits.NameLength` characters.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The artifact version. At most `ScanLimits.VersionLength` characters.", + "nullable": true + }, + "scanner": { + "type": "string", + "description": "The scanner that produced the findings: `osv` or `trivy`.", + "nullable": true + }, + "scannedAt": { + "type": "string", + "description": "When the last scan succeeded (UTC); null when none ever did (the artifact counts as unscanned).", + "format": "date-time", + "nullable": true + }, + "attempted": { + "type": "string", + "description": "When a scan was last attempted (UTC).", + "format": "date-time" + }, + "error": { + "type": "string", + "description": "The scrubbed reason the last attempt failed, or null. The findings of the last success stay while this is set.", + "nullable": true + }, + "highest": { + "type": "integer", + "description": "The highest severity among List<ScanFinding>? ScanResult.Findings (0 low … 3 critical), or -1 when there are none.", + "format": "int32" + }, + "findingCount": { + "type": "integer", + "description": "How many findings the last success recorded.", + "format": "int32" + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScanFinding" + }, + "nullable": true + } + }, + "description": "What the last scans of one artifact version found, in one repository (table `ScanResults`). The artifact is named the way\r\nits format names it: NuGet package id (as stored), npm package name, Maven `group:artifact`, Docker image name; the\r\nversion is the package version, npm version, Maven version or the Docker manifest digest. A row exists once a scan was\r\nattempted; there is no foreign key to the artifact (it may be deleted, and each format keeps its own tables), so stale rows are\r\ndropped by the next sweep." + }, + "ScanSummary": { + "required": [ + "engine", + "artifacts", + "unscanned", + "failed", + "clean", + "bySeverity" + ], + "type": "object", + "properties": { + "engine": { + "$ref": "#/components/schemas/ScanEngineStatus" + }, + "artifacts": { + "type": "integer", + "description": "Artifacts stored in the repository.", + "format": "int32" + }, + "unscanned": { + "type": "integer", + "description": "Artifacts with no successful scan.", + "format": "int32" + }, + "failed": { + "type": "integer", + "description": "Of those, the ones whose last attempt failed.", + "format": "int32" + }, + "clean": { + "type": "integer", + "description": "Artifacts scanned without findings.", + "format": "int32" + }, + "bySeverity": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + }, + "description": "Artifacts by their highest finding: index 0 low … 3 critical." + } + }, + "description": "The repository dashboard numbers." + }, + "ScanViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image).", + "nullable": true + }, + "version": { + "type": "string", + "description": "The version (Docker: the manifest digest).", + "nullable": true + }, + "returnUrl": { + "type": "string", + "description": "Where the link back goes: the package page the user came from (a local address only).", + "nullable": true + }, + "message": { + "type": "string", + "description": "What happened, for the screen to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? ScanViewModel.Message reports a refusal." + }, + "result": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanResult" + } + ] + }, + "engine": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScanEngineStatus" + } + ] + }, + "backUrl": { + "type": "string", + "description": "The address the link back leads to (the return address when it is local, else the home page)." + } + }, + "description": "What the Scan now screen (`/scan-artifact`) shows; filled by the screen's workflow." + }, + "ScreenLink": { + "required": [ + "screen", + "routeValues" + ], + "type": "object", + "properties": { + "screen": { + "$ref": "#/components/schemas/ScreenRef" + }, + "routeValues": { + "type": "object", + "description": "Route values; a null value (`repo` of the default repository) is kept." + } + }, + "description": "A screen as a client links to it: the screen (controller and action) and its route values; the view turns it into an address." + }, + "ScreenNext": { + "required": [ + "screen" + ], + "type": "object", + "properties": { + "screen": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/ScreenRef" + } + ] + }, + "routeValues": { + "type": "object", + "description": "Route and query values of the next screen (`repo`, `name`, `handler`).", + "nullable": true + }, + "message": { + "type": "string", + "description": "The outcome to show on the next screen (a flash message).", + "nullable": true + }, + "error": { + "type": "string", + "description": "The refusal to show on the next screen (a flash error).", + "nullable": true + }, + "localUrl": { + "type": "string", + "description": "Instead of a screen: a local address to continue at (`/packages`, or `~/` for the site root, which the view prefixes with the path\r\nbase). Always safe to follow: a use case only puts a validated local address here (LocalUrls).", + "nullable": true + }, + "fragment": { + "type": "string", + "description": "The URL fragment (`#id`) to leave the next screen at, or null.", + "nullable": true + } + }, + "description": "Where a finished action leads: the screen (controller and action, see ScreenCatalog), its route values and the message to show there." + }, + "ScreenRef": { + "required": [ + "controller", + "action" + ], + "type": "object", + "properties": { + "controller": { + "type": "string", + "description": "The controller name without the `Controller` suffix (`AdminUsers`)." + }, + "action": { + "type": "string", + "description": "The action that shows the screen (`Index`)." + } + }, + "description": "A screen of the web UI: the MVC controller (without the `Controller` suffix, as `asp-controller` writes it) and the action that\r\nanswers a plain `GET` for it (`AdminUsers` / `Index`). The Application projects have no MVC reference, so the UI project\r\nturns it into a link. ScreenCatalog lists every screen." + }, + "ScreenResultOfAbuseViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AbuseViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAccessUnavailableViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AccessUnavailableViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAccountAccessViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AccountAccessViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAccountPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AccountPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAdminOrganizationsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AdminOrganizationsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAdminPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AdminPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAdminSettingsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AdminSettingsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAntiforgeryTokenModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AntiforgeryTokenModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfApiCatalogViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ApiCatalogViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfApiKeysViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ApiKeysViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfAuditViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/AuditViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfClusterViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ClusterViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfConfirmEmailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ConfirmEmailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfContactOwnersViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ContactOwnersViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDatabaseCopyStatusView": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DatabaseCopyStatusView" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDeleteUserViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DeleteUserViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDockerImagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DockerImagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDockerImageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DockerImageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfDockerManageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/DockerManageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfEmptyScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/EmptyScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfForgotPasswordViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ForgotPasswordViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfFormatsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/FormatsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfGroupDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/GroupDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfGroupsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/GroupsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfIndexScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/IndexScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfLegalScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/LegalScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfLoginViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/LoginViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenArtifactsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenArtifactsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenArtifactViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenArtifactViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenManageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenManageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfMavenUploadViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/MavenUploadViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmManageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmManageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmPackageViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmPackageViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfNpmUploadViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/NpmUploadViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfOperationsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/OperationsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfOrganizationDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/OrganizationDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfOrganizationsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/OrganizationsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPackageManageScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PackageManageScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPackageScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PackageScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPermissionDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PermissionDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfPermissionsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/PermissionsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfProfileViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ProfileViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfProjectDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ProjectDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfProjectsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ProjectsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReauthenticateViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReauthenticateViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRecoveryCodeLoginViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RecoveryCodeLoginViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRegisterViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RegisterViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReplicationConfigViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReplicationConfigViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReplicationViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReplicationViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfReportAbuseScreen": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ReportAbuseScreen" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRepositoriesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RepositoriesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRepositoryDeleteViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RepositoryDeleteViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRepositoryEditViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RepositoryEditViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfResetPasswordViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ResetPasswordViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRetentionHoldsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RetentionHoldsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRetentionPolicyViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RetentionPolicyViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfRetentionViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/RetentionViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanningViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanningViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanProjectViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanProjectViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanRepositoryViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanRepositoryViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfScanViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ScanViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfSessionModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/SessionModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfSessionProvidersModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/SessionProvidersModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfSettingsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/SettingsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfStatisticsViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/StatisticsViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfTwoFactorLoginViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/TwoFactorLoginViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfTwoFactorViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/TwoFactorViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUploadViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UploadViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUserDetailViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UserDetailViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUserPackagesViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UserPackagesViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfUsersViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/UsersViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfValidationStatusViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ValidationStatusViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenResultOfValidationViewModel": { + "type": "object", + "properties": { + "status": { + "$ref": "#/components/schemas/ScreenStatus" + }, + "model": { + "$ref": "#/components/schemas/ValidationViewModel" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "nullable": true + }, + "next": { + "$ref": "#/components/schemas/ScreenNext" + }, + "statusCode": { + "type": "integer", + "format": "int32", + "nullable": true + } + }, + "description": "What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is\r\n(`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect.\r\nA use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`." + }, + "ScreenStatus": { + "enum": [ + "Ok", + "Invalid", + "NotFound", + "Forbidden", + "SignIn", + "Next" + ], + "type": "string", + "description": "What a use case decided about a screen." + }, + "SearchResult": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The ID of the matched package.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The latest version of the matched pacakge. This is the full NuGet version after normalization,\r\nincluding any SemVer 2.0.0 build metadata.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description of the matched package.", + "nullable": true + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The authors of the matched package.", + "nullable": true + }, + "iconUrl": { + "type": "string", + "description": "The URL of the matched package's icon.", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "description": "The URL of the matched package's license.", + "nullable": true + }, + "packageTypes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchResultPackageType" + }, + "description": "The package types defined by the package author.", + "nullable": true + }, + "projectUrl": { + "type": "string", + "description": "The URL of the matched package's homepage.", + "nullable": true + }, + "registration": { + "type": "string", + "description": "The URL for the matched package's registration index.", + "nullable": true + }, + "summary": { + "type": "string", + "description": "The summary of the matched package.", + "nullable": true + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The tags of the matched package.", + "nullable": true + }, + "title": { + "type": "string", + "description": "The title of the matched package.", + "nullable": true + }, + "totalDownloads": { + "type": "integer", + "description": "The total downloads for all versions of the matched package.", + "format": "int64" + }, + "versions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchResultVersion" + }, + "description": "The versions of the matched package.", + "nullable": true + }, + "deprecation": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/PackageDeprecation" + } + ] + }, + "vulnerabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageVulnerabilityMetadata" + }, + "description": "The latest version's known vulnerabilities, or null if it has none.", + "nullable": true + }, + "owners": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The package's owners, or null if it has none.", + "nullable": true + }, + "verified": { + "type": "boolean", + "description": "Whether the package ID is reserved for its owners. Null if it has no owners.", + "nullable": true + } + }, + "description": "A package that matched a search query.\r\n\r\nSee https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result" + }, + "SearchResultPackageType": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the package type.", + "nullable": true + } + }, + "description": "A single package type from a SearchResult.\r\n\r\nSee https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result" + }, + "SearchResultVersion": { + "type": "object", + "properties": { + "@id": { + "type": "string", + "description": "The registration leaf URL for this single version of the matched package.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata.", + "nullable": true + }, + "downloads": { + "type": "integer", + "description": "The downloads for this single version of the matched package.", + "format": "int64" + } + }, + "description": "A single version from a SearchResult.\r\n\r\nSee https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result" + }, + "SearchSort": { + "enum": [ + "Relevance", + "TotalDownloads", + "LastUpdated" + ], + "type": "string", + "description": "How the web UI orders search results. The V3 search API has no sort parameter, so\r\nit always uses SearchSort.Relevance." + }, + "SemVerLevel": { + "enum": [ + "Unknown", + "SemVer2" + ], + "type": "string" + }, + "SessionCookieForm": { + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The username (password step).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password (password step).", + "nullable": true + }, + "ticket": { + "type": "string", + "description": "The `twoFactorTicket` of the password step (second step).", + "nullable": true + }, + "code": { + "type": "string", + "description": "A code of the authenticator app (second step).", + "nullable": true + }, + "recoveryCode": { + "type": "string", + "description": "A recovery code (second step).", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/cookie` (a same-origin client that signs in with the cookie): the password step (string? SessionCookieForm.UserName,\r\nstring? SessionCookieForm.Password), or, when the account has two-factor, the second step (string? SessionCookieForm.Ticket with string? SessionCookieForm.Code or string? SessionCookieForm.RecoveryCode)." + }, + "SessionExchangeForm": { + "required": [ + "exchangeToken" + ], + "type": "object", + "properties": { + "exchangeToken": { + "type": "string", + "description": "The `exchange_token` of the external sign-in's redirect.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/exchange`." + }, + "SessionModel": { + "type": "object", + "properties": { + "accessToken": { + "type": "string", + "description": "Authenticates requests to `/api/ui` (`Authorization: Bearer`); null while bool SessionModel.TwoFactorRequired.", + "nullable": true + }, + "expiresAt": { + "type": "string", + "description": "When the access token stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "refreshToken": { + "type": "string", + "description": "Exchanged for a new pair at `/api/ui/session/refresh`; each refresh returns a new one and the old one stays valid until it expires.", + "nullable": true + }, + "refreshExpiresAt": { + "type": "string", + "description": "When the refresh token stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "userName": { + "type": "string", + "description": "The signed-in user's name.", + "nullable": true + }, + "twoFactorRequired": { + "type": "boolean", + "description": "The password was right but the account asks for a second factor: post the string? SessionModel.TwoFactorTicket and a code to `/api/ui/session/two-factor` or `/recovery-code`." + }, + "twoFactorTicket": { + "type": "string", + "description": "Proves the password step; valid for five minutes, and useless without a code.", + "nullable": true + }, + "twoFactorTicketExpiresAt": { + "type": "string", + "description": "When the ticket stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "exchangeToken": { + "type": "string", + "description": "External sign-in only: a single-use-in-practice token (60 seconds) to exchange for the real ones at `POST /api/ui/session/exchange`.", + "nullable": true + }, + "exchangeExpiresAt": { + "type": "string", + "description": "When the exchange token stops being accepted (UTC).", + "format": "date-time", + "nullable": true + }, + "notice": { + "type": "string", + "description": "Something to tell the user when there are no tokens yet (external sign-in: the account was created and awaits approval or a confirmed email address).", + "nullable": true + } + }, + "description": "What `/api/ui/session` answers: a pair of tokens, or the ticket for the second factor of a sign-in." + }, + "SessionProvidersModel": { + "type": "object", + "properties": { + "providers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalProviderInfo" + }, + "description": "The configured providers, empty when there is none." + } + }, + "description": "The external sign-in providers a client can offer (`GET /api/ui/session/providers`): one button each, started at `/api/ui/session/external/{id}`." + }, + "SessionRecoveryCodeForm": { + "required": [ + "ticket", + "recoveryCode" + ], + "type": "object", + "properties": { + "ticket": { + "type": "string", + "description": "The `twoFactorTicket` the password step answered.", + "nullable": true + }, + "recoveryCode": { + "type": "string", + "description": "A recovery code.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/recovery-code`: the ticket of the password step and one of the account's recovery codes (each works once)." + }, + "SessionRefreshForm": { + "required": [ + "refreshToken" + ], + "type": "object", + "properties": { + "refreshToken": { + "type": "string", + "description": "The `refreshToken` of the last answer.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/refresh`." + }, + "SessionSignInForm": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session`: the same credentials as the sign-in page." + }, + "SessionSignOutForm": { + "type": "object", + "properties": { + "refreshToken": { + "type": "string", + "description": "The refresh token to end the session with when the request carries no access token.", + "nullable": true + }, + "everywhere": { + "type": "boolean", + "description": "Also ends every other session of the account (cookie sessions and tokens) by changing its security stamp. Without it nothing is\r\nrevoked: the tokens are stateless, so the client simply forgets them, and they expire." + } + }, + "description": "The body of `POST /api/ui/session/sign-out`." + }, + "SessionTwoFactorForm": { + "required": [ + "ticket", + "code" + ], + "type": "object", + "properties": { + "ticket": { + "type": "string", + "description": "The `twoFactorTicket` the password step answered.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + } + }, + "description": "The body of `POST /api/ui/session/two-factor`: the ticket of the password step and a code of the authenticator app." + }, + "SettingDescriptor": { + "required": [ + "key", + "section", + "group", + "kind", + "enumValues", + "isSensitive", + "requiresRestart", + "description" + ], + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The full key, such as \"Email:Smtp:Host\"." + }, + "section": { + "type": "string", + "description": "The first segment of the key, or an empty string for a top-level key." + }, + "group": { + "type": "string", + "description": "The options type's name without \"Options\", such as \"AzureBlobStorage\"." + }, + "kind": { + "$ref": "#/components/schemas/SettingKind" + }, + "enumValues": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The allowed names of an SettingKind.Enum, otherwise empty." + }, + "isSensitive": { + "type": "boolean", + "description": "The value is a credential: masked and write-only." + }, + "requiresRestart": { + "type": "boolean", + "description": "A change applies after a restart." + }, + "description": { + "type": "string", + "description": "The property's XML documentation summary, or an empty string." + }, + "exampleDependsOnKey": { + "type": "string", + "description": "The full key of the setting that selects Examples (see\r\nSettingExampleAttribute), or null.", + "nullable": true + }, + "examples": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Example values by the value of ExampleDependsOnKey (case-insensitive), or null.", + "nullable": true + } + }, + "description": "One configuration key the Settings page can show." + }, + "SettingKind": { + "enum": [ + "Boolean", + "Integer", + "Number", + "String", + "Enum", + "TimeSpan", + "StringList", + "ReadOnly" + ], + "type": "string", + "description": "The editable type of a setting." + }, + "SettingsSection": { + "required": [ + "key", + "id", + "settings" + ], + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The section's key; empty for the settings that sit at the top level." + }, + "id": { + "type": "string", + "description": "The stable DOM id (string AdminSettingsViewModel.SectionId(string key))." + }, + "settings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SettingState" + }, + "description": "The settings of the section; a sensitive one never carries its value." + } + }, + "description": "One section of the settings screen: its key (empty for the top-level keys), its DOM id and its settings." + }, + "SettingsSubmission": { + "required": [ + "section", + "password", + "fields" + ], + "type": "object", + "properties": { + "section": { + "type": "string", + "description": "The section being saved (the empty section holds the top-level keys).", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + }, + "fields": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "The posted fields; a field may repeat." + } + }, + "description": "The fields of a submitted Settings form, per setting key (`v:<key>` the value, `reset:<key>`, `clear:<key>`; a checkbox posts\r\n`true` next to a hidden `false`, a list is one entry per line) and the section they belong to. The same shape whether it comes from the\r\npage's form or from a JSON body." + }, + "SettingState": { + "required": [ + "descriptor", + "effectiveValue", + "hasValue", + "isOverridden", + "shadowedBy", + "pendingRestart" + ], + "type": "object", + "properties": { + "descriptor": { + "$ref": "#/components/schemas/SettingDescriptor" + }, + "effectiveValue": { + "type": "string", + "description": "The value in effect, as text (a list one entry per line). Always null for a sensitive\r\nsetting: only HasValue says whether one is set.", + "nullable": true + }, + "hasValue": { + "type": "boolean", + "description": "The setting has a non-empty value." + }, + "isOverridden": { + "type": "boolean", + "description": "The setting is saved in the overrides file." + }, + "shadowedBy": { + "type": "string", + "description": "What overrides the saved value (\"environment variable\", \"command line\", ...), or null.\r\nWhile set, a saved value has no effect.", + "nullable": true + }, + "pendingRestart": { + "type": "boolean", + "description": "A restart-only setting whose value changed since startup." + } + }, + "description": "A setting as the Settings page shows it." + }, + "SettingsViewModel": { + "type": "object", + "properties": { + "email": { + "type": "string", + "description": "The account's email address.", + "nullable": true + }, + "emailConfirmed": { + "type": "boolean", + "description": "Whether the address is confirmed." + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the account has a password (else it signs in through a provider)." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is configured to sign in again with." + }, + "canSendEmail": { + "type": "boolean", + "description": "Whether mail is configured." + }, + "externalLogins": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ExternalLoginStatus" + }, + "description": "Every configured external provider with whether this account has linked a login at it (empty when there is none)." + }, + "message": { + "type": "string", + "description": "The success message to show.", + "nullable": true + }, + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "blockers": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/DeletionBlockers" + } + ] + } + }, + "description": "What the account settings screen shows (change email, change password, delete the account)." + }, + "SignInProviderForm": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id (lower-case letters, digits and `-`, 1 to 32).", + "nullable": true + }, + "displayName": { + "type": "string", + "description": "The name on the sign-in button.", + "nullable": true + }, + "authority": { + "type": "string", + "description": "The issuer address.", + "nullable": true + }, + "clientId": { + "type": "string", + "description": "The client id.", + "nullable": true + }, + "clientSecret": { + "type": "string", + "description": "The client secret; blank keeps the saved one. Never sent back.", + "nullable": true + }, + "scopes": { + "type": "string", + "description": "Extra scopes, separated by spaces or semicolons.", + "nullable": true + }, + "parameters": { + "type": "string", + "description": "Extra authorization request parameters, one `name=value` per line.", + "nullable": true + }, + "userNameClaim": { + "type": "string", + "description": "The claim holding the user name.", + "nullable": true + }, + "emailClaim": { + "type": "string", + "description": "The claim holding the email address.", + "nullable": true + }, + "emailVerifiedClaim": { + "type": "string", + "description": "The claim saying the address is verified.", + "nullable": true + }, + "administratorClaim": { + "type": "string", + "description": "The claim that decides the administrator flag (the provider becomes authoritative for it).", + "nullable": true + }, + "administratorValue": { + "type": "string", + "description": "The value of that claim that makes a user an administrator.", + "nullable": true + }, + "groupClaim": { + "type": "string", + "description": "The claim holding the user's groups.", + "nullable": true + }, + "groupMappings": { + "type": "string", + "description": "Claim value to BaGet group, one `value=group` per line.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + } + }, + "description": "What the \"Sign-in providers\" panel of the Settings screen posts to add or edit a named OpenID Connect provider (the body of\r\n`POST /api/ui/admin/settings/save-provider`). The id is the key and cannot change once created; a blank secret keeps the saved one.\r\nstring? SignInProviderForm.Parameters and string? SignInProviderForm.GroupMappings are one `name=value` per line." + }, + "SignInProviderView": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The provider id." + }, + "displayName": { + "type": "string", + "description": "The name on the sign-in button.", + "nullable": true + }, + "authority": { + "type": "string", + "description": "The issuer address.", + "nullable": true + }, + "clientId": { + "type": "string", + "description": "The client id.", + "nullable": true + }, + "hasSecret": { + "type": "boolean", + "description": "Whether a client secret is set." + }, + "scopes": { + "type": "string", + "description": "Extra scopes.", + "nullable": true + }, + "parameters": { + "type": "string", + "description": "Extra request parameters, one `name=value` per line.", + "nullable": true + }, + "userNameClaim": { + "type": "string", + "description": "The claim holding the user name.", + "nullable": true + }, + "emailClaim": { + "type": "string", + "description": "The claim holding the email address.", + "nullable": true + }, + "emailVerifiedClaim": { + "type": "string", + "description": "The claim saying the address is verified.", + "nullable": true + }, + "administratorClaim": { + "type": "string", + "description": "The claim that decides the administrator flag.", + "nullable": true + }, + "administratorValue": { + "type": "string", + "description": "The value of that claim that makes a user an administrator.", + "nullable": true + }, + "groupClaim": { + "type": "string", + "description": "The claim holding the user's groups.", + "nullable": true + }, + "groupMappings": { + "type": "string", + "description": "Claim value to BaGet group, one `value=group` per line.", + "nullable": true + }, + "editable": { + "type": "boolean", + "description": "Whether the overrides file holds it, so this screen can edit or remove it; false when a configuration file or the environment sets it." + }, + "active": { + "type": "boolean", + "description": "Whether the running server has a handler for it (false: saved or removed since startup)." + }, + "pendingRestart": { + "type": "boolean", + "description": "Whether what is saved differs from what the running server uses, so a restart is needed." + } + }, + "description": "A named OpenID Connect provider as the Settings screen lists it. The client secret is never carried, only whether one is set." + }, + "SoleOwnedPackage": { + "required": [ + "repositoryKey", + "repositoryName", + "packageId" + ], + "type": "object", + "properties": { + "repositoryKey": { + "type": "integer", + "description": "The repository's key.", + "format": "int32" + }, + "repositoryName": { + "type": "string", + "description": "The repository's name (string Repository.DefaultName for the default)." + }, + "packageId": { + "type": "string", + "description": "The package ID.", + "nullable": true + }, + "format": { + "$ref": "#/components/schemas/RepositoryFormat" + }, + "label": { + "type": "string", + "description": "The ID for the default repository, `ID (name)` for any other, for messages that mix repositories.", + "nullable": true + } + }, + "description": "A package ID in one repository that only one user owns." + }, + "StatisticsViewModel": { + "required": [ + "statistics" + ], + "type": "object", + "properties": { + "statistics": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/FeedStatistics" + } + ] + } + }, + "description": "What the statistics page shows." + }, + "Stream": { + "type": "string", + "format": "binary", + "nullable": true + }, + "SubmissionForm": { + "required": [ + "submissionId", + "password" + ], + "type": "object", + "properties": { + "submissionId": { + "type": "string", + "description": "The submission.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password (asked to release or reject).", + "nullable": true + } + }, + "description": "A decision on a stuck submission of the validation queue." + }, + "TargetDetails": { + "required": [ + "target", + "grants" + ], + "type": "object", + "properties": { + "target": { + "$ref": "#/components/schemas/TargetSummary" + }, + "grants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GrantInfo" + } + } + }, + "description": "A permission target with its grants." + }, + "TargetFramework": { + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "moniker": { + "type": "string", + "nullable": true + }, + "package": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/Package" + } + ] + } + } + }, + "TargetSummary": { + "required": [ + "key", + "name", + "repositoryPatterns", + "includePatterns", + "excludePatterns", + "projectKey", + "projectName", + "isBuiltIn", + "grantCount" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + }, + "repositoryPatterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "includePatterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludePatterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "projectKey": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "projectName": { + "type": "string", + "nullable": true + }, + "isBuiltIn": { + "type": "boolean" + }, + "grantCount": { + "type": "integer", + "format": "int32" + } + }, + "description": "A permission target as the admin pages list it." + }, + "TelemetrySignalReport": { + "required": [ + "signal", + "state", + "lastSuccess", + "failingSince", + "lastError", + "dropped" + ], + "type": "object", + "properties": { + "signal": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/TelemetrySignalState" + }, + "lastSuccess": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "failingSince": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "lastError": { + "type": "string", + "nullable": true + }, + "dropped": { + "type": "integer", + "format": "int64" + } + }, + "description": "One signal's state. string? TelemetrySignalReport.LastError is already scrubbed (no headers, credentials or URL paths)." + }, + "TelemetrySignalState": { + "enum": [ + "Off", + "NotConfigured", + "Waiting", + "Ok", + "Failing" + ], + "type": "string", + "description": "What one telemetry signal is doing, as the Settings page shows it." + }, + "TelemetryTestOutcome": { + "required": [ + "ok", + "message", + "target" + ], + "type": "object", + "properties": { + "ok": { + "type": "boolean", + "description": "The collector accepted a test span." + }, + "message": { + "type": "string", + "description": "What happened." + }, + "target": { + "type": "string", + "description": "The endpoint that was tested, cut to scheme, host and port.", + "nullable": true + } + }, + "description": "The outcome of a connection test; string TelemetryTestOutcome.Message and string? TelemetryTestOutcome.Target are scrubbed." + }, + "TwoFactorCodeForm": { + "type": "object", + "properties": { + "password": { + "type": "string", + "description": "The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + } + }, + "description": "What the \"turn two-factor authentication on\" form posts." + }, + "TwoFactorLoginForm": { + "required": [ + "code" + ], + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "What the authenticator-code form posts." + }, + "TwoFactorLoginViewModel": { + "required": [ + "code" + ], + "type": "object", + "properties": { + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "code": { + "type": "string", + "description": "The code from the authenticator app.", + "nullable": true + }, + "rememberMe": { + "type": "boolean", + "description": "Whether the session outlives the browser." + }, + "returnUrl": { + "type": "string", + "description": "Where to go after signing in; only a local URL is followed.", + "nullable": true + } + }, + "description": "The second step of signing in: an authenticator code. A request binds TwoFactorLoginForm, never this type." + }, + "TwoFactorViewModel": { + "type": "object", + "properties": { + "twoFactorEnabled": { + "type": "boolean", + "description": "Whether two-factor authentication is on." + }, + "sharedKey": { + "type": "string", + "description": "The key to type into an authenticator that cannot scan the QR code.", + "nullable": true + }, + "qrCodeSvg": { + "type": "string", + "description": "The QR code of the setup link, an SVG built from the user's own key.", + "nullable": true + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is configured to sign in again with." + }, + "recoveryCodesLeft": { + "type": "integer", + "description": "How many recovery codes are unused.", + "format": "int32" + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the account has a password (else it signs in through a provider)." + }, + "recoveryCodes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The new recovery codes. Shown once, when two-factor authentication is turned on." + }, + "error": { + "type": "string", + "description": "The refusal to show.", + "nullable": true + }, + "message": { + "type": "string", + "description": "The success message to show.", + "nullable": true + } + }, + "description": "What the two-factor authentication screen shows." + }, + "UnlinkExternalForm": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "description": "The id of the provider to unlink.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The password, asked again.", + "nullable": true + } + }, + "description": "What unlinking an external provider posts." + }, + "UploadPreview": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The handle of the staged file; only the user who staged it can open it.", + "nullable": true + }, + "isSymbolPackage": { + "type": "boolean", + "description": "Whether the file is a symbol package (`.snupkg`, by its nuspec's package type)." + }, + "id": { + "type": "string", + "description": "The package ID, from the nuspec.", + "nullable": true + }, + "version": { + "type": "string", + "description": "The normalized version, from the nuspec.", + "nullable": true + }, + "description": { + "type": "string", + "description": "The description.", + "nullable": true + }, + "authors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The authors." + }, + "license": { + "type": "string", + "description": "The license expression or license file the package declares, if any.", + "nullable": true + }, + "licenseUrl": { + "type": "string", + "description": "The license URL, if any.", + "nullable": true + }, + "dependencyGroups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DependencyGroupModel" + }, + "description": "The dependencies by target framework." + }, + "readme": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/HtmlString" + } + ] + }, + "symbolFiles": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The PDBs of a symbol package." + }, + "targetPackageExists": { + "type": "boolean", + "description": "Whether the version a symbol package belongs to is on this server." + }, + "targetPackageMessage": { + "type": "string", + "description": "What to tell about a symbol package whose package is missing.", + "nullable": true + } + }, + "description": "What a staged NuGet upload contains, as the preview of the upload page shows it (read from the archive itself)." + }, + "UploadTokenRequest": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The handle of the staged upload (string? UploadPreview.Token)." + }, + "apiKey": { + "type": "string", + "description": "The API key of the uploader while accounts are off (otherwise the signed-in session or the key of the request authenticates).", + "nullable": true + }, + "acceptTerms": { + "type": "boolean", + "description": "The confirmation that the uploader may publish the package (required to publish, ignored when discarding)." + } + }, + "description": "What the second and third step of the NuGet upload send (publish and discard a staged upload): the handle of the staged file and, while accounts are\r\noff, the API key that authenticates the uploader. The key is read and never echoed in an answer." + }, + "UploadViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID a link arrived with, as \"upload a new version of this\" does. A hint for the page only: the ID and version that\r\nare published are read from the file, never from the request.", + "nullable": true + }, + "accountsEnabled": { + "type": "boolean", + "description": "Whether accounts are on (the uploader then signs in)." + }, + "isReadOnlyMode": { + "type": "boolean", + "description": "Whether the server is read-only." + }, + "signedIn": { + "type": "boolean", + "description": "Whether the visitor is signed in." + }, + "needsApiKey": { + "type": "boolean", + "description": "With accounts off there is no user to own an upload, so the pusher proves itself with an API key." + }, + "nothingCanAuthenticate": { + "type": "boolean", + "description": "Nothing on this server can tell one caller from another (accounts off and no global API key): the browser upload is closed." + }, + "noApiKeyExplanation": { + "type": "string", + "description": "What the page says in that state, so the explanation and the refusal are one sentence.", + "nullable": true + }, + "canUpload": { + "type": "boolean", + "description": "Whether to render the form at all." + }, + "staged": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadPreview" + } + ] + }, + "message": { + "type": "string", + "description": "What happened, for the page to show.", + "nullable": true + }, + "failed": { + "type": "boolean", + "description": "Whether string? UploadViewModel.Message reports a failure." + }, + "published": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UploadPreview" + } + ] + }, + "retryToken": { + "type": "string", + "description": "The token of a staged upload whose API key was rejected, so the key can be entered again.", + "nullable": true + }, + "statusCode": { + "type": "integer", + "description": "The HTTP status the page is answered with (200, or the refusal's).", + "format": "int32" + } + }, + "description": "What the NuGet upload page (`/upload`) shows: the form, the preview of a staged file, or the outcome of a step." + }, + "UserAccountInfo": { + "required": [ + "userName", + "email", + "created", + "isAdministrator", + "pendingApproval" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address, or null.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When the account was created.", + "format": "date-time" + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether it is a server administrator." + }, + "pendingApproval": { + "type": "boolean", + "description": "Whether it waits for an administrator to enable it." + } + }, + "description": "The account an administrator looks at, without anything that signs in as it (no password hash, security stamp or tokens)." + }, + "UserChange": { + "required": [ + "userName", + "password" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The account the change applies to.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + }, + "q": { + "type": "string", + "description": "The list's user-name filter.", + "nullable": true + }, + "pageNumber": { + "type": "integer", + "description": "The list's page.", + "format": "int32", + "default": 1 + }, + "resetEmail": { + "type": "string", + "description": "For a password reset: the address to mail the new password to, if the administrator typed one.", + "nullable": true + } + }, + "description": "A change to one account from the Users screen, with the list's filter and page to come back to." + }, + "UserCreation": { + "required": [ + "newUserName", + "newEmail", + "newPassword", + "invite", + "password" + ], + "type": "object", + "properties": { + "newUserName": { + "type": "string", + "description": "The new account's name.", + "nullable": true + }, + "newEmail": { + "type": "string", + "description": "Its address, or null.", + "nullable": true + }, + "newPassword": { + "type": "string", + "description": "The password typed; empty means generate one (unless Invite).", + "nullable": true + }, + "invite": { + "type": "boolean", + "description": "Mail the user a link to choose their own password." + }, + "password": { + "type": "string", + "description": "The administrator's password, asked again.", + "nullable": true + }, + "q": { + "type": "string", + "description": "The list's user-name filter.", + "nullable": true + }, + "pageNumber": { + "type": "integer", + "description": "The list's page.", + "format": "int32", + "default": 1 + } + }, + "description": "A new account from the Users screen." + }, + "UserDeletionForm": { + "required": [ + "soleOwned", + "password" + ], + "type": "object", + "properties": { + "soleOwned": { + "type": "string", + "description": "\"keep\" (default) or \"delete\": what to do with the package IDs only this user owns.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Deleting an account." + }, + "UserDetailViewModel": { + "type": "object", + "properties": { + "package": { + "type": "string", + "description": "A package ID to evaluate the effective permissions for; empty means each repository as a whole.", + "nullable": true + }, + "name": { + "type": "string", + "description": "The user name (route).", + "nullable": true + }, + "modelAvailable": { + "type": "boolean", + "description": "Whether the configured database has an access model (else the access sections are hidden)." + }, + "groups": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The names of the groups the account belongs to (the implicit built-ins excluded)." + }, + "projectRoles": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserProjectRole" + }, + "description": "The roles the account holds in projects, directly or through a group." + }, + "access": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryAccessRow" + }, + "description": "What the account may do in each NuGet repository, and why." + }, + "account": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/UserAccountInfo" + } + ] + }, + "keys": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserKeyRow" + }, + "description": "The account's API keys; the key and its hash are never shown." + }, + "organizations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Organization" + }, + "description": "The organizations the account belongs to." + }, + "ownedPackageIds": { + "type": "integer", + "description": "How many package IDs the account owns, in every repository.", + "format": "int32" + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the user detail screen (`/admin/users/{name}`) shows: the account, its keys, organizations and access." + }, + "UserGroupForm": { + "required": [ + "group", + "password" + ], + "type": "object", + "properties": { + "group": { + "type": "string", + "description": "The group's name.", + "nullable": true + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Adding an account to a group or removing it." + }, + "UserKeyForm": { + "required": [ + "key", + "password" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The key's number (int UserKeyRow.Key).", + "format": "int32" + }, + "password": { + "type": "string", + "description": "The administrator's password.", + "nullable": true + } + }, + "description": "Revoking one of an account's API keys." + }, + "UserKeyRow": { + "required": [ + "key", + "description", + "scopes", + "packageGlobPattern", + "created", + "expires", + "repositories" + ], + "type": "object", + "properties": { + "key": { + "type": "integer", + "description": "The key's number (what revoking names).", + "format": "int32" + }, + "description": { + "type": "string", + "description": "The description the owner gave it.", + "nullable": true + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "What it may do." + }, + "packageGlobPattern": { + "type": "string", + "description": "The package IDs it applies to.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When it was created.", + "format": "date-time" + }, + "expires": { + "type": "string", + "description": "When it expires, or null.", + "format": "date-time", + "nullable": true + }, + "repositories": { + "type": "string", + "description": "Where it may be used: the repositories it is limited to, or \"all repositories\"." + } + }, + "description": "One of an account's API keys as the administrator sees it; the key itself and its hash are never shown." + }, + "UserPackagesViewModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The user name, from the route.", + "nullable": true + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminPackageRow" + }, + "description": "The user's packages." + } + }, + "description": "What the user packages screen (`/admin/users/{name}/packages`) shows: the package IDs one user owns." + }, + "UserProjectRole": { + "required": [ + "project", + "role", + "via" + ], + "type": "object", + "properties": { + "project": { + "type": "string" + }, + "role": { + "$ref": "#/components/schemas/ProjectRole" + }, + "via": { + "type": "string" + } + }, + "description": "A role a user holds in a project, directly or through a group." + }, + "UserRow": { + "required": [ + "userName", + "email", + "created", + "isAdministrator", + "avatarUrl" + ], + "type": "object", + "properties": { + "userName": { + "type": "string", + "description": "The user name.", + "nullable": true + }, + "email": { + "type": "string", + "description": "The email address, if any.", + "nullable": true + }, + "created": { + "type": "string", + "description": "When the account was created.", + "format": "date-time" + }, + "isAdministrator": { + "type": "boolean", + "description": "Whether the user is an administrator." + }, + "avatarUrl": { + "type": "string", + "description": "The avatar's address, or null for the initial.", + "nullable": true + }, + "pendingApproval": { + "type": "boolean", + "description": "Whether the account waits for an administrator to enable it (`Accounts:RequireApproval`).", + "default": false + } + }, + "description": "A user as the Users page lists them." + }, + "UsersViewModel": { + "type": "object", + "properties": { + "q": { + "type": "string", + "description": "User-name filter (contains).", + "nullable": true + }, + "pageNumber": { + "type": "integer", + "description": "One-based page number (the `p` query value; not \"page\", which Razor Pages reserved for the page path).", + "format": "int32" + }, + "users": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserRow" + }, + "description": "The users on this page." + }, + "pendingCount": { + "type": "integer", + "description": "How many accounts, in all pages, wait for approval.", + "format": "int32" + }, + "pageCount": { + "type": "integer", + "description": "The number of pages for the current filter.", + "format": "int32" + }, + "currentUserName": { + "type": "string", + "description": "The signed in administrator's user name; their own row has no actions.", + "nullable": true + }, + "canEmailResetLink": { + "type": "boolean", + "description": "Whether a reset link can be mailed: SMTP is configured." + }, + "canInvite": { + "type": "boolean", + "description": "Whether an invitation (a reset link mailed to the new user) can be offered: SMTP is configured." + }, + "generatedPassword": { + "type": "string", + "description": "The password just generated. Only ever rendered by the response to the reset itself, never kept in TempData or a cookie.", + "nullable": true + }, + "generatedFor": { + "type": "string", + "description": "The user string? UsersViewModel.GeneratedPassword belongs to.", + "nullable": true + }, + "generatedForNewUser": { + "type": "boolean", + "description": "Whether string? UsersViewModel.GeneratedPassword is a new account's first password rather than a reset." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the Users screen (`/admin/users`) shows: the filtered, paged accounts and the state of the last action." + }, + "ValidationStatusViewModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The package ID from the address.", + "nullable": true + }, + "submissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationSubmission" + }, + "description": "The newest submission of each version, newest version first." + } + }, + "description": "What the validation status screen (`/packages/{id}/validation`) shows; filled by the screen's workflow." + }, + "ValidationSubmission": { + "required": [ + "version", + "submissionId", + "status", + "steps" + ], + "type": "object", + "properties": { + "version": { + "type": "string" + }, + "submissionId": { + "type": "string", + "nullable": true + }, + "status": { + "type": "string" + }, + "steps": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PackageValidation" + } + } + }, + "description": "One version's newest validation submission and the verdict of every step." + }, + "ValidationSubmissionState": { + "enum": [ + "Pending", + "Quarantined" + ], + "type": "string", + "description": "Where a submission stands: still to run, or stopped without being indexed." + }, + "ValidationSubmissionSummary": { + "required": [ + "submissionId", + "repository", + "packageId", + "packageVersion", + "state", + "created", + "failureMessages" + ], + "type": "object", + "properties": { + "submissionId": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "packageId": { + "type": "string", + "nullable": true + }, + "packageVersion": { + "type": "string", + "nullable": true + }, + "state": { + "$ref": "#/components/schemas/ValidationSubmissionState" + }, + "created": { + "type": "string", + "format": "date-time" + }, + "failureMessages": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "description": "One submission awaiting validation or quarantined." + }, + "ValidationViewModel": { + "type": "object", + "properties": { + "isSupported": { + "type": "boolean", + "description": "Whether validation can be administered here." + }, + "submissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationSubmissionSummary" + }, + "description": "The pending and quarantined submissions." + }, + "message": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string", + "nullable": true + }, + "hasPassword": { + "type": "boolean", + "description": "Whether the signed in administrator has a password to confirm with." + }, + "reauthenticated": { + "type": "boolean", + "description": "For an account without a password: it signed in again with its provider a moment ago." + }, + "canReauthenticate": { + "type": "boolean", + "description": "Whether an external provider is available to sign in again with." + }, + "returnPage": { + "type": "string", + "description": "The page to come back to after signing in again (the model of the confirmation partial)." + } + }, + "description": "What the validation queue screen (`/admin/validation`) shows: pending and quarantined submissions." + }, + "VirtualMemberDetail": { + "required": [ + "name", + "repository" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The member's name, as stored." + }, + "repository": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + }, + "exists": { + "type": "boolean", + "description": "Whether a repository of that name exists." + } + }, + "description": "One member of a virtual repository as the administration page lists it." + }, + "VirtualRepositoryDetail": { + "required": [ + "repository", + "members", + "deployRepository", + "deployTarget", + "effectiveMembers" + ], + "type": "object", + "properties": { + "repository": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VirtualMemberDetail" + }, + "description": "Its direct members in resolution order." + }, + "deployRepository": { + "type": "string", + "description": "The name of the member that receives deployments, if any.", + "nullable": true + }, + "deployTarget": { + "oneOf": [ + { + "enum": [ + null + ], + "nullable": true + }, + { + "$ref": "#/components/schemas/RepositoryInfo" + } + ] + }, + "effectiveMembers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepositoryInfo" + }, + "description": "The local and remote repositories that answer, in order, nested virtual members expanded." + } + }, + "description": "A virtual repository as the administration pages edit it." + } + }, + "securitySchemes": { + "bearer": { + "type": "http", + "description": "An API key.", + "scheme": "bearer" + }, + "apiKey": { + "type": "apiKey", + "description": "An API key.", + "name": "X-NuGet-ApiKey", + "in": "header" + }, + "session": { + "type": "http", + "description": "A session token: the accessToken of POST /api/ui/session, refreshed with POST /api/ui/session/refresh. Only /api/ui accepts it.", + "scheme": "bearer", + "bearerFormat": "bgs.xxx" + } + } + }, + "security": [ + { + "bearer": [ ] + }, + { + "apiKey": [ ] + }, + { + "session": [ ] + } + ], + "tags": [ + { + "name": "AccountApi" + }, + { + "name": "AccountOrganizationsApi" + }, + { + "name": "AccountPackagesApi" + }, + { + "name": "AccountSettingsApi" + }, + { + "name": "AdminAuditApi" + }, + { + "name": "AdminGroupsApi" + }, + { + "name": "AdminOperationsApi" + }, + { + "name": "AdminOrganizationsApi" + }, + { + "name": "AdminPackagesApi" + }, + { + "name": "AdminPermissionsApi" + }, + { + "name": "AdminProjectsApi" + }, + { + "name": "AdminRepositoriesApi" + }, + { + "name": "AdminSettingsApi" + }, + { + "name": "AdminUsersApi" + }, + { + "name": "ContactOwnersApi" + }, + { + "name": "DockerManageApi" + }, + { + "name": "MavenManageApi" + }, + { + "name": "NpmManageApi" + }, + { + "name": "PackageManageApi" + }, + { + "name": "ProfileApi" + }, + { + "name": "ReplicationApi" + }, + { + "name": "RetentionApi" + }, + { + "name": "ScanArtifactApi" + }, + { + "name": "ScanningApi" + }, + { + "name": "SessionApi" + }, + { + "name": "ValidationStatusApi" + }, + { + "name": "ApiCatalogApi" + }, + { + "name": "DockerBrowseApi" + }, + { + "name": "IndexApi" + }, + { + "name": "LegalApi" + }, + { + "name": "MavenBrowseApi" + }, + { + "name": "NpmBrowseApi" + }, + { + "name": "PackageApi" + }, + { + "name": "ReportAbuseApi" + }, + { + "name": "StatisticsApi" + }, + { + "name": "UploadApi" + } + ] +} \ No newline at end of file diff --git a/samples/BaGet.Frontend.React/package-lock.json b/samples/BaGet.Frontend.React/package-lock.json new file mode 100644 index 000000000..6235d22fa --- /dev/null +++ b/samples/BaGet.Frontend.React/package-lock.json @@ -0,0 +1,2226 @@ +{ + "name": "baget-frontend-react", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "baget-frontend-react", + "version": "0.0.0", + "dependencies": { + "openapi-fetch": "^0.13.5", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-router-dom": "^6.28.0" + }, + "devDependencies": { + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.4", + "openapi-typescript": "^7.5.2", + "typescript": "~5.6.3", + "vite": "^6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.11.tgz", + "integrity": "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", + "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.11.tgz", + "integrity": "sha512-OZ6+oaK7GMyg3IfCpj8JOmn8n+w2rJbDT0LLfVDTLb1ZFeKDh3AiNELgCMUw175IJHSkLl74hG0M0VLsvx+gag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.11" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.10.tgz", + "integrity": "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.9", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz", + "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.11", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@redocly/ajv": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/@redocly/ajv/-/ajv-8.11.2.tgz", + "integrity": "sha512-io1JpnwtIcvojV7QKDUSIuMN/ikdOUd1ReEnUnMKGfDVridQZ31J0MmIuqwuRjWDZfmvr+Q0MqCcfHM2gTivOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js-replace": "^1.0.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@redocly/config": { + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/@redocly/config/-/config-0.22.0.tgz", + "integrity": "sha512-gAy93Ddo01Z3bHuVdPWfCwzgfaYgMdaZPcfL7JZ7hWJoK9V0lXDbigTWkhiPFAaLWzbOJ+kbUQG1+XwIm0KRGQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@redocly/openapi-core": { + "version": "1.34.22", + "resolved": "https://registry.npmjs.org/@redocly/openapi-core/-/openapi-core-1.34.22.tgz", + "integrity": "sha512-dEyx4uHh6Pc6ZkdU9Xe8rA4h12Odq6QKU/fqseBn07xwVwskhHiF3KHhqmw5BR+jAiFTvKTmwCafFql/k1pSzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@redocly/ajv": "8.11.2", + "@redocly/config": "0.22.0", + "colorette": "1.4.0", + "https-proxy-agent": "7.0.6", + "js-levenshtein": "1.1.6", + "js-yaml": "4.3.2", + "minimatch": "5.1.9", + "pluralize": "8.0.0", + "yaml-ast-parser": "0.0.43" + }, + "engines": { + "node": ">=18.17.0", + "npm": ">=9.5.0" + } + }, + "node_modules/@remix-run/router": { + "version": "1.23.4", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.4.tgz", + "integrity": "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.65.1.tgz", + "integrity": "sha512-5coxNSjqOI2J3NkVhlp3u+zGcyjnowQFsU9sg7MMz4UPXY4Dv63kFGLt7ConXz9CNq2i0yuOJZAF/2RMrgI2OA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.65.1.tgz", + "integrity": "sha512-K0HFf6XMB3IYs+jDZ1/RRhZaVOwxNXrl0n4MDEyGDjuK7+B6K/nDJp8DCBitO3S1sK/fzNxAf9QZAny4AIUPtg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.65.1.tgz", + "integrity": "sha512-zkZrXYwNlIcSUmcwY2DpsaDHr0XjVUeQHCuSunG3eQD7/5Wn/DvI7OMUE8NRRweK87yG8ebJ1xGOzmwpMsbZQA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.65.1.tgz", + "integrity": "sha512-Zaed+R3cpkkA3aiNd7NO0GV5KFh/LVf8j6bGcoRdpoXkSm/mWH8M0oX2/3u/nyGcx/bHEovD9CzX+w9/gcpI4A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.65.1.tgz", + "integrity": "sha512-h12p3WJWhyJ9kir0zqAPr0rKNmBzOWIjoaOMT9OULs9KZQZCeOMKd+mGSvERjd9VxJYShd3zIxtrVxkYz6BEVA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.65.1.tgz", + "integrity": "sha512-yRBwh/5imKY4DydDulVtrjy8Jf7h7NQJUqZbgmZ3zFsCD9QqlnWvZ7RtEF+ecO1b+IukKjXlu5Bb9fehV3tIbg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.65.1.tgz", + "integrity": "sha512-1XuPiWYYaLE1UDOqhbKVOfsqxvfmFS/lYPSk92U1hEX1qRfSYH0hNeAlbxFIgjp4d6+YQmL95EPRgdvjbZEddA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.65.1.tgz", + "integrity": "sha512-Y3C5e55Yrf6p2r5rBcc4P9hFWVNi6oqWy/53I/AyCJJGlp3KRSpTP8eoUmVntchTbEnhgBgAgLO9flj9AvOdUw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.65.1.tgz", + "integrity": "sha512-Itj6coSswkYPIcVLczObXmwdplHNQQxyfnK1ppBg4czDaX8RiEzLKqU7EMc64BiBuiDZEUS+M93ktM18rv5llw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.65.1.tgz", + "integrity": "sha512-KeO8jTEqdrnhvcahufbimyMoI44vedRUp1bVz2QUnRX2vDm/hxzCPt5F8fERVD5fsHyTW/vXmCElT054VOSVOA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.65.1.tgz", + "integrity": "sha512-dDOz5VZZ+ZGnglpmET6VJefamWXFsgaVtuhSClf2/URZBp048jprD6z1hddsIMN6n1w+oUzGZEBp9u6Mlszsfg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.65.1.tgz", + "integrity": "sha512-JbfRKz8nJCuo8gn1Dqx8lQWEHw4qhZ3uRaHphw5vrSjnSptJTKTRC/bLKHh8QQMsEnhL4uq+bdg3tkiXbJ2q/A==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.65.1.tgz", + "integrity": "sha512-3oQpe1q0emSeCAssVHMQdOz5fz3PBH5my/Fr0ZekV2UMNL4ZiRa1ciikYlGQXyDkeqseYYv1InwOY8YPqY7RIQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.65.1.tgz", + "integrity": "sha512-nNV3HHi23o1LtpGGwH+Bav4hqnc4+klQtC96tSvCfvql8bLlNFTnTFiGl/jai2nve3eEr/vT2ocuyf+h+eMnYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.65.1.tgz", + "integrity": "sha512-b5zab0FryBxuocuDeqOsYGAg2EzjKw4mKA6LjQXCyewXjGv/BXqACBsY2cO45xM4hV2weYtdjGThP2VB2ByAYg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.65.1.tgz", + "integrity": "sha512-Rh08xZakiUxKNgI3hbgH9mivlx478lSqckS9s+Oc3/TX1VrAH3W8z/5wpJXR/v5VjqcJ/jJNVBg64PU1+iQsTQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.65.1.tgz", + "integrity": "sha512-qDgtS6juN3/k97y4kcD6XLFpXEo4f6CnG8lTOGYwlhrUYTrMyhN0WHdZCPAW5rqS0MqQG7qI7dxnjugt6QB39Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.65.1.tgz", + "integrity": "sha512-44IKzBPqXXVm0kt1O+F5eW4juR5FyIxGNlFkpP8qwIDzucBsjM1HCbdYUQrQw8rU/g6HRl/tfBm0+Qq4H4Ro3w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.65.1.tgz", + "integrity": "sha512-tvYWZ/h2PCHs558Xu7B6LptuRCV8lXV2xI75ONMcldII1m2zlFwuI4BJZi9M6rSMkYqcPLLtPUPrjyqfbzLOdg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.65.1.tgz", + "integrity": "sha512-gdyeucgZCnei3pXwadKVTEAOgRx0B+c847DUPR/PdOMmp3olhfkYo6r0J4PzRFZB5ZICZQTxntyvgmWH5xT7rg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.65.1.tgz", + "integrity": "sha512-Wf/NEKdn2SAL4Nvt8HyDtdkseWTwiLbZEOoNYnEaHkbso0B9eHO42vKnZh+OYsn+IMhAMcWcuIwPlBOgOXsUzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.65.1.tgz", + "integrity": "sha512-x9VSsDmsMsEWy4cr/mFeaEsXnVJ6Kc4NCAU/lCnwml3s7LQbZoa9+/qwc9etWHbuuDT5mYxdyyKUwo76njtjZw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.65.1.tgz", + "integrity": "sha512-RIDbiVvvLkN45mOFpbo6eYMgnuiBEB62BGR/0s4QJgGg2AvVxucDDNn67kpAcUoYyfmY8iX8/RifMcmxmmnejA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.65.1.tgz", + "integrity": "sha512-+KN8HIr88vN59JNxlrM2fMimzY43Y0lQB7+0xdVsFbvFCAA74CLKCdfzIHzzvndJryBc94Pm+MvwtukKjaS2ug==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.65.1.tgz", + "integrity": "sha512-+Y1Sd49cSDq60UOl8/U2HI0ebUvnSl/hDhMHQn+ouw17yb8fYwMWIazzJ4JFpSkjPE7sj5NTNSX9IoyEqcFfyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.31", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", + "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.7", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz", + "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^18.0.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", + "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.34", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz", + "integrity": "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001819", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz", + "integrity": "sha512-LFUqIIAwpzsIuevnKnsR9qnStBcgzPShTX61lBwN9uFkkf8o8zLiebEjbW8AYtZiF+1YKDWfdt/pWDtMuG8Xwg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/change-case": { + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/change-case/-/change-case-5.4.4.tgz", + "integrity": "sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/colorette": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", + "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.467", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.467.tgz", + "integrity": "sha512-Nw9X371rtZmYcBSnEijnCDONILjs93biCZO34juC7MBOmK8E+GFnyD4T/WvyrlJkppul7oxg6TwvtKst9SODTw==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/index-to-position": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/index-to-position/-/index-to-position-1.2.0.tgz", + "integrity": "sha512-Yg7+ztRkqslMAS2iFaU+Oa4KTSidr63OsFGlOrJoW981kIYO3CGCS3wA95P1mUi/IVSJkn0D479KTJpVpvFNuw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/js-levenshtein": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/js-levenshtein/-/js-levenshtein-1.1.6.tgz", + "integrity": "sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.60", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.60.tgz", + "integrity": "sha512-OmO8+GM1JUZqXET720VrJCwkjUCXmCMQm0Z3UDDRbfNLHS4NEAvY60j5jiFv0tkKw2PNNlqOLhahVmwJIOLDIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/openapi-fetch": { + "version": "0.13.8", + "resolved": "https://registry.npmjs.org/openapi-fetch/-/openapi-fetch-0.13.8.tgz", + "integrity": "sha512-yJ4QKRyNxE44baQ9mY5+r/kAzZ8yXMemtNAOFwOzRXJscdjSxxzWSNlyBAr+o5JjkUw9Lc3W7OIoca0cY3PYnQ==", + "license": "MIT", + "dependencies": { + "openapi-typescript-helpers": "^0.0.15" + } + }, + "node_modules/openapi-typescript": { + "version": "7.13.0", + "resolved": "https://registry.npmjs.org/openapi-typescript/-/openapi-typescript-7.13.0.tgz", + "integrity": "sha512-EFP392gcqXS7ntPvbhBzbF8TyBA+baIYEm791Hy5YkjDYKTnk/Tn5OQeKm5BIZvJihpp8Zzr4hzx0Irde1LNGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@redocly/openapi-core": "^1.34.6", + "ansi-colors": "^4.1.3", + "change-case": "^5.4.4", + "parse-json": "^8.3.0", + "supports-color": "^10.2.2", + "yargs-parser": "^21.1.1" + }, + "bin": { + "openapi-typescript": "bin/cli.js" + }, + "peerDependencies": { + "typescript": "^5.x" + } + }, + "node_modules/openapi-typescript-helpers": { + "version": "0.0.15", + "resolved": "https://registry.npmjs.org/openapi-typescript-helpers/-/openapi-typescript-helpers-0.0.15.tgz", + "integrity": "sha512-opyTPaunsklCBpTK8JGef6mfPhLSnyy5a0IN9vKtx3+4aExf+KxEqYwIy3hqkedXIB97u357uLMJsOnm3GVjsw==", + "license": "MIT" + }, + "node_modules/parse-json": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-8.3.0.tgz", + "integrity": "sha512-ybiGyvspI+fAoRQbIPRddCcSTV9/LsJbf0e/S85VLowVGzRmokfneg2kwVW/KU5rOXrPSbF1qAKPMgNTqqROQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.26.2", + "index-to-position": "^1.1.0", + "type-fest": "^4.39.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-router": { + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.6.tgz", + "integrity": "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.23.4" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8" + } + }, + "node_modules/react-router-dom": { + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.6.tgz", + "integrity": "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.23.4", + "react-router": "6.30.6" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.65.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.65.1.tgz", + "integrity": "sha512-HzD4IdphaPMvuAacnL/vtoq5B8FwqewKvxTtqYibWvP6VDyZ+UsTtlw5F8HIOIIpLQAkN2NOP/0sM3puo9xN/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.65.1", + "@rollup/rollup-android-arm64": "4.65.1", + "@rollup/rollup-darwin-arm64": "4.65.1", + "@rollup/rollup-darwin-x64": "4.65.1", + "@rollup/rollup-freebsd-arm64": "4.65.1", + "@rollup/rollup-freebsd-x64": "4.65.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.65.1", + "@rollup/rollup-linux-arm-musleabihf": "4.65.1", + "@rollup/rollup-linux-arm64-gnu": "4.65.1", + "@rollup/rollup-linux-arm64-musl": "4.65.1", + "@rollup/rollup-linux-loong64-gnu": "4.65.1", + "@rollup/rollup-linux-loong64-musl": "4.65.1", + "@rollup/rollup-linux-ppc64-gnu": "4.65.1", + "@rollup/rollup-linux-ppc64-musl": "4.65.1", + "@rollup/rollup-linux-riscv64-gnu": "4.65.1", + "@rollup/rollup-linux-riscv64-musl": "4.65.1", + "@rollup/rollup-linux-s390x-gnu": "4.65.1", + "@rollup/rollup-linux-x64-gnu": "4.65.1", + "@rollup/rollup-linux-x64-musl": "4.65.1", + "@rollup/rollup-openbsd-x64": "4.65.1", + "@rollup/rollup-openharmony-arm64": "4.65.1", + "@rollup/rollup-win32-arm64-msvc": "4.65.1", + "@rollup/rollup-win32-ia32-msvc": "4.65.1", + "@rollup/rollup-win32-x64-gnu": "4.65.1", + "@rollup/rollup-win32-x64-msvc": "4.65.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", + "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js-replace": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uri-js-replace/-/uri-js-replace-1.0.2.tgz", + "integrity": "sha512-VeBBt/nMxedczht3KDL2yBBMJqIxpCQLMZp3UJ1otcWwUHdQW4IiyHpJivExzSK+FdxTowRfGL4FmwDqH9+S8Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "6.4.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.5.tgz", + "integrity": "sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yaml-ast-parser": { + "version": "0.0.43", + "resolved": "https://registry.npmjs.org/yaml-ast-parser/-/yaml-ast-parser-0.0.43.tgz", + "integrity": "sha512-2PTINUwsRqSd+s8XxKaJWQlUuEMHJQyEuh2edBbW8KNJz0SJPwUSD2zRWqezFEdN7IzAgeuYHFUCF7o8zRdZ0A==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + } + } +} diff --git a/samples/BaGet.Frontend.React/package.json b/samples/BaGet.Frontend.React/package.json new file mode 100644 index 000000000..9c6895a58 --- /dev/null +++ b/samples/BaGet.Frontend.React/package.json @@ -0,0 +1,28 @@ +{ + "name": "baget-frontend-react", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "gen:api": "openapi-typescript openapi/ui.json -o src/api/schema.d.ts", + "dev": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview", + "lint": "tsc --noEmit", + "smoke": "node scripts/smoke.mjs" + }, + "dependencies": { + "openapi-fetch": "^0.13.5", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-router-dom": "^6.28.0" + }, + "devDependencies": { + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.4", + "openapi-typescript": "^7.5.2", + "typescript": "~5.6.3", + "vite": "^6.0.0" + } +} diff --git a/samples/BaGet.Frontend.React/scripts/smoke.mjs b/samples/BaGet.Frontend.React/scripts/smoke.mjs new file mode 100644 index 000000000..ddf9d7011 --- /dev/null +++ b/samples/BaGet.Frontend.React/scripts/smoke.mjs @@ -0,0 +1,36 @@ +// Smoke test: signs in with a session token and lists packages, using openapi-fetch like the app does. +// Usage: node scripts/smoke.mjs [userName] [password] [origin] +// A script sends no Origin header; pass a 4th argument to send one and see the CORS rules at work. +import createClient from 'openapi-fetch'; + +const [baseUrl = 'http://localhost:6060', userName = 'Admin', password = 'Admin1234!', origin] = process.argv.slice(2); +const headers = origin ? { Origin: origin } : {}; +const api = createClient({ baseUrl: baseUrl.replace(/\/$/, ''), headers }); + +function check(name, ok, detail = '') { + console.log(`${ok ? 'ok ' : 'FAIL'} ${name} ${detail}`); + if (!ok) process.exitCode = 1; +} + +// Anonymous: the home twin is public; the admin one is 401 SignIn. +const anon = await api.GET('/api/ui/packages', { params: { query: { q: '', p: 1 } } }); +check('anonymous packages list', anon.response.ok, `HTTP ${anon.response.status}, status=${anon.data?.status}`); +const denied = await api.GET('/api/ui/admin/users', { params: { query: {} } }); +check('anonymous admin users is 401', denied.response.status === 401, `HTTP ${denied.response.status}, status=${denied.error?.status}`); + +const signIn = await api.POST('/api/ui/session', { body: { userName, password } }); +const m = signIn.data?.model; +check('sign in', signIn.response.ok && !!m?.accessToken, `HTTP ${signIn.response.status}, status=${signIn.data?.status}, twoFactor=${m?.twoFactorRequired ?? false}`); +if (!m?.accessToken) process.exit(1); + +const auth = { Authorization: `Bearer ${m.accessToken}` }; +const list = await api.GET('/api/ui/packages', { params: { query: { q: '', p: 1 } }, headers: auth }); +check('signed-in packages list', list.response.ok, `${list.data?.model?.packages?.length ?? 0} packages`); +const users = await api.GET('/api/ui/admin/users', { params: { query: {} }, headers: auth }); +check('admin users', users.response.ok, `${users.data?.model?.users?.length ?? 0} users`); + +const refreshed = await api.POST('/api/ui/session/refresh', { body: { refreshToken: m.refreshToken } }); +check('refresh', refreshed.response.ok && !!refreshed.data?.model?.accessToken, `HTTP ${refreshed.response.status}`); + +const out = await api.POST('/api/ui/session/sign-out', { body: { refreshToken: m.refreshToken }, headers: auth }); +check('sign out', out.response.ok, `HTTP ${out.response.status}`); diff --git a/samples/BaGet.Frontend.React/src/App.tsx b/samples/BaGet.Frontend.React/src/App.tsx new file mode 100644 index 000000000..afaf98d67 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/App.tsx @@ -0,0 +1,50 @@ +import { Link, Route, Routes } from 'react-router-dom'; +import { useAuth } from './auth'; +import { AdminUsers } from './pages/AdminUsers'; +import { ConfirmEmail } from './pages/ConfirmEmail'; +import { ForgotPassword } from './pages/ForgotPassword'; +import { Home } from './pages/Home'; +import { PackageDetail } from './pages/PackageDetail'; +import { Register } from './pages/Register'; +import { ResetPassword } from './pages/ResetPassword'; +import { SignIn } from './pages/SignIn'; + +export function App() { + const auth = useAuth(); + if (!auth.ready) return

Loading...

; + return ( + <> +
+ BaGet + + + {auth.signedIn ? ( + <> + {auth.userName} + + + + ) : ( + Sign in + )} +
+
+ + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + Page not found. Home

} /> +
+
+ + ); +} diff --git a/samples/BaGet.Frontend.React/src/api/client.ts b/samples/BaGet.Frontend.React/src/api/client.ts new file mode 100644 index 000000000..dce9548dc --- /dev/null +++ b/samples/BaGet.Frontend.React/src/api/client.ts @@ -0,0 +1,53 @@ +import createClient, { type Middleware } from 'openapi-fetch'; +import { baseUrl } from '../config'; +import type { paths } from './schema'; +import { sessionStore } from './session'; + +export const api = createClient({ baseUrl }); + +const isSessionCall = (url: string) => new URL(url, location.href).pathname.includes('/api/ui/session'); + +// A request is consumed when sent, so keep a clone to replay it after a refresh. +const replayable = new WeakMap(); +// One refresh at a time: concurrent 401s share the same promise. +let refreshing: Promise | null = null; + +/** Exchanges the refresh token for a new pair. False = no new tokens (cleared when the server refused). */ +export function refreshSession(): Promise { + refreshing ??= (async () => { + const refreshToken = sessionStore.get().refreshToken; + if (!refreshToken) return false; + const { data, response } = await api.POST('/api/ui/session/refresh', { body: { refreshToken } }); + if (response.ok && data?.model?.accessToken) { + sessionStore.adopt(data.model); + return true; + } + // Only a refusal ends the session; a network error or a 5xx leaves the tokens for a retry. + if (response.status === 401 || response.status === 403) sessionStore.clear(); + return false; + })().finally(() => { + refreshing = null; + }); + return refreshing; +} + +const auth: Middleware = { + onRequest({ request }) { + replayable.set(request, request.clone()); + const { accessToken } = sessionStore.get(); + if (accessToken) request.headers.set('Authorization', `Bearer ${accessToken}`); + return request; + }, + async onResponse({ request, response }) { + // Renewed pair after a password / two-factor change made by this very session. + sessionStore.adoptHeaders(response.headers); + if (response.status !== 401 || isSessionCall(request.url) || !sessionStore.get().refreshToken) return response; + if (!(await refreshSession())) return response; + const retry = replayable.get(request); + if (!retry) return response; + retry.headers.set('Authorization', `Bearer ${sessionStore.get().accessToken}`); + return fetch(retry); // once: a second 401 is returned as is + }, +}; + +api.use(auth); diff --git a/samples/BaGet.Frontend.React/src/api/schema.d.ts b/samples/BaGet.Frontend.React/src/api/schema.d.ts new file mode 100644 index 000000000..5b3aebba9 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/api/schema.d.ts @@ -0,0 +1,29135 @@ +/** + * This file was auto-generated by openapi-typescript. + * Do not make direct changes to the file. + */ + +export interface paths { + "/api/ui/account/login": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The sign-in form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Signs in. Success sets the session cookie and continues at `next.localUrl` (the local return URL, else the site root), or at the second-factor screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["LoginForm"]; + "text/json": (null) | components["schemas"]["LoginForm"]; + "application/*+json": (null) | components["schemas"]["LoginForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLoginViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/loginwith2fa": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The authenticator code form (back to sign-in without the half-signed-in cookie). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + rememberMe?: boolean; + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Completes the sign-in with an authenticator code. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["TwoFactorLoginForm"]; + "text/json": (null) | components["schemas"]["TwoFactorLoginForm"]; + "application/*+json": (null) | components["schemas"]["TwoFactorLoginForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorLoginViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/loginwithrecoverycode": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The recovery code form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Completes the sign-in with a recovery code (each works once). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RecoveryCodeLoginForm"]; + "text/json": (null) | components["schemas"]["RecoveryCodeLoginForm"]; + "application/*+json": (null) | components["schemas"]["RecoveryCodeLoginForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRecoveryCodeLoginViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/logout": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The sign-out screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + put?: never; + /** + * Signs the user out. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/register": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The registration form (404 while `Accounts:AllowRegistration` is off). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Creates an account (and signs it in when no confirmation or approval is pending). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RegisterForm"]; + "text/json": (null) | components["schemas"]["RegisterForm"]; + "application/*+json": (null) | components["schemas"]["RegisterForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRegisterViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/confirmemail": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The target of the links in confirmation emails (a GET that confirms the address, like the page). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + userId?: string; + code?: string; + email?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfConfirmEmailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/forgotpassword": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The "forgot password" form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Asks for a reset link. The answer is the same whether or not an account matches. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "text/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "application/*+json": (null) | components["schemas"]["ForgotPasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/resetpassword": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The new-password form behind the link of a reset email. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + userId?: string; + code?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Sets the new password from the link; success continues at the sign-in screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ResetPasswordForm"]; + "text/json": (null) | components["schemas"]["ResetPasswordForm"]; + "application/*+json": (null) | components["schemas"]["ResetPasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfResetPasswordViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/reauthenticate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The "confirm it is you" screen (the button that starts the provider's sign-in is browser-only). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReauthenticateViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The organizations of the user. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations/create": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Create an organization. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["CreateOrganizationForm"]; + "text/json": (null) | components["schemas"]["CreateOrganizationForm"]; + "application/*+json": (null) | components["schemas"]["CreateOrganizationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Add a member (organization administrators only; 403 otherwise). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["AddOrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["AddOrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["AddOrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/organizations/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Remove a member (an administrator removes anyone; any member may leave; 403 otherwise). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RemoveOrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["RemoveOrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["RemoveOrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The package IDs the user owns, per repository. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/access": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * What the user may do in each repository (optionally for one package ID). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + package?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccountAccessViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/profile": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The user's own profile: continues at `next.localUrl` (`~/profiles/{name}`). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Account settings. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/change-password": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Change the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ChangePasswordForm"]; + "text/json": (null) | components["schemas"]["ChangePasswordForm"]; + "application/*+json": (null) | components["schemas"]["ChangePasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/change-email": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Change the email address (asks the password again). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ChangeEmailForm"]; + "text/json": (null) | components["schemas"]["ChangeEmailForm"]; + "application/*+json": (null) | components["schemas"]["ChangeEmailForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/unlink-external": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unlinks the account's login at an external provider (asks the password again; refused when it is the only way to sign in). Linking is browser-only: it redirects to the provider. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UnlinkExternalForm"]; + "text/json": (null) | components["schemas"]["UnlinkExternalForm"]; + "application/*+json": (null) | components["schemas"]["UnlinkExternalForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/settings/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Delete the account (asks the password again). Success signs the user out. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "text/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "application/*+json": (null) | components["schemas"]["PasswordConfirmationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Two-factor authentication (the setup key and QR code while it is off). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor/enable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Turn two-factor authentication on with a code from the authenticator; the answer carries the recovery codes, once. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["TwoFactorCodeForm"]; + "text/json": (null) | components["schemas"]["TwoFactorCodeForm"]; + "application/*+json": (null) | components["schemas"]["TwoFactorCodeForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor/disable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Turn two-factor authentication off (asks the password again). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "text/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "application/*+json": (null) | components["schemas"]["PasswordConfirmationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/twofactor/reset": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Reset the authenticator (asks the password again). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "text/json": (null) | components["schemas"]["PasswordConfirmationForm"]; + "application/*+json": (null) | components["schemas"]["PasswordConfirmationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfTwoFactorViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/apikeys": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The user's API keys (never their values) and the new-key form. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/apikeys/create": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Creates a key. The answer carries its value (`createdKey`) once. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ApiKeyForm"]; + "text/json": (null) | components["schemas"]["ApiKeyForm"]; + "application/*+json": (null) | components["schemas"]["ApiKeyForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/apikeys/revoke/{key}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Revokes a key. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiKeysViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/audit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the entries that match the filter. */ + get: { + parameters: { + query?: { + actor?: string; + subject?: string; + from?: string; + to?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAuditViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the groups. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a group and points at it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupCreation"]; + "text/json": (null) | components["schemas"]["GroupCreation"]; + "application/*+json": (null) | components["schemas"]["GroupCreation"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one group, with the member search for q. */ + get: { + parameters: { + query?: { + q?: string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/rename": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Renames the group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupRename"]; + "text/json": (null) | components["schemas"]["GroupRename"]; + "application/*+json": (null) | components["schemas"]["GroupRename"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds a user to the group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupMemberChange"]; + "text/json": (null) | components["schemas"]["GroupMemberChange"]; + "application/*+json": (null) | components["schemas"]["GroupMemberChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a user from the group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GroupMemberChange"]; + "text/json": (null) | components["schemas"]["GroupMemberChange"]; + "application/*+json": (null) | components["schemas"]["GroupMemberChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/groups/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the group with the grants and project roles that name it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfGroupDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/operations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the operations and their status. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Starts an operation on a repository. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OperationForm"]; + "text/json": (null) | components["schemas"]["OperationForm"]; + "application/*+json": (null) | components["schemas"]["OperationForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOperationsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the pending and quarantined submissions. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation/retry": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Validates the submission again. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SubmissionForm"]; + "text/json": (null) | components["schemas"]["SubmissionForm"]; + "application/*+json": (null) | components["schemas"]["SubmissionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation/release": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Indexes the quarantined package although validation failed. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SubmissionForm"]; + "text/json": (null) | components["schemas"]["SubmissionForm"]; + "application/*+json": (null) | components["schemas"]["SubmissionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/validation/reject": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the quarantined package. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SubmissionForm"]; + "text/json": (null) | components["schemas"]["SubmissionForm"]; + "application/*+json": (null) | components["schemas"]["SubmissionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/abuse": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the abuse reports (the unresolved ones unless all). */ + get: { + parameters: { + query?: { + all?: boolean; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/abuse/resolve": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Marks a report resolved. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["AbuseForm"]; + "text/json": (null) | components["schemas"]["AbuseForm"]; + "application/*+json": (null) | components["schemas"]["AbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/abuse/reopen": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Reopens a resolved report. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["AbuseForm"]; + "text/json": (null) | components["schemas"]["AbuseForm"]; + "application/*+json": (null) | components["schemas"]["AbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAbuseViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/cluster": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The cluster status; `?refresh=true` runs the health checks again. */ + get: { + parameters: { + query?: { + refresh?: boolean; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfClusterViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/formats": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The package formats this server can host. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfFormatsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/access-unavailable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Why the access screens are not available: the configured database has no access model. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAccessUnavailableViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the organizations. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminOrganizationsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one organization. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/rename": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Renames the organization. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationRenameForm"]; + "text/json": (null) | components["schemas"]["OrganizationRenameForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationRenameForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the organization (refused while it owns packages). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds a user to the organization. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/set-admin": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Makes a member an administrator of the organization, or not. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/organizations/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a member from the organization. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "text/json": (null) | components["schemas"]["OrganizationMemberForm"]; + "application/*+json": (null) | components["schemas"]["OrganizationMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfOrganizationDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the ownerless IDs of every repository, pageNumber being one-based. */ + get: { + parameters: { + query?: { + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/admin/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the ownerless IDs of every repository, pageNumber being one-based. */ + get: { + parameters: { + query?: { + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the permission targets. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a target and points at it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Previews the form patterns without saving anything. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/restore-built-ins": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Re-creates the built-in groups and targets that are missing (the upgrade defaults). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one target. principalType and principalName pre-fill the grant form. */ + get: { + parameters: { + query?: { + testPackage?: string; + principalType?: components["schemas"]["PrincipalType"]; + principalName?: string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Previews the form patterns (and the test package) without saving anything. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/save": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Replaces the target's patterns. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PermissionTargetForm"]; + "text/json": (null) | components["schemas"]["PermissionTargetForm"]; + "application/*+json": (null) | components["schemas"]["PermissionTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/set-grant": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Gives a principal the ticked actions through the target, replacing an earlier grant to it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["GrantForm"]; + "text/json": (null) | components["schemas"]["GrantForm"]; + "application/*+json": (null) | components["schemas"]["GrantForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/remove-grant": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a principal's grant. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PrincipalRemoval"]; + "text/json": (null) | components["schemas"]["PrincipalRemoval"]; + "application/*+json": (null) | components["schemas"]["PrincipalRemoval"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/permissions/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the target and its grants. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPermissionDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the projects the caller may open. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a project (server administrators only) and points at it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectCreation"]; + "text/json": (null) | components["schemas"]["ProjectCreation"]; + "application/*+json": (null) | components["schemas"]["ProjectCreation"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one project. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/set-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Gives a user or group a role in the project, replacing an earlier one. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectMemberForm"]; + "text/json": (null) | components["schemas"]["ProjectMemberForm"]; + "application/*+json": (null) | components["schemas"]["ProjectMemberForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Takes a user or group out of the project. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PrincipalRemoval"]; + "text/json": (null) | components["schemas"]["PrincipalRemoval"]; + "application/*+json": (null) | components["schemas"]["PrincipalRemoval"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/assign-repository": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Puts a repository in the project (server administrators only); it leaves any project it was in. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "text/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "application/*+json": (null) | components["schemas"]["ProjectRepositoryForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/unassign-repository": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Takes a repository out of the project (server administrators only). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "text/json": (null) | components["schemas"]["ProjectRepositoryForm"]; + "application/*+json": (null) | components["schemas"]["ProjectRepositoryForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/create-target": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a permission target that applies only to the project's repositories. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectTargetForm"]; + "text/json": (null) | components["schemas"]["ProjectTargetForm"]; + "application/*+json": (null) | components["schemas"]["ProjectTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Previews the new target's patterns without saving anything. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ProjectTargetForm"]; + "text/json": (null) | components["schemas"]["ProjectTargetForm"]; + "application/*+json": (null) | components["schemas"]["ProjectTargetForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/projects/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the project (server administrators only) with its members and targets; the repositories stay. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProjectDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the repositories (narrowed by format, kind, q) and describes the create forms. */ + get: { + parameters: { + query?: { + format?: string; + kind?: string; + q?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a local NuGet repository (`name`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/create/format": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a local repository of a format other than NuGet (`name`, `format`, `fields`, `anonymousRead`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/create/virtual": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a virtual repository with no members (`name`, `format`, `anonymousRead`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/create/remote": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates a remote repository (`name`, `format`, `remote`, `anonymousRead`, `password`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "text/json": (null) | components["schemas"]["RepositoryCreateForm"]; + "application/*+json": (null) | components["schemas"]["RepositoryCreateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoriesViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one repository. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + put?: never; + /** Saves the repository (`anonymousRead`; a remote one also `remote` and `password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/maven-settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the policy of a local Maven repository (`policy`, `redeploy`, `snapshotBuilds`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/test": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Asks a remote repository's upstream with the unsaved `remote` values and saves nothing (`password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/purge": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes everything a remote repository cached (`password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/purge-package": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes one cached package of a remote repository (`packageId`, `packageVersion`, `password`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/add-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds a member at the end of a virtual repository (`member`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/remove-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a member of a virtual repository (`member`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/move-member": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Moves a member of a virtual repository up or down (`member`, `direction`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/deploy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Sets the member of a virtual repository that receives uploads (`deploy`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Shows where a package version would come from in a virtual repository (`previewPackageId`, `previewVersion`). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "text/json": (null) | components["schemas"]["RepositoryEditRequest"]; + "application/*+json": (null) | components["schemas"]["RepositoryEditRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryEditViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/repositories/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows what deleting the repository does. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deletes the repository (refused while it holds packages or is a member of a virtual repository). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRepositoryDeleteViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the settings; section is the id of the section to show. */ + get: { + parameters: { + query?: { + section?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Saves the settings of one section: the body names the section, the password and the fields (`v:<key>` values, `reset:<key>`, + * `clear:<key>`, `copyData`), each an array of strings. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SettingsSubmission"]; + "text/json": (null) | components["schemas"]["SettingsSubmission"]; + "application/*+json": (null) | components["schemas"]["SettingsSubmission"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/copy-status": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The progress of the database copy. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDatabaseCopyStatusView"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/save-provider": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds or changes a named OpenID Connect provider (password in the body; takes effect after a restart; a blank secret keeps the saved one). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SignInProviderForm"]; + "text/json": (null) | components["schemas"]["SignInProviderForm"]; + "application/*+json": (null) | components["schemas"]["SignInProviderForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/remove-provider": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a named OpenID Connect provider saved on this screen (takes effect after a restart). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RemoveSignInProviderForm"]; + "text/json": (null) | components["schemas"]["RemoveSignInProviderForm"]; + "application/*+json": (null) | components["schemas"]["RemoveSignInProviderForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/set-log-level": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Sets the lowest level logged for one source. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["LogLevelForm"]; + "text/json": (null) | components["schemas"]["LogLevelForm"]; + "application/*+json": (null) | components["schemas"]["LogLevelForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/remove-log-level": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a per-source level saved on this screen. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["LogLevelForm"]; + "text/json": (null) | components["schemas"]["LogLevelForm"]; + "application/*+json": (null) | components["schemas"]["LogLevelForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/settings/test-telemetry": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Sends one test span to the posted, unsaved telemetry endpoint (`v:Telemetry:Otlp:*` fields) and answers the outcome; nothing is saved. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SettingsSubmission"]; + "text/json": (null) | components["schemas"]["SettingsSubmission"]; + "application/*+json": (null) | components["schemas"]["SettingsSubmission"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAdminSettingsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the users, filtered by q (user name contains), one page of them. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/approve": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Enables a self-registered account that waits for approval. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/promote": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Makes a user an administrator. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/demote": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes a user's administrator flag. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/reset-password": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Replaces a user's password with a generated one, which the answer carries once (`generatedPassword`). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/send-reset-link": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Mails a user a password reset link. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserChange"]; + "text/json": (null) | components["schemas"]["UserChange"]; + "application/*+json": (null) | components["schemas"]["UserChange"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/create": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Creates an account (typed, generated or invited password). A generated password is in the answer once. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserCreation"]; + "text/json": (null) | components["schemas"]["UserCreation"]; + "application/*+json": (null) | components["schemas"]["UserCreation"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUsersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one account. package is a package ID to evaluate the effective permissions for. */ + get: { + parameters: { + query?: { + package?: string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/approve": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Enables the account when it waits for approval. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/revoke-key": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Revokes one of the account's API keys. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserKeyForm"]; + "text/json": (null) | components["schemas"]["UserKeyForm"]; + "application/*+json": (null) | components["schemas"]["UserKeyForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/add-group": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Adds the account to a group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserGroupForm"]; + "text/json": (null) | components["schemas"]["UserGroupForm"]; + "application/*+json": (null) | components["schemas"]["UserGroupForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/remove-group": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Removes the account from a group. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserGroupForm"]; + "text/json": (null) | components["schemas"]["UserGroupForm"]; + "application/*+json": (null) | components["schemas"]["UserGroupForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserDetailViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows what deleting the account does. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deletes the account after the administrator's password. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UserDeletionForm"]; + "text/json": (null) | components["schemas"]["UserDeletionForm"]; + "application/*+json": (null) | components["schemas"]["UserDeletionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDeleteUserViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/users/{name}/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the package IDs one user owns. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/admin/users/{name}/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the package IDs one user owns. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUserPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/contact-owners": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The form's state; 404 when the package has no owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Sends the message to the owners (400 with the field errors when the message is missing or too long). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ContactOwnersForm"]; + "text/json": (null) | components["schemas"]["ContactOwnersForm"]; + "application/*+json": (null) | components["schemas"]["ContactOwnersForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/contact-owners": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The form's state; 404 when the package has no owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Sends the message to the owners (400 with the field errors when the message is missing or too long). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ContactOwnersForm"]; + "text/json": (null) | components["schemas"]["ContactOwnersForm"]; + "application/*+json": (null) | components["schemas"]["ContactOwnersForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfContactOwnersViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/delete-tag/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a tag, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/delete-tag/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a tag, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/delete-manifest/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a manifest with its tags, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/delete-manifest/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a manifest with its tags, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/prune/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes the layers no manifest uses, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/prune/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes the layers no manifest uses, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-manage/delete-image/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole image, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-manage/delete-image/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole image, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["DockerManageForm"]; + "text/json": (null) | components["schemas"]["DockerManageForm"]; + "application/*+json": (null) | components["schemas"]["DockerManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/delete-file": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one file of the chosen version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-file": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one file of the chosen version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/delete-version": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-version": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes one version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/delete-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole artifact, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/delete-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the whole artifact, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-manage/{group}/{artifact}/cleanup": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes old snapshot builds of a version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-manage/{group}/{artifact}/cleanup": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes old snapshot builds of a version, after the password. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["MavenManageForm"]; + "text/json": (null) | components["schemas"]["MavenManageForm"]; + "application/*+json": (null) | components["schemas"]["MavenManageForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/add-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/add-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/remove-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/remove-owner/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "text/json": (null) | components["schemas"]["NpmManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/set-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Points a dist-tag at a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/set-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Points a dist-tag at a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/remove-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a dist-tag. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/remove-tag/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a dist-tag. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageTagForm"]; + "text/json": (null) | components["schemas"]["NpmManageTagForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageTagForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/deprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/deprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/undeprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/undeprecate/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/unpublish/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes one version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/unpublish/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes one version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-manage/unpublish-all/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes every version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-manage/unpublish-all/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unpublishes every version, after the password is confirmed. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "text/json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + "application/*+json": (null) | components["schemas"]["NpmManageUnpublishForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmManageViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The screen. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/add-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/remove-owner": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes an owner. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "text/json": (null) | components["schemas"]["PackageManageOwnerForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageOwnerForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/unlist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unlists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/unlist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unlists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/relist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Relists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/relist": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Relists a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a version as the server is configured to (unlist or permanent). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes a version as the server is configured to (unlist or permanent). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/hard-delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes a version (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "text/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes a version (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "text/json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageHardDeleteForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/hard-delete-all": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes every version and the owners (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "text/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "application/*+json": (null) | components["schemas"]["PackageManagePasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/hard-delete-all": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Permanently deletes every version and the owners (administrators, after the password). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "text/json": (null) | components["schemas"]["PackageManagePasswordForm"]; + "application/*+json": (null) | components["schemas"]["PackageManagePasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/deprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/deprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deprecates a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "text/json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageDeprecateForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/undeprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/undeprecate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a version's deprecation. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/add-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds a vulnerability to a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/add-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Adds a vulnerability to a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/remove-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a vulnerability from a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/remove-vulnerability": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Removes a vulnerability from a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "text/json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageRemoveVulnerabilityForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/set-verified": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Marks or unmarks the ID as verified (administrators). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "text/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/set-verified": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Marks or unmarks the ID as verified (administrators). + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "text/json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVerifiedForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/delete-symbols": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the PDBs recorded for a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/delete-symbols": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Deletes the PDBs recorded for a version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "text/json": (null) | components["schemas"]["PackageManageVersionForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageVersionForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/manage/resolve-report": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Resolves an abuse report. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageReportForm"]; + "text/json": (null) | components["schemas"]["PackageManageReportForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageReportForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/manage/resolve-report": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Resolves an abuse report. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PackageManageReportForm"]; + "text/json": (null) | components["schemas"]["PackageManageReportForm"]; + "application/*+json": (null) | components["schemas"]["PackageManageReportForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageManageScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/profiles/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The profile named name; 404 when neither a user nor an organization has it. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/profiles/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The profile named name; 404 when neither a user nor an organization has it. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfProfileViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the replications and the form that creates one. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a replication and opens it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ReplicationBody"]; + "text/json": (null) | components["schemas"]["ReplicationBody"]; + "application/*+json": (null) | components["schemas"]["ReplicationBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one replication with its log. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/save": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the settings. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ReplicationBody"]; + "text/json": (null) | components["schemas"]["ReplicationBody"]; + "application/*+json": (null) | components["schemas"]["ReplicationBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/test": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Tests the connection with the typed settings; saves nothing. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ReplicationBody"]; + "text/json": (null) | components["schemas"]["ReplicationBody"]; + "application/*+json": (null) | components["schemas"]["ReplicationBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/run": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a run. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/resume": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a run that continues the last interrupted or failed one. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/stop": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Asks the running replication to stop; it ends as interrupted and can be resumed. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/replication/{key}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the configuration with its log. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReplicationConfigViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the policies and the form that creates one. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + }; + }; + put?: never; + /** Creates a policy and opens it. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "text/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "application/*+json": (null) | components["schemas"]["RetentionPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows one policy, its last run and report. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/save": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the rules. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "text/json": (null) | components["schemas"]["RetentionPolicyBody"]; + "application/*+json": (null) | components["schemas"]["RetentionPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/dry-run": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a dry run: the report of what a run would delete. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/run": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a run that deletes. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/{key}/delete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Deletes the policy (what it deleted stays deleted). */ + post: { + parameters: { + query?: never; + header?: never; + path: { + key: number; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["PasswordForm"]; + "text/json": (null) | components["schemas"]["PasswordForm"]; + "application/*+json": (null) | components["schemas"]["PasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionPolicyViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/holds": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Lists the legal holds (of `?repository=` only, when given). */ + get: { + parameters: { + query?: { + repository?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/holds/add": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Places a hold. */ + post: { + parameters: { + query?: { + repository?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionHoldForm"]; + "text/json": (null) | components["schemas"]["RetentionHoldForm"]; + "application/*+json": (null) | components["schemas"]["RetentionHoldForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/retention/holds/remove": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Lifts a hold. */ + post: { + parameters: { + query?: { + repository?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["RetentionHoldRemoval"]; + "text/json": (null) | components["schemas"]["RetentionHoldRemoval"]; + "application/*+json": (null) | components["schemas"]["RetentionHoldRemoval"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfRetentionHoldsViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/scan-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Shows the form (and the stored result) of the version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + name?: string; + version?: string; + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Scans the version now (or queues it, for an image) and shows the outcome. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanArtifactForm"]; + "text/json": (null) | components["schemas"]["ScanArtifactForm"]; + "application/*+json": (null) | components["schemas"]["ScanArtifactForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/scan-artifact": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Shows the form (and the stored result) of the version. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: { + name?: string; + version?: string; + returnUrl?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + put?: never; + /** + * Scans the version now (or queues it, for an image) and shows the outcome. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanArtifactForm"]; + "text/json": (null) | components["schemas"]["ScanArtifactForm"]; + "application/*+json": (null) | components["schemas"]["ScanArtifactForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The overview of every repository and project. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanningViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The dashboard of a repository: `?min=` is the lowest severity listed (0 to 3), `?p=` the page. */ + get: { + parameters: { + query?: { + min?: number | string; + p?: number | string; + }; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/{name}/policy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the repository policy; empty values remove it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanPolicyBody"]; + "text/json": (null) | components["schemas"]["ScanPolicyBody"]; + "application/*+json": (null) | components["schemas"]["ScanPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/{name}/scan": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Starts a scan of every artifact of the repository in the background. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanRepositoryViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/projects/{name}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The scanning policy of a project. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/scanning/projects/{name}/policy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Saves the project policy; empty values remove it. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + name: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ScanPolicyBody"]; + "text/json": (null) | components["schemas"]["ScanPolicyBody"]; + "application/*+json": (null) | components["schemas"]["ScanPolicyBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfScanProjectViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Signs in with the user name and password. Answers the tokens, or `twoFactorRequired` with a short-lived `twoFactorTicket` for + * `/session/two-factor` or `/session/recovery-code`. 401 for wrong credentials, 403 for a locked, unapproved or unconfirmed account. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionSignInForm"]; + "text/json": (null) | components["schemas"]["SessionSignInForm"]; + "application/*+json": (null) | components["schemas"]["SessionSignInForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/two-factor": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Completes a sign-in with a code of the authenticator app. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionTwoFactorForm"]; + "text/json": (null) | components["schemas"]["SessionTwoFactorForm"]; + "application/*+json": (null) | components["schemas"]["SessionTwoFactorForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/recovery-code": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Completes a sign-in with a recovery code (each works once). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionRecoveryCodeForm"]; + "text/json": (null) | components["schemas"]["SessionRecoveryCodeForm"]; + "application/*+json": (null) | components["schemas"]["SessionRecoveryCodeForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/refresh": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Exchanges the refresh token for a new pair of tokens (the authentication time is kept; the session ends `Accounts:SessionMaxLifetime` after the sign-in). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionRefreshForm"]; + "text/json": (null) | components["schemas"]["SessionRefreshForm"]; + "application/*+json": (null) | components["schemas"]["SessionRefreshForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/exchange": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Exchanges the 60-second `exchange_token` of an external sign-in's redirect for the tokens (or the two-factor ticket). */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionExchangeForm"]; + "text/json": (null) | components["schemas"]["SessionExchangeForm"]; + "application/*+json": (null) | components["schemas"]["SessionExchangeForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/sign-out": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Ends the session: the client forgets its tokens. With `everywhere` the account's security stamp changes and every token and cookie + * session of the account stops working. The caller is the access token, or the refresh token in the body. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionSignOutForm"]; + "text/json": (null) | components["schemas"]["SessionSignOutForm"]; + "application/*+json": (null) | components["schemas"]["SessionSignOutForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/cookie": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Signs in with the cookie (same origin only; needs the antiforgery token of `GET /api/ui/antiforgery` fetched while signed out, so a cross-site page cannot + * sign a visitor in): the rules of `POST /session`, the second factor in the same endpoint (`ticket` with `code` or `recoveryCode`), but the answer holds no tokens. + * Fetch the antiforgery token again afterwards: it is bound to the signed-in user. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["SessionCookieForm"]; + "text/json": (null) | components["schemas"]["SessionCookieForm"]; + "application/*+json": (null) | components["schemas"]["SessionCookieForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/cookie/sign-out": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Signs the cookie session out (same origin; send the cookie with the antiforgery header). 401 for anything but a cookie session. */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfEmptyScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/providers": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The external sign-in providers a client can offer before anyone is signed in (the sign-in screen's model is interactive-only): their ids, to put in + * `/session/external/{id}`, and the names for the buttons. An empty list when none is configured. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfSessionProvidersModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/antiforgery": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The antiforgery request token for a same-origin client that uses the cookie session: send it in the `X-XSRF-TOKEN` header (every method). It + * is bound to the signed-in user, so fetch it again after signing in or out. Also sets the antiforgery cookie. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfAntiforgeryTokenModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/account/resend-confirmation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Mails a new confirmation link to an account whose address is not confirmed. The answer is the same whether or not an account matches or the mail was allowed + * (one per account per ten minutes, and per client); 404 without outgoing mail. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "text/json": (null) | components["schemas"]["ForgotPasswordForm"]; + "application/*+json": (null) | components["schemas"]["ForgotPasswordForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfForgotPasswordViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/external/{provider}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Starts the sign-in with the external provider (a browser navigation, not a fetch). The result comes back in the URL fragment of + * returnUrl, which must lie under `Frontend:SpaBasePath` of this server, or be an address of an origin listed in `Cors:AllowedOrigins`. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path: { + provider: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/session/external-callback": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The provider's answer: redirects to returnUrl with, in the URL fragment, `exchange_token` (+ `exchange_expires_at`, `user_name`), to exchange within + * a minute at `POST /api/ui/session/exchange`, or `notice` (account created, not usable yet) or `error`. No token of the session itself is ever put in a URL. + */ + get: { + parameters: { + query?: { + returnUrl?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/validation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The submissions of the ID. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/validation": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The submissions of the ID. + * @description Interactive session only (bearer session token or same-origin cookie with antiforgery header); API keys are refused. This screen changes or reveals credentials or ownership, so it answers 403 to an API key and to an anonymous caller. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfValidationStatusViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/admin/api": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The operations of the REST API. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfApiCatalogViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-images": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The image list with a search box and the client commands. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-images": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The image list with a search box and the client commands. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/docker-images/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One image: tags, manifests, and with `digest` one manifest in full. */ + get: { + parameters: { + query?: { + digest?: string; + artifactType?: string; + }; + header?: never; + path: { + image: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/docker-images/{image}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One image: tags, manifests, and with `digest` one manifest in full. */ + get: { + parameters: { + query?: { + digest?: string; + artifactType?: string; + }; + header?: never; + path: { + image: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfDockerImageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/home": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The front page of the repository, or the results when the query asks for something. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/home": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The front page of the repository, or the results when the query asks for something. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One page of the package list. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One page of the package list. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + packageType?: string; + framework?: string; + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfIndexScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/privacy": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The Privacy Policy. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/terms": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The Terms of Use. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfLegalScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-artifacts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The artifact list with a search box and the client configuration. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-artifacts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The artifact list with a search box and the client configuration. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-artifacts/{group}/{artifact}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + version: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deploys the chosen files under the given coordinates. */ + post: { + parameters: { + query?: { + groupId?: string; + artifactId?: string; + version?: string; + packaging?: string; + classifier?: string; + apiKey?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + file?: components["schemas"]["IFormFile"]; + } & { + pom?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Deploys the chosen files under the given coordinates. */ + post: { + parameters: { + query?: { + groupId?: string; + artifactId?: string; + version?: string; + packaging?: string; + classifier?: string; + apiKey?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + file?: components["schemas"]["IFormFile"]; + } & { + pom?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The package list with a search box. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-packages": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The package list with a search box. */ + get: { + parameters: { + query?: { + q?: string; + p?: number | string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackagesViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One package: readme, versions, dist-tags, install commands. */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One package: readme, versions, dist-tags, install commands. */ + get: { + parameters: { + query?: { + version?: string; + }; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmPackageViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/npm-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Publishes the chosen tarball with the dist-tag tag (default `latest`). */ + post: { + parameters: { + query?: { + tag?: string; + apiKey?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/npm-upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The upload form's state. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + put?: never; + /** Publishes the chosen tarball with the dist-tag tag (default `latest`). */ + post: { + parameters: { + query?: { + tag?: string; + apiKey?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfNpmUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/{version}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}/{version}/report-abuse": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The empty form. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + put?: never; + /** Records the report. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["ReportAbuseForm"]; + "text/json": components["schemas"]["ReportAbuseForm"]; + "application/*+json": components["schemas"]["ReportAbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}/{version}/report-abuse": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The empty form. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + put?: never; + /** Records the report. */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + version: string; + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["ReportAbuseForm"]; + "text/json": components["schemas"]["ReportAbuseForm"]; + "application/*+json": components["schemas"]["ReportAbuseForm"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfReportAbuseScreen"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/stats": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The feed's statistics. */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/stats": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The feed's statistics. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfStatisticsViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Step one: the form. */ + get: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Step one: the form. */ + get: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload/stage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Stages the chosen file and describes what it contains. */ + post: { + parameters: { + query?: { + id?: string; + apiKey?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload/stage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Stages the chosen file and describes what it contains. */ + post: { + parameters: { + query?: { + id?: string; + apiKey?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/x-www-form-urlencoded": { + package?: components["schemas"]["IFormFile"]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload/submit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Publishes the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload/submit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Publishes the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/upload/cancel": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Discards the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/upload/cancel": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Discards the staged upload. */ + post: { + parameters: { + query?: { + id?: string; + }; + header?: never; + path: { + repo: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": (null) | components["schemas"]["UploadTokenRequest"]; + "text/json": (null) | components["schemas"]["UploadTokenRequest"]; + "application/*+json": (null) | components["schemas"]["UploadTokenRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfUploadViewModel"]; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/maven-artifacts/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/maven-artifacts/{group}/{artifact}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** One artifact: versions, files, POM, the dependency to copy. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + group: string; + artifact: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfMavenArtifactViewModel"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ui/r/{repo}/packages/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Shows the package. */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + repo: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Invalid: the input was refused. The body still holds the screen's model and the errors by field ("" = the whole form). */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description SignIn: the caller must authenticate (a session token, an API key, or the cookie with the antiforgery header). Carries WWW-Authenticate: Bearer. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description Forbidden: the caller may not do this. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + /** @description NotFound: no such screen or item, or the caller may not know it exists. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ScreenResultOfPackageScreen"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; +} +export type webhooks = Record; +export interface components { + schemas: { + /** @description A decision on an abuse report. */ + AbuseForm: { + /** + * Format: int32 + * @description The report's number. + */ + key: number; + /** @description Whether the list to come back to shows the resolved reports too. */ + all: boolean; + }; + /** @description An abuse report with the name of its repository. */ + AbuseReportSummary: { + /** Format: int32 */ + key: number; + repository: string; + packageId: string | null; + packageVersion: string | null; + reason: string | null; + details: string | null; + reporterEmail: string | null; + /** Format: date-time */ + created: string; + /** Format: date-time */ + resolved: string | null; + isResolved?: boolean; + }; + /** @description What the abuse reports screen (`/admin/abuse`) shows: the reports of every repository. */ + AbuseViewModel: { + /** @description Show the resolved reports too. */ + all?: boolean; + /** @description Whether reports are stored with the configured database. */ + isSupported?: boolean; + /** @description The reports, newest first. */ + items?: components["schemas"]["AbuseReportSummary"][]; + message?: string | null; + error?: string | null; + }; + /** + * @description What a permission grants. Independent flags: AccessAction.Deploy does not imply AccessAction.Read, as in + * Artifactory. Package ownership (IPackageAuthorizationService) is a second, separate requirement + * for the actions that change an existing package ID. + * @enum {string} + */ + AccessAction: "None" | "Read" | "Annotate" | "Deploy" | "Delete" | "Manage" | "All"; + /** @description One change to the access model. */ + AccessAuditEntry: { + /** Format: int32 */ + key?: number; + /** Format: date-time */ + created?: string; + /** @description The user name that made the change; null for the server itself. */ + actor?: string | null; + /** @description What happened, such as `group.create` or `grant.set`. */ + action?: string | null; + /** @description What it happened to (a group, target or repository name). */ + subject?: string | null; + /** @description JSON with the details (never credentials). */ + details?: string | null; + }; + /** @description What a caller may do in a repository, and why (Task<AccessExplanation> IAccessEvaluator.ExplainAsync(BaGetPrincipal? principal, RepositoryInfo repository, string? packageId, CancellationToken cancellationToken)). */ + AccessExplanation: { + actions: components["schemas"]["AccessAction"]; + /** + * @description A rule that grants everything or bypasses the model (administrator, global API key, no + * access model), instead of Reasons; null when the grants decide. + */ + override: string | null; + /** @description The grants and project roles that apply to the caller. */ + reasons: components["schemas"]["AccessReason"][]; + }; + /** @description One grant or project role behind an access decision, for the admin pages that explain it. */ + AccessReason: { + /** @description Where it comes from, such as `Permission target 'Anyone reads every repository'`. */ + source: string; + principalType: components["schemas"]["PrincipalType"]; + /** @description The principal's id (user id, group or organization key). */ + principalId: string; + /** @description The principal in words (a user name, `group Developers`, `organization Contoso`). */ + principal: string; + granted: components["schemas"]["AccessAction"]; + effective: components["schemas"]["AccessAction"]; + /** @description The package filter of the target, such as `Contoso.* except Contoso.Internal.*`; null for all. */ + packages: string | null; + /** @description Why AccessAction AccessReason.Effective differs from AccessAction AccessReason.Granted, if it does. */ + note: string | null; + }; + /** @description What the "access control unavailable" screen (`/admin/access-unavailable`) says: why, as the JSON carries it (the page has fixed text). */ + AccessUnavailableViewModel: { + /** @description Why the access screens are not available. */ + reason: string; + }; + /** @description The "My access" screen: the signed-in user's own effective permissions. */ + AccountAccessViewModel: { + /** @description A package ID to evaluate the grants for; empty means the repository as a whole. */ + package?: string | null; + /** @description The repositories where the user holds some action. */ + rows?: components["schemas"]["RepositoryAccessRow"][]; + /** @description The projects the user administers. */ + administeredProjects?: string[]; + /** @description Whether the configured database has an access model at all. */ + modelAvailable?: boolean; + }; + /** @description One API key as the screen lists it: never the key itself or its hash (only the creation response shows a new key, once). */ + AccountApiKey: { + /** + * Format: int32 + * @description The key's id (the number the revoke button posts). + */ + key?: number; + /** @description What the key is for. */ + description?: string | null; + /** @description What the key may do. */ + scopes?: string[]; + /** @description The package IDs the key applies to. */ + packageGlobPattern?: string | null; + /** + * Format: date-time + * @description When it was created. + */ + created?: string; + /** + * Format: date-time + * @description When it expires; null = never. + */ + expires?: string | null; + }; + /** @description One organization with its members. */ + AccountOrganization: { + /** @description The organization's name. */ + name?: string | null; + /** @description Whether the current user administers it. */ + isAdmin?: boolean; + /** @description The members, by user name. */ + members?: components["schemas"]["AccountOrganizationMember"][] | null; + }; + /** @description One member of an organization (a flat record, so the screen's JSON names its fields). */ + AccountOrganizationMember: { + /** @description The member's user name. */ + userName: string; + /** @description Whether the member administers the organization. */ + isAdmin: boolean; + }; + /** @description The "My packages" screen: the packages the user owns in each repository. */ + AccountPackagesViewModel: { + /** @description The owned packages of each repository that has any, `default` first. */ + groups?: components["schemas"]["RepositoryPackages"][]; + /** @description Whether the user owns nothing in any repository. */ + isEmpty?: boolean; + /** @description Whether the list needs repository headings: more than the default repository holds packages of the user. */ + showRepositoryNames?: boolean; + }; + /** @description What the "add a member" form posts. */ + AddOrganizationMemberForm: { + /** @description The organization. */ + organization?: string | null; + /** @description The user to add. */ + userName?: string | null; + /** @description Whether the new member administers the organization. */ + isAdmin?: boolean; + }; + /** @description What deleting a user as an administrator would remove or change. */ + AdminDeletionPreview: { + /** + * Format: int32 + * @description How many API keys go. + */ + apiKeys: number; + /** @description Package IDs the user owns directly. */ + directPackageIds: string[]; + /** @description The subset nobody else owns, in every repository. */ + soleOwnedPackages: components["schemas"]["SoleOwnedPackage"][]; + /** @description What happens to each organization the user belongs to. */ + organizations: components["schemas"]["OrganizationOutcome"][]; + }; + /** @enum {string} */ + AdminJobState: "Running" | "Succeeded" | "Failed"; + /** @description The last run of an operation on a repository. In memory: a restart forgets it. */ + AdminJobStatus: { + operation?: string; + repository?: string; + state?: components["schemas"]["AdminJobState"]; + actor?: string | null; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + /** @description The result on success, the exception type and message on failure. */ + message?: string | null; + }; + /** @description What the organizations screen (`/admin/organizations`) lists: every organization with its members and packages. */ + AdminOrganizationsViewModel: { + /** @description The organizations, by name. */ + organizations?: components["schemas"]["OrganizationSummary"][]; + }; + /** @description A package ID as the administrator pages list it. */ + AdminPackageRow: { + package: components["schemas"]["OwnedPackage"]; + /** @description The names of its owners; empty for an ownerless ID. */ + owners: string[]; + /** + * @description The repository the ID is in; ownership and versions are per repository. + * @default default + */ + repositoryName: string; + }; + /** @description What the ownerless packages screen (`/admin/packages`) shows: the package IDs nobody owns, in every repository. */ + AdminPackagesViewModel: { + /** + * Format: int32 + * @description One-based page number (the `p` query value). + */ + pageNumber?: number; + /** @description The ownerless IDs on this page. */ + packages?: components["schemas"]["AdminPackageRow"][]; + /** @description Whether a Repository column is worth showing: some listed ID is outside the default repository. */ + showRepository?: boolean; + /** + * Format: int32 + * @description The number of pages. + */ + pageCount?: number; + }; + /** @description What the server settings screen (`/admin/settings`) shows: every registered setting by section and the state of the last save. */ + AdminSettingsViewModel: { + /** @description The same sections as IReadOnlyList<IGrouping<string, SettingState>> AdminSettingsViewModel.Sections, each with its key and DOM id, as the JSON carries them. */ + sectionList?: components["schemas"]["SettingsSection"][] | null; + /** @description The file the settings are saved to. */ + overridesPath?: string | null; + /** @description The keys changed since startup that only apply after a restart. */ + pendingRestart?: string[]; + /** @description Why the last save was refused. */ + errors?: string[]; + /** @description The section the IReadOnlyList<string> AdminSettingsViewModel.Errors belong to. */ + errorSection?: string | null; + /** @description The per-source log levels (`Serilog:MinimumLevel:Override`) shown under the Serilog section. */ + logLevels?: components["schemas"]["LogLevelOverride"][]; + /** @description The level names offered for a source. */ + logLevelNames?: string[] | null; + /** @description The named OpenID Connect providers (`Accounts:OpenIdConnectProviders`) shown in the "Sign-in providers" panel of the Accounts section. No secret is carried. */ + signInProviders?: components["schemas"]["SignInProviderView"][]; + /** @description Why the overrides file could not be read, or null. */ + loadError?: string | null; + /** @description The state of each telemetry signal for the Telemetry section, or null when the host exports no telemetry. */ + telemetrySignals?: components["schemas"]["TelemetrySignalReport"][] | null; + /** + * @description True when this host exports telemetry (registers ITelemetryDiagnostics). When false the Telemetry + * section stays editable (the settings file may be shared with a host that does export) but a note says it has no effect here. + */ + hostExportsTelemetry?: boolean; + telemetryTest?: (null) | components["schemas"]["TelemetryTestOutcome"]; + /** + * @description Whether the running database is relational, so a change of database can copy the data (the "Copy all data" option of the + * Database section). + */ + canCopyDatabase?: boolean; + /** @description The `Database:Type` values a copy can target; the option is hidden for any other type. */ + copyTargetTypes?: string[]; + copyStatus?: components["schemas"]["DatabaseCopyStatus"]; + /** + * @description The DOM id (slug) of the section shown; every other section is rendered `hidden`. Chosen by the workflow: the failed + * section, else the Telemetry section after "Test connection", else the `?section=` value, else the first section. The URL + * fragment is only known to the browser, so the page's script applies it on load unless bool AdminSettingsViewModel.SelectionLocked. + */ + selectedId?: string; + /** @description True when the server picked the section for a reason the URL fragment must not override (a failed save, a connection test). */ + selectionLocked?: boolean; + message?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What `GET /api/ui/antiforgery` answers: the request token to send with a cookie session. */ + AntiforgeryTokenModel: { + /** @description The header to send the token in (`X-XSRF-TOKEN`). */ + headerName?: string | null; + /** @description The request token. It is bound to the signed-in user: ask again after signing in or out. */ + requestToken?: string | null; + }; + /** @description What the REST API page shows (also the model of its JSON twin). */ + ApiCatalogViewModel: { + /** @description Every operation, ordered by path. */ + endpoints: components["schemas"]["ApiEndpointSummary"][]; + /** @description The address of the API on this server. */ + apiBase: string; + /** @description The header that carries the password of the owner. */ + confirmHeader: string; + /** @description Where the OpenAPI document is. */ + openApiUrl?: string | null; + }; + /** @description One operation of the REST API as the page (and the JSON twin) lists it: flat, with no reflection objects. */ + ApiEndpointSummary: { + /** @description The HTTP method. */ + method: string; + /** @description The path template (`/api/v1/groups/{name}`). */ + path: string; + /** @description What the operation does. */ + summary: string; + uiScreen: components["schemas"]["ScreenRef"]; + /** @description Whether the owner's password is asked (the confirmation header). */ + confirm: boolean; + }; + /** @description What the new-key form posts (and the body of `POST /api/ui/account/apikeys`). */ + ApiKeyForm: { + /** @description The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it. */ + password?: string | null; + /** @description What the key is for. */ + description?: string | null; + /** @description The scopes of the new key. */ + scopes?: string[]; + /** @description The package IDs the key applies to. */ + packageGlobPattern?: string; + /** + * Format: int32 + * @description Days until the key expires; none = never. + */ + expiresInDays?: number | null; + /** @description The keys of the repositories the new key is limited to; none (the default) means every repository. */ + repositoryKeys?: number[]; + }; + /** + * @description The API keys screen: the new-key form's fields it repeats and the user's keys. A request binds ApiKeyForm, never this type, + * so the outputs cannot be set from outside. + */ + ApiKeysViewModel: { + /** + * @description The repositories offered in the picker: those the user can read. Empty (picker hidden) where the server holds + * the default repository only. + */ + repositories?: components["schemas"]["RepositoryInfo"][]; + /** @description The user's keys. */ + keys?: components["schemas"]["AccountApiKey"][]; + /** @description The names of the repositories each key (by key id) is limited to. */ + keyRepositories?: { + [key: string]: string[]; + }; + /** @description The key just created. Shown once: only its hash is kept. */ + createdKey?: string | null; + /** + * @description The scopes the new-key form offers: the package scopes, plus string ApiKeyScopes.Admin (the REST API under + * `/api/v1`) for an administrator. + */ + allScopes?: string[]; + /** @description The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it. */ + password?: string | null; + /** @description What the key is for. */ + description?: string | null; + /** @description The scopes of the new key. */ + scopes?: string[]; + /** @description The package IDs the key applies to. */ + packageGlobPattern?: string; + /** + * Format: int32 + * @description Days until the key expires; none = never. + */ + expiresInDays?: number | null; + /** @description The keys of the repositories the new key is limited to; none (the default) means every repository. */ + repositoryKeys?: number[]; + }; + /** @description What the access audit screen (`/admin/audit`) shows: the filter and the matching entries. */ + AuditViewModel: { + /** @description The user name that made the change. */ + actorFilter?: string | null; + /** @description Part of what the change was done to (a group, target, project or repository name). */ + subject?: string | null; + /** @description First day, `yyyy-MM-dd`. */ + from?: string | null; + /** @description Last day, `yyyy-MM-dd`. */ + to?: string | null; + /** @description The matching entries. */ + entries?: components["schemas"]["AccessAuditEntry"][]; + /** @description Why the filter was not applied, if a date could not be read. */ + filterError?: string | null; + }; + /** @description What the change-email form posts. */ + ChangeEmailForm: { + /** @description The new address. */ + newEmail?: string | null; + /** @description The password, asked again (an account without one needs a fresh provider sign-in instead). */ + password?: string | null; + }; + /** @description What the change-password form posts (the body of `POST /api/ui/account/settings/change-password`). */ + ChangePasswordForm: { + /** @description The current password (an account without one sets its first after signing in again with its provider). */ + currentPassword?: string | null; + /** @description The new password. */ + newPassword?: string | null; + /** @description The new password again. */ + confirmPassword?: string | null; + }; + /** @description What the cluster page shows. */ + ClusterStatus: { + /** @description Whether this node is in a cluster. */ + enabled: boolean; + /** @description This node's name. */ + thisNode: string; + /** @description The store, without credentials. */ + backend: string | null; + /** @description Whether the store answered. */ + backendReachable: boolean; + /** @description The nodes with a recent heartbeat, this one included. */ + nodes: components["schemas"]["NodeInfo"][]; + /** @description The job leases held now. */ + leases: components["schemas"]["LeaseInfo"][]; + /** @description Why the cluster is read-only, or null. */ + gateReason: string | null; + readiness: components["schemas"]["ReadinessReport"]; + }; + /** @description What the cluster screen (`/admin/cluster`) shows: nodes, leases, shared state and health. */ + ClusterViewModel: { + status?: components["schemas"]["ClusterStatus"]; + }; + /** @description The result of following the link of a confirmation email. */ + ConfirmEmailViewModel: { + /** @description Whether the link was valid. */ + succeeded?: boolean; + /** @description Whether the link changed the address of an existing account. */ + emailChanged?: boolean; + /** @description Whether the account still waits for an administrator (`Accounts:RequireApproval`) after the confirmation. */ + pendingApproval?: boolean; + }; + /** + * @description The fields of the contact-owners form as the screen receives them (a page's form post or the JSON body of the twin). It carries no + * validation attributes: the use case validates by itself (ContactOwnersViewModel holds the rules), so a page's model + * binding does not report the same error a second time. + */ + ContactOwnersForm: { + /** @description The message to send to the owners. */ + message?: string | null; + /** @description Whether the sender also gets a copy. */ + copyToSelf?: boolean; + }; + /** + * @description The contact-owners screen (`/packages/{id}/contact-owners`): the two form fields (string? ContactOwnersViewModel.Message, + * bool ContactOwnersViewModel.CopyToSelf, bound on POST) and what the screen shows; filled by the screen's workflow. + */ + ContactOwnersViewModel: { + /** @description The message to send to the owners. */ + message: string | null; + /** @description Whether the sender also gets a copy. */ + copyToSelf?: boolean; + /** @description The package ID as stored, which is the only text that reaches the subject. */ + packageId?: string | null; + /** @description Whether the message was sent. */ + sent?: boolean; + /** @description Why the message was not sent, or null. */ + error?: string | null; + /** @description Replies come to the sender's address, so there must be one, and it must be confirmed: an unconfirmed address could be anyone's. */ + senderHasEmail?: boolean; + }; + /** @description What the "create an organization" form posts. */ + CreateOrganizationForm: { + /** @description The organization's name. */ + name?: string | null; + }; + /** + * @description The stage a database copy is in. + * @enum {string} + */ + DatabaseCopyPhase: "Idle" | "Queued" | "Checking" | "Migrating" | "Copying" | "Verifying" | "SavingSettings" | "RollingBack" | "Succeeded" | "Failed"; + /** @description A snapshot of the copy's progress, as shown by the Settings page. Holds no connection string. */ + DatabaseCopyStatus: { + phase: components["schemas"]["DatabaseCopyPhase"]; + /** @description The table being copied, or null. */ + table: string | null; + /** + * Format: int64 + * @description Rows of Table copied so far. + */ + tableRowsCopied: number; + /** + * Format: int64 + * @description Rows of Table in the source. + */ + tableRowsTotal: number; + /** + * Format: int32 + * @description Tables completed. + */ + tablesDone: number; + /** + * Format: int32 + * @description Tables to copy. + */ + tablesTotal: number; + /** + * Format: int64 + * @description Rows copied over all tables. + */ + rowsCopied: number; + /** + * Format: int64 + * @description Rows to copy over all tables. + */ + rowsTotal: number; + /** @description Why the copy was refused or failed. */ + errors: string[]; + /** @description A one-line summary of the current state. */ + message: string | null; + /** @description A copy is queued or running. */ + isActive?: boolean; + /** @description The copy ended, either way. */ + isFinished?: boolean; + /** @description The copy succeeded: the settings are saved and the process must restart to use them. */ + restartRequired?: boolean; + }; + /** + * @description The progress of the database copy as the Settings page polls it (`?handler=CopyStatus`): the properties are those the page's script reads + * (`phase` as the phase name, `active`, `finished`, `succeeded`, `restartRequired` ...). Holds no connection string. + */ + DatabaseCopyStatusView: { + /** @description The stage, by name. */ + phase: string; + /** @description A copy is queued or running. */ + active: boolean; + /** @description The copy ended, either way. */ + finished: boolean; + /** @description The copy succeeded. */ + succeeded: boolean; + /** @description The settings are saved and the process must restart to use them. */ + restartRequired: boolean; + /** @description The table being copied, or null. */ + table: string | null; + /** + * Format: int64 + * @description Rows of the table copied so far. + */ + tableRowsCopied: number; + /** + * Format: int64 + * @description Rows of the table in the source. + */ + tableRowsTotal: number; + /** + * Format: int32 + * @description Tables completed. + */ + tablesDone: number; + /** + * Format: int32 + * @description Tables to copy. + */ + tablesTotal: number; + /** + * Format: int64 + * @description Rows copied over all tables. + */ + rowsCopied: number; + /** + * Format: int64 + * @description Rows to copy over all tables. + */ + rowsTotal: number; + /** @description A one-line summary of the current state. */ + message: string | null; + /** @description Why the copy was refused or failed. */ + errors: string[]; + }; + /** @description What the delete-user screen (`/admin/users/{name}/delete`) shows: what the deletion would remove or change. */ + DeleteUserViewModel: { + /** @description The user to delete (route). */ + name?: string | null; + /** @description "keep" (default) or "delete": what to do with the IDs only this user owns. */ + soleOwned?: string; + preview?: (null) | components["schemas"]["AdminDeletionPreview"]; + /** @description Whether the user is the server's only administrator. */ + lastAdministrator?: boolean; + /** @description Read-only mode: the account may go, but package files are not deleted. */ + isReadOnlyMode?: boolean; + /** @description Why the deletion was refused. */ + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What stops a user from deleting their account. */ + DeletionBlockers: { + /** + * @description Package IDs the user is the only direct owner of, in any repository (ownership is per repository, so the same + * ID in two repositories counts once each). Same rule as + * Task<OwnerChangeResult> PackageOwnershipService.RemoveOwnerAsync(string? packageId, string ownerName, CancellationToken cancellationToken): an owned ID keeps an owner. + */ + lastOwnerPackageIds: string[]; + /** + * @description Organizations the user is the last administrator of while others still belong to it, or + * that own packages and so cannot be left without anyone to run them. Same rule as + * Task<bool> PackageOwnershipService.RemoveMemberAsync(string organizationName, string userId, CancellationToken cancellationToken). + */ + organizations: string[]; + /** + * @description The user is the server's only administrator, so deleting them would leave nobody able to + * change the settings. + * @default false + */ + lastAdministrator: boolean; + /** @description Per-repository detail of IReadOnlyList<string?> DeletionBlockers.LastOwnerPackageIds; never null. */ + lastOwnerPackages?: components["schemas"]["SoleOwnedPackage"][] | null; + /** @description Whether anything blocks the deletion. */ + any?: boolean; + }; + DependencyGroupModel: { + name?: string | null; + dependencies?: components["schemas"]["DependencyModel"][] | null; + }; + DependencyModel: { + packageId?: string | null; + versionSpec?: string | null; + }; + /** @description What the Docker front page (`/docker-images`) shows: this page of images and the commands for the client. */ + DockerImagesViewModel: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The page, from 1. + */ + pageIndex?: number; + result?: components["schemas"]["OciImagePage"]; + /** @description The registry host as a Docker client writes it (`host:port`). */ + host?: string; + /** @description Whether the registry is reached over plain http (the Docker daemon then needs it as an insecure registry). */ + isHttp?: boolean; + /** @description The repository's name, the first path segment of every image reference. */ + repositoryName?: string; + /** @description Whether the repository caches an upstream registry (it takes no pushes). */ + isRemote?: boolean; + /** @description Whether the repository merges other repositories (a push goes to its deploy repository). */ + isVirtual?: boolean; + /** @description Whether another page follows. */ + hasNext?: boolean; + commandTabs?: components["schemas"]["InstallSnippet"][]; + }; + /** @description What the page of one Docker image (`/docker-images/{image}`, `?digest=` for a manifest) shows. */ + DockerImageViewModel: { + /** @description The image name from the address (it may contain slashes). */ + image?: string | null; + /** @description The manifest to show in full (`?digest=`), or null for the overview. */ + digest?: string | null; + /** @description Narrows the referrers to one artifact type (`?artifactType=`); empty keeps them all. */ + artifactType?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with: 200, or 404 when the image or manifest does not exist (the page then explains). + */ + statusCode?: number; + info?: (null) | components["schemas"]["OciImageInfo"]; + selected?: (null) | components["schemas"]["OciManifestDetail"]; + /** @description The manifests whose `subject` is the chosen manifest (signatures, SBOMs). Empty without a selection. */ + referrers?: components["schemas"]["OciDescriptor"][]; + /** @description The registry host as a Docker client writes it. */ + host?: string; + /** @description The repository's name. */ + repositoryName?: string; + /** @description Whether the repository caches an upstream registry (it takes no pushes). */ + isRemote?: boolean; + /** @description Whether the signed-in user holds Delete on the image, so the manage page is offered. */ + canManage?: boolean; + pullTabs?: components["schemas"]["InstallSnippet"][]; + /** @description The address of the registry API for the image (what a script calls). */ + registryUrl?: string; + }; + /** @description The form of the Docker management handlers; every one asks for the caller's password. */ + DockerManageForm: { + /** @description The tag to delete (`DeleteTag`). */ + tag?: string | null; + /** @description The manifest digest to delete (`DeleteManifest`). */ + digest?: string | null; + /** @description The caller's password. */ + password?: string | null; + }; + /** @description What the Docker image management screen (`/docker-manage/{**image}`) shows; filled by the screen's workflow. */ + DockerManageViewModel: { + /** @description The image name from the address (it may contain slashes). */ + image?: string | null; + info?: (null) | components["schemas"]["OciImageInfo"]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether string? DockerManageViewModel.Message reports a refusal. */ + failed?: boolean; + /** @description Whether the user has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + }; + /** @description The policy in force for a repository: its own, else its project's, else none. */ + EffectiveScanPolicy: { + values: components["schemas"]["ScanPolicyValues"]; + from: (null) | components["schemas"]["ScanPolicyScope"]; + /** @description The repository or project name it is stored for, or null. */ + name: string | null; + }; + /** @description The model of a screen that shows nothing but itself (the sign-out button), or of an action that only continues elsewhere. */ + EmptyScreen: Record; + /** @description A configured external provider as the account settings list it for one user. */ + ExternalLoginStatus: { + /** @description The provider id. */ + id: string; + /** @description The provider's name. */ + displayName: string; + /** @description Whether the account has a linked login at this provider. */ + linked: boolean; + }; + /** @description An external sign-in provider as a screen offers it (one button per provider). */ + ExternalProviderInfo: { + /** @description The provider id: the value a form or `/api/ui/session/external/{provider}` names it by. */ + id: string; + /** @description The name on the button. */ + displayName: string; + }; + FeedStatistics: { + /** Format: int32 */ + packageIds?: number; + /** Format: int32 */ + packageVersions?: number; + /** Format: int64 */ + downloads?: number; + /** @description The most downloaded package IDs, all versions together. */ + topPackages?: components["schemas"]["PackageDownloads"][] | null; + /** @description The most recently published versions. */ + recentVersions?: components["schemas"]["PackageDownloads"][] | null; + }; + /** @description What the "forgot password" form posts. */ + ForgotPasswordForm: { + /** @description The user name or email address. */ + identifier: string | null; + }; + /** @description The "forgot password" screen. A request binds ForgotPasswordForm, never this type. */ + ForgotPasswordViewModel: { + /** @description Whether the request was answered (always the same answer, see the use case). */ + sent?: boolean; + /** @description The user name or email address. */ + identifier: string | null; + }; + /** @description An input of the create form a format contributes. */ + FormatCreateField: { + /** @description The key in the dictionary string? IFormatModule.CreateSettings(IReadOnlyDictionary<string, string?> fields) receives. */ + name: string; + /** @description The visible label. */ + label: string; + /** @description One line of explanation, or null. */ + help?: string | null; + /** + * @description Whether an empty value is refused by the form. + * @default false + */ + required: boolean; + /** @description For a choice: the allowed values; null for free text. */ + options?: string[] | null; + }; + /** @description A link a format contributes to the administration of a repository: to one of its screens or to a path under its base. */ + FormatLink: { + /** @description A stable identifier (`browse`, `upload`); becomes the CSS class `repository-{id}`. */ + id?: string | null; + /** @description The visible text. */ + label?: string | null; + /** @description The MVC controller (without the suffix) of the screen it opens; null for a path link. */ + controller?: string | null; + /** @description The action of that controller that shows the screen; null for a path link. */ + action?: string | null; + /** @description A path under the repository base; null for a screen link. */ + path?: string | null; + /** @description Shown only for repositories that take uploads (not a remote one, nor a virtual one without a deploy repository). */ + needsUploads?: boolean; + }; + /** @description One format with what it offers, as the formats screen lists it. */ + FormatRow: { + module: components["schemas"]["IFormatModule"]; + /** + * Format: int32 + * @description How many repositories use it. + */ + repositories: number; + /** @description The capabilities its services implement. */ + capabilities: string[]; + }; + /** @description What the formats screen (`/admin/formats`) lists: the package formats this server can host. */ + FormatsViewModel: { + /** @description The formats. */ + rows?: components["schemas"]["FormatRow"][]; + }; + /** @description The frameworks of one package, as the package page's Frameworks tab shows them. */ + FrameworkGroup: { + /** @description The family (.NET, .NET Core, .NET Standard, .NET Framework, Other). */ + name?: string | null; + /** @description Frameworks the package ships assets for. */ + declared?: string[] | null; + /** @description Frameworks the package works with without declaring them. */ + computed?: string[] | null; + }; + /** @description Giving a principal the ticked actions through a permission target, replacing an earlier grant to it. */ + GrantForm: { + principalType: (null) | components["schemas"]["PrincipalType"]; + /** @description The principal's name. */ + principalName: string | null; + /** @description The ticked AccessAction names (`Read`, `Annotate`, `Deploy`, `Delete`, `Manage`); none removes the grant. */ + actions: string[] | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** @description A grant, with the target and principal in words. */ + GrantInfo: { + target: string; + principalType: components["schemas"]["PrincipalType"]; + principalId: string; + principal: string; + actions: components["schemas"]["AccessAction"]; + }; + /** @description A new group. */ + GroupCreation: { + /** @description The group's name. */ + name: string | null; + /** @description What the group is for, or null. */ + description: string | null; + }; + /** @description A group with its members and the grants naming it. */ + GroupDetails: { + group: components["schemas"]["GroupSummary"]; + members: components["schemas"]["GroupMemberInfo"][]; + grants: components["schemas"]["GrantInfo"][]; + }; + /** @description What the group screen (`/admin/groups/{name}`) shows: the group, its members and the member search. */ + GroupDetailViewModel: { + /** @description The group name (route). */ + name?: string | null; + /** @description User-name search for the member picker (contains). */ + q?: string | null; + group?: (null) | components["schemas"]["GroupDetails"]; + /** @description The users found by string? GroupDetailViewModel.Q, not yet members. */ + found?: components["schemas"]["GroupMemberInfo"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Adding a user to a group or removing them. */ + GroupMemberChange: { + /** @description The user's id (string GroupMemberInfo.UserId). */ + userId: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** @description A member of a group. */ + GroupMemberInfo: { + userId: string; + userName: string; + }; + /** @description Renaming a group. */ + GroupRename: { + /** @description The new name. */ + newName: string | null; + }; + /** @description A group as the admin pages list it. */ + GroupSummary: { + /** Format: int32 */ + key: number; + name: string; + description: string | null; + isBuiltIn: boolean; + /** Format: int32 */ + memberCount: number; + }; + /** @description What the groups screen (`/admin/groups`) shows: the groups and the new-group form. */ + GroupsViewModel: { + /** @description The new group name. */ + name?: string | null; + /** @description The new group description. */ + description?: string | null; + /** @description The groups. */ + groups?: components["schemas"]["GroupSummary"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description One probe of the readiness check. */ + HealthProbe: { + /** @description `database`, `storage` or `cluster`. */ + name: string; + /** @description Whether it answered. */ + healthy: boolean; + /** @description A short, credential-free note (the exception type when it failed). */ + detail: string | null; + /** + * @description The probe is reported but a failure does not make the node unready (the shared store: a node keeps serving without it). + * @default false + */ + informational: boolean; + }; + HtmlString: { + value: string | null; + }; + /** + * @description A long-running maintenance operation an administrator can start from the web UI for one repository + * (what the `catalog rebuild` and `import downloads` commands do). Registered as a singleton. + */ + IAdminOperation: { + /** @description The stable id used in forms and status (`catalog-rebuild`). */ + name?: string | null; + title?: string | null; + description?: string | null; + /** + * @description Whether the operation deletes data, so the Operations page asks the administrator's password again before it starts it (as the + * other destructive pages do). Default: no. + */ + requiresConfirmation?: boolean; + }; + /** + * @description One package format (NuGet, npm, later Maven and OCI) as the common code sees it: what its repositories are called and where + * they live, which kinds a repository of it can have, the UI it contributes, and how its artifacts are counted and purged. + * A module only describes the format; what it does per request is a set of services registered beside it + * (IFormatIndexer, IFormatSearchProvider, IFormatRetentionHooks, + * IFormatScanner, looked up with T? FormatServices.GetFormatService<T>(IServiceProvider provider, RepositoryFormat format)) and the format's own controllers, + * whose routes go through `BaGetEndpointBuilder.MapRoute` with the module's RepositoryFormat IFormatModule.Format. + */ + IFormatModule: { + format?: components["schemas"]["RepositoryFormat"]; + /** @description The name shown to people: `NuGet`, `npm`. */ + displayName?: string | null; + /** + * @description The path segment (or segments, without slashes at the ends) every route of the format starts with, after the repository + * base: `npm`. Empty for NuGet, whose routes were there first. + */ + routePrefix?: string | null; + /** + * @description The address a client is configured with, relative to the repository base (`r/{repo}/`, or the root for the default + * repository): `v3/index.json` for NuGet, `npm/` for npm. + */ + feedPath?: string | null; + /** + * @description The kinds of repository that can be created through IRepositoryService without a dedicated administration + * service (a virtual repository is created with its members by IVirtualRepositoryAdministration and is not + * listed here). Kinds not listed are refused for this format. + */ + creatableKinds?: components["schemas"]["RepositoryKind"][] | null; + /** + * @description Whether virtual repositories of this format exist (Task<RepositoryInfo> IVirtualRepositoryAdministration.CreateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null, bool anonymousRead = true, RepositoryFormat format = RepositoryFormat.NuGet)): the format's + * reads then merge the members, and a write goes to the deploy repository. False for a format that has not implemented the + * merge. + */ + supportsVirtual?: boolean; + /** + * @description Whether the format stores blobs too large to buffer (Docker layers) and so needs a store that is an + * IStreamingStorageService. A repository of such a format is refused at creation when the configured store + * cannot stream (IStreamingStorageService StreamingStorage.Require(IStorageService? storage, string purpose)). + */ + requiresStreamingStorage?: boolean; + /** + * @description The top-level storage folders the format writes below a repository's string RepositoryStorage.Prefix(RepositoryInfo repository) + * (`packages`, `symbols`…). Two modules may not claim the same folder, nor string RepositoryStorage.ReposFolder: + * FormatRegistry refuses the registration, since a collision would let one format read another's files. + */ + storageFolders?: string[] | null; + /** + * @description What the administrator fills in to create a repository of this format, on top of the name. Empty when a name is all that + * is needed. + */ + createFields?: components["schemas"]["FormatCreateField"][] | null; + }; + /** Format: binary */ + IFormFile: string; + /** @description What the front page and the package list show: the search that was asked for and its results. */ + IndexScreen: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The 1-based page of results. + */ + pageIndex?: number; + /** @description The package type filter, `any` for none. */ + packageType?: string; + /** @description The target framework filter, `any` for none. */ + framework?: string; + /** @description Whether prerelease versions are included. */ + prerelease?: boolean; + sortBy?: components["schemas"]["SearchSort"]; + /** @description The orders the search provider can apply on the server; with only the default there is nothing to choose. */ + supportedSorts?: components["schemas"]["SearchSort"][]; + /** @description True for the front page: the repository's root with no search. Everything else lists packages. */ + isHome?: boolean; + totals?: (null) | components["schemas"]["FeedStatistics"]; + /** @description The page of results (empty on the front page). */ + packages?: components["schemas"]["SearchResult"][]; + /** @description When each listed package ID was last published, by ID; empty when unsupported. */ + lastUpdated?: { + [key: string]: string; + }; + }; + /** @description One tab of the "install / configure / push" commands of a package, artifact or image page (one tool per tab). */ + InstallSnippet: { + /** @description The tool the tab is for. */ + name?: string | null; + /** @description A shell prompt shown before the first line; not part of the copied text. */ + prefix?: string | null; + /** @description The lines to copy. */ + lines?: string[] | null; + }; + JsonObject: Record; + /** @description A lease as stored: the holder's node, a token that tells two holders of one node apart, and when it was taken. */ + LeaseInfo: { + /** @description The job's name. */ + job: string; + /** @description The holder. */ + node: string; + /** + * Format: date-time + * @description When it was acquired (UTC). + */ + since: string; + }; + /** @description What a legal page (Terms of Use, Privacy Policy) shows: its heading and the operator's Markdown rendered to safe HTML. */ + LegalScreen: { + /** @description The heading and page title. */ + title: string; + /** @description The operator's Markdown file as HTML (raw HTML in the source is escaped, script links neutralised: HtmlString? ReadmeMarkdown.ToSafeHtml(string? markdown)). */ + contentHtml: string; + }; + /** @description What the sign-in form posts (and the body of `POST /api/ui/account/login`). */ + LoginForm: { + /** @description The user name. */ + userName: string | null; + /** @description The password. Never echoed: a screen's model leaves it empty. */ + password: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** + * @description The sign-in screen: the form fields it repeats and what it shows. A request never binds this type (the form is LoginForm), so + * the outputs cannot be set from outside; string? LoginForm.Password is always empty. + */ + LoginViewModel: { + /** @description Whether the registration link is shown. */ + allowRegistration?: boolean; + /** @description Whether sign-in with an external provider is offered (any provider in IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders). */ + hasExternalProvider?: boolean; + /** @description The first provider's display name (kept for clients that offer one button); see IReadOnlyList<ExternalProviderInfo> LoginViewModel.ExternalProviders. */ + externalProviderName?: string | null; + /** @description The configured external providers, one sign-in button each. */ + externalProviders?: components["schemas"]["ExternalProviderInfo"][]; + /** @description Whether mail is configured (the forgot-password link is shown). */ + emailIsConfigured?: boolean; + /** @description The refusal to show. */ + error?: string | null; + /** @description The notice to show. */ + notice?: string | null; + /** @description The user name. */ + userName: string | null; + /** @description The password. Never echoed: a screen's model leaves it empty. */ + password: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description Setting or removing the lowest level logged for one source. */ + LogLevelForm: { + /** @description The source (a namespace prefix). */ + source: string | null; + /** @description The level (ignored when removing). */ + level: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** + * @description One `Serilog:MinimumLevel:Override:{Source}` entry: the lowest level logged for a source (a namespace or type + * name prefix such as `Microsoft.AspNetCore`). + */ + LogLevelOverride: { + /** @description The namespace or type name prefix. */ + source: string; + /** @description Verbose, Debug, Information, Warning, Error or Fatal. */ + level: string; + /** @description True when the Settings overrides file holds it, so it can be removed from here; false when only a configuration file or the environment sets it. */ + inOverridesFile: boolean; + }; + /** @description An artifact with its versions, newest first. */ + MavenArtifactInfo: { + /** @description The group id. */ + groupId: string; + /** @description The artifact id. */ + artifactId: string; + /** + * Format: date-time + * @description The first deploy (UTC). + */ + created: string; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** @description Its versions, highest first. */ + versions: components["schemas"]["MavenVersionSummary"][]; + latest?: components["schemas"]["MavenVersionSummary"]; + /** @description `group:artifact`. */ + name?: string | null; + }; + /** @description What the Maven front page (`/maven-artifacts`) shows: this page of search results and the client configuration. */ + MavenArtifactsViewModel: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The page, from 1. + */ + pageIndex?: number; + result?: components["schemas"]["MavenSearchPage"]; + settings?: components["schemas"]["MavenRepositorySettings"]; + /** @description The address Maven is configured with for this repository. */ + repositoryUrl?: string; + kind?: components["schemas"]["RepositoryKind"]; + /** @description The repository's name, which is the `id` in `settings.xml` and the POM. */ + repositoryName?: string; + /** @description Whether another page follows. */ + hasNext?: boolean; + configurationTabs?: components["schemas"]["InstallSnippet"][]; + }; + /** @description What the page of one Maven artifact (`/maven-artifacts/{group}/{artifact}/{version?}`) shows. */ + MavenArtifactViewModel: { + /** @description The group id from the address. */ + group?: string | null; + /** @description The artifact id from the address. */ + artifact?: string | null; + /** @description The version from the address; the latest when absent. */ + version?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with: 200, or 404 when the artifact or version does not exist (the page then explains). + */ + statusCode?: number; + info?: (null) | components["schemas"]["MavenArtifactInfo"]; + selected?: (null) | components["schemas"]["MavenVersionDetail"]; + /** @description The address Maven is configured with for this repository. */ + repositoryUrl?: string; + /** @description The repository's name (the `id` in `settings.xml`). */ + repositoryName?: string; + installTabs?: components["schemas"]["InstallSnippet"][]; + /** @description The owners, when accounts are on; empty otherwise. */ + owners?: string[]; + /** @description Whether the signed-in user can open the manage page (an owner or an administrator). */ + canManage?: boolean; + }; + /** @description What the upload page hands to Task<MavenResult> IMavenRepository.DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken). */ + MavenDeployment: { + /** @description The group id. */ + groupId?: string | null; + /** @description The artifact id. */ + artifactId?: string | null; + /** @description The version. */ + version?: string | null; + /** @description The packaging, the extension of the main file when it has no other (default `jar`). */ + packaging?: string | null; + /** @description The classifier of the main file, or null. */ + classifier?: string | null; + /** @description The extension of the main file (default: the packaging). */ + extension?: string | null; + file?: (null) | components["schemas"]["Stream"]; + pom?: (null) | components["schemas"]["Stream"]; + }; + /** @description A file of a version as the pages list it. */ + MavenFileDetail: { + /** @description The file name. */ + fileName: string; + /** @description The classifier, or null. */ + classifier: string | null; + /** @description The extension. */ + extension: string; + /** + * Format: int64 + * @description Bytes. + */ + size: number; + /** @description SHA-1 hex. */ + sha1: string; + /** @description MD5 hex. */ + md5: string; + /** @description SHA-256 hex. */ + sha256: string; + /** @description SHA-512 hex. */ + sha512: string; + /** + * Format: date-time + * @description When stored (UTC). + */ + created: string; + /** @description The snapshot build timestamp, or null. */ + snapshotTimestamp: string | null; + /** + * Format: int32 + * @description The snapshot build number, or 0. + */ + snapshotBuild: number; + }; + /** @description The form of the Maven management handlers: the chosen version and what the handler needs. */ + MavenManageForm: { + /** @description The user or organization (`AddOwner`, `RemoveOwner`). */ + ownerName?: string | null; + /** @description The version whose files are listed, and the one a handler acts on (`DeleteFile`, `DeleteVersion`, `Cleanup`). */ + version?: string | null; + /** @description The file to delete (`DeleteFile`). */ + fileName?: string | null; + /** @description How many snapshot builds to keep (`Cleanup`). */ + keep?: string | null; + /** @description The caller's password, for the deleting handlers. */ + password?: string | null; + }; + /** @description What the Maven artifact management screen (`/maven-manage/{group}/{artifact}`) shows; filled by the screen's workflow. */ + MavenManageViewModel: { + /** @description The group id from the address. */ + group?: string | null; + /** @description The artifact id from the address. */ + artifact?: string | null; + /** @description The version whose files are listed (`?version=`), or null. */ + version?: string | null; + info?: (null) | components["schemas"]["MavenArtifactInfo"]; + selected?: (null) | components["schemas"]["MavenVersionDetail"]; + /** @description The artifact's owners. */ + owners?: components["schemas"]["PackageOwner"][]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether string? MavenManageViewModel.Message reports a refusal. */ + failed?: boolean; + /** @description Whether the signed-in user is an administrator. */ + isAdministrator?: boolean; + /** @description Whether the user manages the artifact only as an administrator (they are not an owner). */ + actingAsAdministrator?: boolean; + /** @description Whether the user has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description `group:artifact`. */ + name?: string | null; + }; + /** + * @description Which versions a local Maven repository accepts. + * @enum {string} + */ + MavenPolicy: "Releases" | "Snapshots" | "Both"; + /** @description A dependency a POM declares (versions and scopes as written; properties are not resolved). */ + MavenPomDependency: { + /** @description The group id. */ + groupId: string; + /** @description The artifact id. */ + artifactId: string; + /** @description The version, or null (managed elsewhere). */ + version: string | null; + /** @description The scope, or null (compile). */ + scope: string | null; + /** @description Whether the dependency is optional. */ + optional: boolean; + }; + /** @description What the search and the pages read from a POM. */ + MavenPomInfo: { + /** @description The group id (the parent's when the POM has none). */ + groupId: string | null; + /** @description The artifact id. */ + artifactId: string | null; + /** @description The version (the parent's when the POM has none). */ + version: string | null; + /** @description The packaging, `jar` by default. */ + packaging: string; + /** @description The `name`. */ + name: string | null; + /** @description The `description`. */ + description: string | null; + /** @description The project `url`. */ + url: string | null; + /** @description The parent as `group:artifact:version`, or null. */ + parent: string | null; + /** @description The declared dependencies, in order. */ + dependencies: components["schemas"]["MavenPomDependency"][]; + }; + /** @description The settings of a local Maven repository, kept as JSON in string? Repository.Settings (no schema of their own). */ + MavenRepositorySettings: { + policy?: components["schemas"]["MavenPolicy"]; + /** + * @description Whether a release file that exists may be deployed again (replaced). The caller then also needs the Delete action, as + * Artifactory's Delete/Overwrite does. Default false: a release is immutable. Snapshots are never refused for this. + */ + allowRedeploy?: boolean; + /** + * Format: int32 + * @description How many timestamped builds of a snapshot version are kept: when a deploy brings a newer build, older ones beyond this + * number are deleted. Zero keeps all (clean up on the artifact's page). + */ + maxSnapshotBuilds?: number; + }; + /** @description A search hit. */ + MavenSearchHit: { + /** @description The group id. */ + groupId: string; + /** @description The artifact id. */ + artifactId: string; + /** @description The newest version (a release if there is one), or null. */ + version: string | null; + /** @description The POM's name of it, or null. */ + name: string | null; + /** @description The POM's description of it, or null. */ + description: string | null; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** @description `group:artifact`. */ + coordinateName?: string | null; + }; + /** @description A page of hits. */ + MavenSearchPage: { + /** + * Format: int32 + * @description All matches. + */ + total: number; + /** @description This page. */ + hits: components["schemas"]["MavenSearchHit"][]; + }; + /** @description What the Maven upload page (`/maven-upload`) shows, before and after a deployment. */ + MavenUploadViewModel: { + /** @description Whether accounts are on (the uploader then signs in). */ + accountsEnabled?: boolean; + /** @description Whether the server is read-only. */ + isReadOnlyMode?: boolean; + /** @description Whether the visitor is signed in. */ + signedIn?: boolean; + /** @description Without accounts there is no user to own an upload, so the uploader proves itself with the API key. */ + needsApiKey?: boolean; + /** @description Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed. */ + nothingCanAuthenticate?: boolean; + /** @description Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in. */ + canUpload?: boolean; + /** @description The address Maven is configured with for this repository. */ + repositoryUrl?: string; + /** @description The repository's name (the `id` in `settings.xml`). */ + repositoryName?: string; + settings?: components["schemas"]["MavenRepositorySettings"]; + /** @description What happened, for the page to show. */ + message?: string | null; + /** @description Whether string? MavenUploadViewModel.Message reports a failure. */ + failed?: boolean; + /** @description The artifact just deployed (`group:artifact`), so the page can link to it. */ + deployedName?: string | null; + /** @description The version just deployed. */ + deployedVersion?: string | null; + posted?: (null) | components["schemas"]["MavenDeployment"]; + /** + * Format: int32 + * @description The HTTP status the page is answered with (200, or the refusal's). + */ + statusCode?: number; + }; + /** @description One version with its files and POM. */ + MavenVersionDetail: { + summary: components["schemas"]["MavenVersionSummary"]; + /** @description Its files, by name. */ + files: components["schemas"]["MavenFileDetail"][]; + pom: (null) | components["schemas"]["MavenPomInfo"]; + /** @description The POM text (for the view), or null. */ + pomText: string | null; + }; + /** @description A version as the artifact page lists it. */ + MavenVersionSummary: { + /** @description The version. */ + version: string; + /** @description Whether it is a snapshot. */ + isSnapshot: boolean; + /** @description The POM's name, or null. */ + name: string | null; + /** @description The POM's description, or null. */ + description: string | null; + /** @description The POM's packaging, or null. */ + packaging: string | null; + /** + * Format: date-time + * @description The first file (UTC). + */ + created: string; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** + * Format: int32 + * @description Files of the version. + */ + fileCount: number; + /** + * Format: int64 + * @description Bytes of the version. + */ + size: number; + /** + * Format: int32 + * @description For a snapshot: how many timestamped builds it holds. + */ + builds: number; + }; + /** @description A node as it publishes itself. */ + NodeInfo: { + /** @description The node's name. */ + id: string; + /** + * Format: date-time + * @description When it started (UTC). + */ + started: string; + /** + * Format: date-time + * @description Its latest heartbeat (UTC). + */ + seen: string; + /** @description The BaGet version it runs. */ + version: string; + /** @description Whether its last readiness check passed. */ + ready: boolean; + /** @description What failed, when it did not. */ + problem: string | null; + /** @description Whether its read-only gate is closed. */ + gateClosed: boolean; + }; + /** @description The form of `Deprecate` and `Undeprecate`. */ + NpmManageDeprecateForm: { + /** @description The version. */ + version?: string | null; + /** @description The deprecation message (`Deprecate` only). */ + message?: string | null; + }; + /** @description The form of the npm management handlers that name an owner. */ + NpmManageOwnerForm: { + /** @description The user or organization. */ + ownerName?: string | null; + }; + /** @description The form of `SetTag`. */ + NpmManageTagForm: { + /** @description The dist-tag. */ + tag?: string | null; + /** @description The version it points at (not used by `RemoveTag`). */ + version?: string | null; + }; + /** @description The form of `Unpublish` (one version) and `UnpublishAll` (the version is ignored); the password confirms. */ + NpmManageUnpublishForm: { + /** @description The version (`Unpublish` only). */ + version?: string | null; + /** @description The caller's password. */ + password?: string | null; + }; + /** @description What the npm package management screen (`/npm-manage/{*id}`) shows; filled by the screen's workflow. */ + NpmManageViewModel: { + /** @description The package name from the address. */ + id?: string | null; + package?: (null) | components["schemas"]["NpmPackageInfo"]; + /** @description The package's owners. */ + owners?: components["schemas"]["PackageOwner"][]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether string? NpmManageViewModel.Message reports a refusal. */ + failed?: boolean; + /** @description Whether the signed-in user is an administrator. */ + isAdministrator?: boolean; + /** @description Whether the user manages the package only as an administrator (they are not an owner). */ + actingAsAdministrator?: boolean; + /** @description Whether the user has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + /** @description How long after publishing a version its owner may unpublish it with Deploy alone. */ + unpublishWindow?: string; + }; + /** @description A package with its versions and dist-tags, as stored. */ + NpmPackageInfo: { + /** @description The name (`@scope/name` for a scoped package). */ + name: string; + /** + * Format: date-time + * @description The first publish. + */ + created: string; + /** + * Format: date-time + * @description The last change. + */ + modified: string; + /** @description Tag to version. */ + distTags: { + [key: string]: string; + }; + /** @description Every version, oldest first by semantic version. */ + versions: components["schemas"]["NpmVersionInfo"][]; + latest?: components["schemas"]["NpmVersionInfo"]; + /** @description The document revision clients send back on a write (`?write=true` reads, `/-rev/{rev}` writes): changes with every change of the package. */ + revision?: string | null; + }; + /** @description What the npm front page (`/npm-packages`) shows: this page of search results and the registry address. */ + NpmPackagesViewModel: { + /** @description The search text. */ + query?: string | null; + /** + * Format: int32 + * @description The page, from 1. + */ + pageIndex?: number; + result?: components["schemas"]["NpmSearchPage"]; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + /** @description Whether another page follows. */ + hasNext?: boolean; + }; + /** @description What the page of one npm package (`/npm-packages/{name}`) shows. */ + NpmPackageViewModel: { + /** @description The package name from the address. */ + id?: string | null; + /** @description The version asked for with `?version=`; the latest when absent or unknown. */ + requestedVersion?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with: 200, or 404 when the package does not exist (the page then explains). + */ + statusCode?: number; + package?: (null) | components["schemas"]["NpmPackageInfo"]; + selected?: (null) | components["schemas"]["NpmVersionInfo"]; + readme?: (null) | components["schemas"]["HtmlString"]; + /** @description The dist-tags that point at the selected version. */ + selectedTags?: string[]; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + /** @description Where the selected version's tarball is. */ + tarballUrl?: string | null; + installTabs?: components["schemas"]["InstallSnippet"][]; + /** @description The owners, when accounts are on; empty otherwise. */ + owners?: string[]; + /** @description Whether the signed-in user can open the manage page (an owner or an administrator). */ + canManage?: boolean; + }; + /** @description One package in a search result. */ + NpmSearchHit: { + /** @description The name. */ + name: string; + /** @description The latest version. */ + version: string | null; + /** @description Its description. */ + description: string | null; + /** @description Its keywords. */ + keywords: string[]; + /** + * Format: date-time + * @description The last change. + */ + modified: string; + }; + /** @description A page of packages. */ + NpmSearchPage: { + /** + * Format: int32 + * @description All matches. + */ + total: number; + /** @description This page, ordered by name. */ + hits: components["schemas"]["NpmSearchHit"][]; + }; + /** @description What the npm upload page (`/npm-upload`) shows, before and after a publish. */ + NpmUploadViewModel: { + /** @description Whether accounts are on (the uploader then signs in). */ + accountsEnabled?: boolean; + /** @description Whether the server is read-only. */ + isReadOnlyMode?: boolean; + /** @description Whether the visitor is signed in. */ + signedIn?: boolean; + /** @description Without accounts there is no user to own an upload, so the uploader proves itself with the API key. */ + needsApiKey?: boolean; + /** @description Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed. */ + nothingCanAuthenticate?: boolean; + /** @description Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in. */ + canUpload?: boolean; + /** @description The address npm is configured with for this repository. */ + registryUrl?: string; + publishLines?: string[]; + /** @description What happened, for the page to show. */ + message?: string | null; + /** @description Whether string? NpmUploadViewModel.Message reports a failure. */ + failed?: boolean; + /** @description The package just published, so the page can link to it. */ + publishedName?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with (200, or the refusal's). + */ + statusCode?: number; + }; + /** @description One published version as stored. */ + NpmVersionInfo: { + /** @description The version string as published. */ + version: string; + /** + * Format: date-time + * @description When it was published. + */ + published: string; + /** @description The deprecation message, or null. */ + deprecated: string | null; + /** + * Format: int64 + * @description Bytes of the tarball. + */ + tarballSize: number; + /** @description The tarball's SRI string (`sha512-…`). */ + integrity: string; + /** @description The tarball's SHA-1 in hex. */ + shasum: string; + manifest: components["schemas"]["JsonObject"]; + /** @description The manifest's `description`, or null. */ + description?: string | null; + /** @description The manifest's `readme`, or null. */ + readme?: string | null; + /** @description The manifest's `license` when it is a string, or null. */ + license?: string | null; + /** @description The manifest's `keywords` that are strings. */ + keywords?: string[] | null; + }; + NuGetVersion: { + version?: string | null; + isLegacyVersion?: boolean; + /** Format: int32 */ + revision?: number; + isSemVer2?: boolean; + originalVersion?: string | null; + /** Format: int32 */ + major?: number; + /** Format: int32 */ + minor?: number; + /** Format: int32 */ + patch?: number; + releaseLabels?: string[] | null; + release?: string | null; + isPrerelease?: boolean; + hasMetadata?: boolean; + metadata?: string | null; + }; + /** @description A descriptor in a referrers index. */ + OciDescriptor: { + /** @description The referrer's media type. */ + mediaType: string; + /** @description Its digest. */ + digest: string; + /** + * Format: int64 + * @description Its size. + */ + size: number; + /** @description Its artifact type, or null. */ + artifactType: string | null; + /** @description Its annotations, or null. */ + annotations: { + [key: string]: string; + } | null; + }; + /** @description One thing a garbage collection removes. */ + OciGcItem: { + kind: components["schemas"]["OciGcItemKind"]; + /** @description A digest or a session reference. */ + subject: string; + /** + * Format: int64 + * @description Bytes it frees (0 for a session). + */ + bytes: number; + /** @description The image it belonged to, if any. */ + image: string | null; + }; + /** + * @description What a garbage collection found (or, outside a dry run, removed). + * @enum {string} + */ + OciGcItemKind: "ExpiredUpload" | "UnreferencedLayer" | "OrphanBlob" | "OrphanFile"; + /** @description The outcome of one garbage collection of a repository. */ + OciGcReport: { + /** @description Whether nothing was changed (the numbers are what a run would remove). */ + dryRun: boolean; + /** @description The repository. */ + repository: string; + /** + * Format: int32 + * @description Upload sessions discarded. + */ + expiredUploads: number; + /** + * Format: int32 + * @description Image-to-layer links dropped (a layer two images hold counts twice). + */ + unreferencedLayers: number; + /** + * Format: int32 + * @description Blobs (rows and files) removed: those no image holds after the links are dropped, orphan rows included. + */ + blobs: number; + /** + * Format: int32 + * @description Files under the blob folder with no row, removed. + */ + orphanFiles: number; + /** + * Format: int64 + * @description Bytes freed by the blobs and orphan files, as far as they are known (an orphan file's size is not). + */ + bytes: number; + /** @description The first of the things removed (the list is capped). */ + items: components["schemas"]["OciGcItem"][]; + /** @description Whether there are more than Items holds. */ + itemsTruncated: boolean; + /** @description Something the run could not do (the store cannot list files), or null. */ + note: string | null; + /** @description One line for the Operations page and the audit log. */ + summary?: string | null; + }; + /** @description An image with its tags and manifests (the image page). */ + OciImageInfo: { + /** @description The image name. */ + name: string; + /** + * Format: date-time + * @description When the first upload arrived (UTC). + */ + created: string; + /** + * Format: date-time + * @description The last change (UTC). + */ + modified: string; + /** @description The tags, by name. */ + tags: components["schemas"]["OciTagInfo"][]; + /** @description The manifests, newest first. */ + manifests: components["schemas"]["OciManifestSummary"][]; + /** + * Format: int64 + * @description Bytes of the distinct blobs the image holds. + */ + size: number; + /** + * Format: int32 + * @description Blobs held by the image that no manifest uses. + */ + unreferencedBlobs: number; + }; + /** @description A page of OciImageSummary. */ + OciImagePage: { + /** + * Format: int32 + * @description All images that matched and may be read. + */ + total: number; + /** @description The page. */ + images: components["schemas"]["OciImageSummary"][]; + }; + /** @description An image as the browse page lists it. */ + OciImageSummary: { + /** @description The image name. */ + name: string; + /** + * Format: int32 + * @description Number of tags. + */ + tags: number; + /** + * Format: int32 + * @description Number of manifests (including indexes). + */ + manifests: number; + /** + * Format: int64 + * @description Bytes of the distinct blobs the image holds. + */ + size: number; + /** + * Format: date-time + * @description The last manifest or tag change (UTC). + */ + modified: string; + }; + /** @description A layer, config or other blob a manifest lists. */ + OciLayerInfo: { + /** @description The digest. */ + digest: string; + /** + * Format: int64 + * @description The size announced by the manifest. + */ + size: number; + /** @description The media type. */ + mediaType: string; + }; + /** @description One manifest in full (the manifest page). */ + OciManifestDetail: { + summary: components["schemas"]["OciManifestSummary"]; + /** @description The manifest document, pretty-printed for display (the stored bytes are unchanged). */ + json: string; + config: (null) | components["schemas"]["OciLayerInfo"]; + /** @description The layers in order (empty for an index). */ + layers: components["schemas"]["OciLayerInfo"][]; + /** @description The entries of an index (empty for a single-image manifest). */ + platforms: components["schemas"]["OciPlatformInfo"][]; + /** @description The manifest's annotations. */ + annotations: { + [key: string]: string; + }; + }; + /** @description A manifest as the image page lists it. */ + OciManifestSummary: { + /** @description Its digest. */ + digest: string; + /** @description Its media type. */ + mediaType: string; + /** + * Format: int64 + * @description Bytes of the manifest document. + */ + size: number; + /** @description Whether it is an index of platform manifests. */ + isIndex: boolean; + /** + * Format: date-time + * @description When it was first pushed to the image (UTC). + */ + created: string; + /** @description The tags that point at it. */ + tags: string[]; + /** @description Its artifact type, or null. */ + artifactType: string | null; + /** @description The digest it refers to, or null. */ + subjectDigest: string | null; + /** @description For a single-image manifest, its platform when the config says so (`linux/amd64`); otherwise null. */ + platform: string | null; + /** + * Format: int32 + * @description Number of layers (0 for an index). + */ + layerCount: number; + /** + * Format: int64 + * @description Bytes of the config and layers (the children are not summed for an index). + */ + contentSize: number; + }; + /** @description A platform entry of an index. */ + OciPlatformInfo: { + /** @description The child manifest. */ + digest: string; + /** @description The child's media type. */ + mediaType: string; + /** + * Format: int64 + * @description The child's size. + */ + size: number; + /** @description The operating system, or null. */ + os: string | null; + /** @description The architecture, or null. */ + architecture: string | null; + /** @description The variant (`v7`), or null. */ + variant: string | null; + /** @description Whether the child manifest is in this image. */ + present: boolean; + /** @description The platform as one string: `linux/arm64/v8` (or `unknown` for an entry with none). */ + platform?: string | null; + }; + /** @description A tag of an image. */ + OciTagInfo: { + /** @description The tag. */ + name: string; + /** @description The manifest it points at. */ + digest: string; + /** + * Format: date-time + * @description When it was created or moved (UTC). + */ + updated: string; + }; + /** @description Starting a maintenance operation. */ + OperationForm: { + /** @description The operation's name (`catalog-rebuild`). */ + operation: string | null; + /** @description The repository it runs on. */ + repository: string | null; + /** @description The administrator's password (asked for operations that delete data). */ + password: string | null; + }; + /** @description One row of the operations screen: an operation on a repository. */ + OperationRow: { + operation: components["schemas"]["IAdminOperation"]; + repository: components["schemas"]["RepositoryInfo"]; + status: (null) | components["schemas"]["AdminJobStatus"]; + }; + /** @description What the operations screen (`/admin/operations`) shows: the maintenance operations and the status of each. */ + OperationsViewModel: { + /** @description The operations available on this server, for every repository. */ + rows?: components["schemas"]["OperationRow"][]; + /** @description Whether any job is running (the page refreshes itself). */ + anyRunning?: boolean; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description An account that several users own packages through. */ + Organization: { + /** Format: int32 */ + key?: number; + name?: string | null; + /** Format: date-time */ + created?: string; + }; + /** @description What the organization screen (`/admin/organizations/{name}`) shows: the organization, its members and the last action. */ + OrganizationDetailViewModel: { + /** @description The organization's name (route). */ + name?: string | null; + organization?: (null) | components["schemas"]["Organization"]; + /** @description Its members, by name. */ + members?: components["schemas"]["OrganizationMemberRow"][]; + /** + * Format: int32 + * @description How many package IDs it owns, in every repository. + */ + ownedPackageIds?: number; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Adding a member to an organization, changing their administrator flag or removing them. */ + OrganizationMemberForm: { + /** @description The member's user name. */ + userName: string | null; + /** @description Whether the member administers the organization (ignored when removing). */ + isAdmin: boolean; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description A member as the organization page lists them. */ + OrganizationMemberRow: { + /** @description The user name. */ + userName: string | null; + /** @description Whether the member administers the organization. */ + isAdmin: boolean; + }; + /** @description What happens to one organization when an administrator deletes a member. */ + OrganizationOutcome: { + /** @description The organization. */ + name: string | null; + /** @description A sentence for the confirmation page. */ + outcome: string; + }; + /** @description Renaming an organization. */ + OrganizationRenameForm: { + /** @description The new name. */ + newName: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description An organization as the administrator's list shows it. */ + OrganizationSummary: { + /** @description The name. */ + name: string | null; + /** + * Format: date-time + * @description When it was created. + */ + created: string; + /** + * Format: int32 + * @description How many members it has. + */ + members: number; + /** + * Format: int32 + * @description How many of them administer it. + */ + administrators: number; + /** + * Format: int32 + * @description How many package IDs it owns, counted per repository. + */ + packageIds: number; + }; + /** @description The signed-in user's organizations screen. */ + OrganizationsViewModel: { + /** @description The organizations the user belongs to. */ + organizations?: components["schemas"]["AccountOrganization"][]; + /** @description The answer to the last action. */ + message?: string | null; + }; + /** @description One owned package ID, summarised across its versions. */ + OwnedPackage: { + id?: string | null; + /** @description The highest version, listed or not, or null when no version remains. */ + latestVersion?: string | null; + latestVersionIsListed?: boolean; + /** Format: int32 */ + versionCount?: number; + /** Format: int64 */ + downloads?: number; + }; + Package: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + id?: string | null; + version?: components["schemas"]["NuGetVersion"]; + authors?: string[] | null; + description?: string | null; + /** Format: int64 */ + downloads?: number; + hasReadme?: boolean; + hasEmbeddedIcon?: boolean; + isPrerelease?: boolean; + releaseNotes?: string | null; + language?: string | null; + listed?: boolean; + minClientVersion?: string | null; + /** + * Format: date-time + * @description The time at which the package was published, in UTC. + */ + published?: string; + requireLicenseAcceptance?: boolean; + semVerLevel?: components["schemas"]["SemVerLevel"]; + summary?: string | null; + title?: string | null; + /** Format: uri */ + iconUrl?: string | null; + /** Format: uri */ + licenseUrl?: string | null; + /** Format: uri */ + projectUrl?: string | null; + /** Format: uri */ + repositoryUrl?: string | null; + repositoryType?: string | null; + tags?: string[] | null; + /** + * Format: byte + * @description Used for optimistic concurrency. + */ + rowVersion?: string | null; + dependencies?: components["schemas"]["PackageDependency"][] | null; + packageTypes?: components["schemas"]["PackageType"][] | null; + targetFrameworks?: components["schemas"]["TargetFramework"][] | null; + deprecation?: (null) | components["schemas"]["PackageDeprecation"]; + /** @description The known vulnerabilities affecting this version. */ + vulnerabilities?: components["schemas"]["PackageVulnerability"][] | null; + normalizedVersionString?: string | null; + originalVersionString?: string | null; + iconUrlString?: string | null; + licenseUrlString?: string | null; + projectUrlString?: string | null; + repositoryUrlString?: string | null; + }; + /** + * @description How BaGet should interpret package deletion requests. + * See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package + * @enum {string} + */ + PackageDeletionBehavior: "Unlist" | "HardDelete"; + PackageDependency: { + /** Format: int32 */ + key?: number; + /** @description The dependency's package ID. Null if this is a dependency group without any dependencies. */ + id?: string | null; + /** @description The dependency's package version. Null if this is a dependency group without any dependencies. */ + versionRange?: string | null; + targetFramework?: string | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** @description A package that depends on the queried package. */ + PackageDependent: { + /** @description The dependent package id. */ + id?: string | null; + /** @description The description of the dependent package. */ + description?: string | null; + /** + * Format: int64 + * @description The total downloads for the dependent package. + */ + totalDownloads?: number; + }; + /** + * @description A package version marked as deprecated. + * See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation + */ + PackageDeprecation: { + /** Format: int32 */ + key?: number; + /** + * @description Why the package was deprecated. The protocol defines "Legacy", "CriticalBugs" + * and "Other"; a package may carry more than one. + */ + reasons?: string[] | null; + /** @description Free text explaining the deprecation. Optional. */ + message?: string | null; + /** @description The ID of the package to use instead. Null if none was suggested. */ + alternatePackageId?: string | null; + /** + * @description The versions of the alternate package that may be used, or "*" for any. + * Null if no alternate package was suggested. + */ + alternateVersionRange?: string | null; + /** + * Format: int32 + * @description The key of the deprecated package version. Nullable so that the relationship + * stays optional in the database: a required one would need a foreign key change, + * which SQLite cannot make in place. + */ + packageKey?: number | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** @description What the package page shows about the version it displays (a flat copy of the stored package, with no navigation properties). */ + PackageDetails: { + /** @description The package ID. */ + id?: string | null; + /** @description The normalized version. */ + version?: string | null; + /** @description The description. */ + description?: string | null; + /** @description The release notes. */ + releaseNotes?: string | null; + /** @description The project website, or an empty string. */ + projectUrl?: string | null; + /** @description The source repository, or an empty string. */ + repositoryUrl?: string | null; + /** + * Format: int64 + * @description The downloads of this version. + */ + downloads?: number; + /** @description The authors. */ + authors?: string[]; + }; + PackageDownloads: { + id?: string | null; + /** @description Null when the downloads are a whole package ID's. */ + version?: string | null; + /** Format: int64 */ + downloads?: number; + /** Format: date-time */ + published?: string | null; + }; + /** @description The form of `Deprecate`. */ + PackageManageDeprecateForm: { + /** @description The version. */ + version?: string | null; + /** @description The reasons (at least one of `Legacy`, `CriticalBugs`, `Other`). */ + reasons?: string[] | null; + /** @description Free text, optional. */ + message?: string | null; + /** @description The package to use instead, optional. */ + alternatePackageId?: string | null; + /** @description The versions of it that may be used, optional (needs string? PackageManageDeprecateForm.AlternatePackageId). */ + alternateVersionRange?: string | null; + }; + /** @description A version's deprecation. */ + PackageManageDeprecation: { + /** @description Why (`Legacy`, `CriticalBugs`, `Other`). */ + reasons: string[]; + /** @description Free text, or null. */ + message: string | null; + /** @description The package to use instead, or null. */ + alternatePackageId: string | null; + /** @description The versions of it that may be used, or null. */ + alternateVersionRange: string | null; + }; + /** @description The form of a permanent deletion of a version (administrators; the password confirms). */ + PackageManageHardDeleteForm: { + /** @description The version. */ + version?: string | null; + /** @description The caller's password. */ + password?: string | null; + }; + /** @description An owner of a package ID. */ + PackageManageOwner: { + /** @description The user or organization name. */ + ownerName: string | null; + /** @description Whether the ID is reserved for this owner. */ + isVerified: boolean; + }; + /** @description The form of a handler that names an owner. */ + PackageManageOwnerForm: { + /** @description The user or organization. */ + ownerName?: string | null; + }; + /** @description The form of a handler that only asks for the password. */ + PackageManagePasswordForm: { + /** @description The caller's password. */ + password?: string | null; + }; + /** @description The form of `RemoveVulnerability`. */ + PackageManageRemoveVulnerabilityForm: { + /** @description The version. */ + version?: string | null; + /** + * Format: int32 + * @description The vulnerability's key. + */ + key?: number; + }; + /** @description An open abuse report. */ + PackageManageReport: { + /** + * Format: int32 + * @description The report's key (what `ResolveReport` takes). + */ + key: number; + /** @description The reported version. */ + packageVersion: string | null; + /** @description The reason given. */ + reason: string | null; + /** @description The details given. */ + details: string | null; + /** @description Where to reply, if the reporter gave an address. */ + reporterEmail: string | null; + }; + /** @description The form of `ResolveReport`. */ + PackageManageReportForm: { + /** + * Format: int32 + * @description The report's key. + */ + key?: number; + }; + /** + * @description What the package management screen (`/packages/{id}/manage`) shows, as plain data (the JSON model of `/api/ui/packages/{id}/manage`). + * The page's own `ManageViewModel` is built from it for the view. + */ + PackageManageScreen: { + /** @description The package ID from the address. */ + id?: string | null; + /** @description The ID's owners. */ + owners?: components["schemas"]["PackageManageOwner"][]; + /** @description The ID's versions, newest first, unlisted ones included. */ + versions?: components["schemas"]["PackageManageVersion"][]; + /** @description The open abuse reports against the ID. */ + reports?: components["schemas"]["PackageManageReport"][]; + /** @description The outcome of the last action. */ + message?: string | null; + /** @description Whether validation has submissions for the ID. */ + hasValidation?: boolean; + /** @description Whether the ID is verified (reserved). */ + isVerified?: boolean; + /** @description The PDBs indexed from each version's symbol package, by normalized version. */ + symbols?: { + [key: string]: components["schemas"]["PackageManageSymbol"][]; + }; + /** @description Whether the database records symbols per package version. */ + symbolsSupported?: boolean; + /** @description The severity names a vulnerability can have, by their protocol number. */ + severityNames?: string[]; + /** @description Whether the caller is an administrator. */ + isAdministrator?: boolean; + /** @description Whether the caller manages this ID only as an administrator (not as an owner). */ + actingAsAdministrator?: boolean; + /** @description Whether the caller has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + deletionBehavior?: components["schemas"]["PackageDeletionBehavior"]; + /** @description Whether the server refuses writes. */ + isReadOnlyMode?: boolean; + }; + /** @description An indexed PDB of a version. */ + PackageManageSymbol: { + /** @description The PDB file name. */ + fileName: string; + /** @description Its signature key. */ + key: string; + }; + /** @description The form of `SetVerified`. */ + PackageManageVerifiedForm: { + /** @description Whether the ID is verified. */ + verified?: boolean; + }; + /** @description One version of the ID. */ + PackageManageVersion: { + /** @description The version as published (original text). */ + version: string; + /** @description The normalized version, which the forms post back. */ + normalizedVersion: string | null; + /** + * Format: int64 + * @description The download count. + */ + downloads: number; + /** @description Whether the version is listed. */ + listed: boolean; + deprecation: (null) | components["schemas"]["PackageManageDeprecation"]; + /** @description Its vulnerabilities. */ + vulnerabilities: components["schemas"]["PackageManageVulnerability"][]; + }; + /** @description The form of a handler that names a version. */ + PackageManageVersionForm: { + /** @description The (normalized) version. */ + version?: string | null; + }; + /** @description A vulnerability recorded for a version. */ + PackageManageVulnerability: { + /** + * Format: int32 + * @description The row's key (what `RemoveVulnerability` takes). + */ + key: number; + /** @description The advisory. */ + advisoryUrl: string | null; + /** + * Format: int32 + * @description 0 low, 1 moderate, 2 high, 3 critical. + */ + severity: number; + /** @description The affected range, or null. */ + versionRange: string | null; + /** @description Null for a manual entry, `osv` for one the scanner wrote (not editable here). */ + source: string | null; + }; + /** @description The form of `AddVulnerability`. */ + PackageManageVulnerabilityForm: { + /** @description The version. */ + version?: string | null; + /** @description The advisory URL. */ + advisoryUrl?: string | null; + /** + * Format: int32 + * @description 0 low, 1 moderate, 2 high, 3 critical. + */ + severity?: number; + /** @description The affected range, optional. */ + versionRange?: string | null; + }; + /** @description An owner of every version of a package ID. */ + PackageOwner: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + packageId?: string | null; + /** @description A user name or an organization name. */ + ownerName?: string | null; + /** + * @description Set by the server's administrator to mark the ID as reserved for this owner, + * which search reports as "verified". + */ + isVerified?: boolean; + }; + /** @description What the package page shows. */ + PackageScreen: { + /** @description False when the package (or any listed version of it) does not exist; PackageDetails PackageScreen.Package then only names the ID. */ + found?: boolean; + package?: components["schemas"]["PackageDetails"]; + /** @description The package is a dotnet template. */ + isDotnetTemplate?: boolean; + /** @description The package is a dotnet tool. */ + isDotnetTool?: boolean; + /** + * Format: date-time + * @description When any version was last published. + */ + lastUpdated?: string; + /** + * Format: int64 + * @description Downloads of every version. + */ + totalDownloads?: number; + /** @description The packages that depend on this one. */ + usedBy?: components["schemas"]["PackageDependent"][]; + /** @description The dependencies, by framework. */ + dependencyGroups?: components["schemas"]["DependencyGroupModel"][]; + /** @description The listed versions, newest first. */ + versions?: components["schemas"]["PackageVersionEntry"][]; + /** @description The readme as safe HTML (ReadmeMarkdown), or null. */ + readmeHtml?: string | null; + /** @description The frameworks the package supports, by family. */ + frameworkGroups?: components["schemas"]["FrameworkGroup"][]; + /** @description The install commands, one tab per tool. */ + installTabs?: components["schemas"]["InstallSnippet"][]; + /** @description Owner names; empty unless accounts are enabled and the package has owners. */ + owners?: string[]; + /** @description The avatar address of each owner by name; empty when Gravatar is off or accounts are disabled. */ + ownerAvatars?: { + [key: string]: string; + }; + /** + * @description Where the management page is, when the caller may open it (an owner holding the Manage permission, or an administrator), else null. + * The use case answers an application-relative address (`~/packages/…`); the controller resolves it against the path base. + */ + manageUrl?: string | null; + /** @description The icon address. */ + iconUrl?: string | null; + /** @description The license address, null for a license expression or file. */ + licenseUrl?: string | null; + /** @description Where the package file is downloaded. */ + packageDownloadUrl?: string | null; + /** + * @description This version on nuget.info, the web app of NuGet Package Explorer, as nuget.org links it. nuget.info always downloads from + * nuget.org, so the link only works for a package that is also published there. + */ + packageExplorerUrl?: string | null; + }; + PackageType: { + /** Format: int32 */ + key?: number; + name?: string | null; + version?: string | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** + * @description One step of validating a pushed package: a validator's verdict, or the final + * indexing step. A submission is every row sharing a string? PackageValidation.SubmissionId. + */ + PackageValidation: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + submissionId?: string | null; + packageId?: string | null; + /** @description The normalized version. */ + packageVersion?: string | null; + /** + * Format: int32 + * @description The indexed package, once the submission succeeds. Nullable so that the + * relationship is additive; see PackageDeprecation. + */ + packageKey?: number | null; + package?: (null) | components["schemas"]["Package"]; + /** @description The validator's name, or string PackageValidation.IndexType. */ + type?: string | null; + state?: components["schemas"]["PackageValidationState"]; + /** @description Why the step failed, if it did. */ + message?: string | null; + /** Format: date-time */ + created?: string; + /** Format: date-time */ + completed?: string | null; + }; + /** @enum {string} */ + PackageValidationState: "Pending" | "Succeeded" | "Failed"; + /** @description One row of the versions table of the package page. */ + PackageVersionEntry: { + /** @description The normalized version. */ + version: string; + /** + * Format: int64 + * @description Its downloads. + */ + downloads: number; + /** @description Whether it is the version shown. */ + selected: boolean; + /** + * Format: date-time + * @description When it was published. + */ + lastUpdated: string; + }; + /** + * @description A known vulnerability affecting a package version. + * See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info + */ + PackageVulnerability: { + /** Format: int32 */ + key?: number; + /** @description The URL of the advisory describing the vulnerability. */ + advisoryUrl?: string | null; + /** + * Format: int32 + * @description The severity, as the protocol numbers it: 0 low, 1 moderate, 2 high, 3 critical. + */ + severity?: number; + /** @description The range of versions the advisory applies to. */ + versionRange?: string | null; + /** + * @description Who recorded it: null for an entry set through the metadata API or the Manage page, `osv` for one the vulnerability + * scanner wrote from a scan of this version. Setting the list by hand replaces the manual entries only; the next scan + * replaces the scanner's. + */ + source?: string | null; + /** + * Format: int32 + * @description The key of the affected package version. Nullable for the same reason as on + * PackageDeprecation. + */ + packageKey?: number | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** + * @description A known vulnerability affecting a package version, as it appears in the package's + * registration metadata. + * + * See https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#vulnerabilities + */ + PackageVulnerabilityMetadata: { + /** @description The URL of the advisory describing the vulnerability. */ + advisoryUrl?: string | null; + /** + * @description The severity: "0" low, "1" moderate, "2" high, "3" critical. A string in the + * registration metadata, unlike the VulnerabilityInfo resource, which uses a number. + */ + severity?: string | null; + }; + /** @description What a form that only re-asks the password posts (delete the account, turn two-factor off, reset the authenticator). */ + PasswordConfirmationForm: { + /** @description The password, asked again. */ + password?: string | null; + }; + /** @description A write that only asks the administrator's password again (approve an account, delete an organization). */ + PasswordForm: { + /** @description The administrator's password. */ + password: string | null; + }; + /** @description The result of previewing repository and package patterns. */ + PatternPreview: { + /** @description The NuGet repositories whose names match the repository patterns. */ + repositories: string[]; + /** @description The package ID typed in the test box, if any. */ + testPackage: string | null; + test: (null) | components["schemas"]["PatternTest"]; + }; + /** @description The outcome of PatternTest AccessPatterns.Test(IEnumerable<string>? include, IEnumerable<string>? exclude, string packageId). */ + PatternTest: { + /** @description Whether the target applies to the package. */ + matches: boolean; + /** @description Which pattern decided, in words. */ + explanation: string; + }; + /** @description What the permission target screen (`/admin/permissions/{name}`) shows: the patterns, the preview and the grants. */ + PermissionDetailViewModel: { + /** @description The target name (route). */ + name?: string | null; + /** @description Repository names or globs, one per line. */ + repositoryPatterns?: string | null; + /** @description Package ID globs the target applies to, one per line. */ + includePatterns?: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + principalType?: components["schemas"]["PrincipalType"]; + /** @description The user, group or organization name in the grant form. */ + principalName?: string | null; + target?: (null) | components["schemas"]["TargetDetails"]; + preview?: (null) | components["schemas"]["PatternPreview"]; + formActions?: components["schemas"]["AccessAction"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the permission targets screen (`/admin/permissions`) shows: the targets and the new-target form. */ + PermissionsViewModel: { + /** @description The new target name. */ + name?: string | null; + /** @description Repository names or `*` globs, one per line. */ + repositoryPatterns?: string | null; + /** @description Package ID globs the target applies to, one per line; none means all. */ + includePatterns?: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns?: string | null; + /** @description The project that administers the target, if any. */ + project?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + /** @description The targets. */ + targets?: components["schemas"]["TargetSummary"][]; + /** @description The projects a target can belong to. */ + projects?: components["schemas"]["ProjectSummary"][]; + preview?: (null) | components["schemas"]["PatternPreview"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The fields of the permission-target form (new target, or the patterns of an existing one) and its test box. */ + PermissionTargetForm: { + /** @description The new target's name (ignored for an existing target: the route names it). */ + name?: string | null; + /** @description Repository names or `*` globs, one per line. */ + repositoryPatterns?: string | null; + /** @description Package ID globs the target applies to, one per line; none means all. */ + includePatterns?: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns?: string | null; + /** @description For a new target: the project that administers it, or null. */ + project?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + principalType?: (null) | components["schemas"]["PrincipalType"]; + /** @description For an existing target: the principal name in the grant form (kept across a preview). */ + principalName?: string | null; + /** @description The administrator's password (saving the patterns of an existing target). */ + password?: string | null; + }; + /** @description Removing a principal's grant or project role. */ + PrincipalRemoval: { + type: components["schemas"]["PrincipalType"]; + /** @description The principal's id. */ + principalId: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** + * @description Who a PermissionGrant or ProjectMember names. + * @enum {string} + */ + PrincipalType: "User" | "Group" | "Organization"; + /** @description A user's or an organization's public page: the packages it owns. */ + ProfileViewModel: { + /** @description The account's name. */ + name?: string | null; + /** @description Whether the account is an organization. */ + isOrganization?: boolean; + /** @description The owned packages with their downloads. */ + packages?: components["schemas"]["PackageDownloads"][]; + /** @description The members of an organization. */ + members?: string[]; + /** @description Whether the profile is the signed-in user's own. */ + isCurrentUser?: boolean; + /** @description The account's avatar address, or null when Gravatar is off. */ + avatarUrl?: string | null; + }; + /** @description A new project. */ + ProjectCreation: { + /** @description The project's name. */ + name: string | null; + /** @description A name to show, or null. */ + displayName: string | null; + }; + /** @description A project with its repositories, members and targets. */ + ProjectDetails: { + project: components["schemas"]["ProjectSummary"]; + repositories: string[]; + members: components["schemas"]["ProjectMemberInfo"][]; + targets: components["schemas"]["TargetSummary"][]; + }; + /** @description What the project screen (`/admin/projects/{name}`) shows: repositories, members and the project targets. */ + ProjectDetailViewModel: { + /** @description The project name (route). */ + name?: string | null; + project?: (null) | components["schemas"]["ProjectDetails"]; + /** @description The NuGet repositories not yet in this project, for the assignment picker. */ + assignable?: string[]; + /** @description The new target name. */ + targetName?: string | null; + /** @description Repository globs of the new target, one per line (they only ever reach the project repositories). */ + repositoryPatterns?: string | null; + /** @description Include globs of the new target. */ + includePatterns?: string | null; + /** @description Exclude globs of the new target. */ + excludePatterns?: string | null; + /** @description A package ID to test the patterns with. */ + testPackage?: string | null; + preview?: (null) | components["schemas"]["PatternPreview"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Giving a user or group a role in a project. */ + ProjectMemberForm: { + type: components["schemas"]["PrincipalType"]; + /** @description The principal's name. */ + principalName: string | null; + role: components["schemas"]["ProjectRole"]; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** @description A member of a project. */ + ProjectMemberInfo: { + principalType: components["schemas"]["PrincipalType"]; + principalId: string; + principal: string; + role: components["schemas"]["ProjectRole"]; + }; + /** @description Putting a repository in a project or taking it out. */ + ProjectRepositoryForm: { + /** @description The repository's name. */ + repository: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + }; + /** + * @description A member's role in a Project, applying to the project's repositories. + * @enum {string} + */ + ProjectRole: "Viewer" | "Developer" | "Admin"; + /** @description A project as the admin pages list it. */ + ProjectSummary: { + /** Format: int32 */ + key: number; + name: string; + displayName: string | null; + /** Format: int32 */ + repositoryCount: number; + /** Format: int32 */ + memberCount: number; + }; + /** @description What the projects screen (`/admin/projects`) shows: the projects the user may open and the new-project form. */ + ProjectsViewModel: { + /** @description The new project name. */ + name?: string | null; + /** @description The new project display name. */ + displayName?: string | null; + /** @description The projects the signed-in user may open. */ + projects?: components["schemas"]["ProjectSummary"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed-in user is a server administrator. */ + isServerAdministrator?: boolean; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The fields of a project's new permission target and its test box. */ + ProjectTargetForm: { + /** @description The new target's name. */ + targetName: string | null; + /** @description Repository globs, one per line (they only ever reach the project's repositories). */ + repositoryPatterns: string | null; + /** @description Package ID globs the target applies to, one per line. */ + includePatterns: string | null; + /** @description Package ID globs the target leaves out, one per line. */ + excludePatterns: string | null; + /** @description A package ID to test the patterns with. */ + testPackage: string | null; + }; + /** @description The result of the readiness check. */ + ReadinessReport: { + /** + * Format: date-time + * @description When it ran (UTC). + */ + checkedAt: string; + /** @description Each probe. */ + probes: components["schemas"]["HealthProbe"][]; + /** @description Every probe that decides readiness answered (an informational probe, the shared store, never takes the node out of rotation). */ + isReady?: boolean; + /** @description The failing probes (informational ones too) as one line, or null. */ + problem?: string | null; + }; + /** @description The "confirm it is you" screen of an account without a password. A request binds ReauthenticateForm, never this type. */ + ReauthenticateViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The linked providers to pick from when the account has several (one button each); null otherwise. */ + providers?: components["schemas"]["ExternalProviderInfo"][] | null; + /** @description Where to go after the provider answered; only a local URL is followed. */ + returnUrl?: string | null; + /** @description The id of the linked provider to sign in again with; empty takes the only linked one (several: the screen offers the choice). */ + provider?: string | null; + }; + /** @description What the recovery-code form posts. */ + RecoveryCodeLoginForm: { + /** @description The recovery code. */ + recoveryCode: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description The second step of signing in with a recovery code. A request binds RecoveryCodeLoginForm, never this type. */ + RecoveryCodeLoginViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The recovery code. */ + recoveryCode: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description What the registration form posts. */ + RegisterForm: { + /** @description The wanted user name. */ + userName: string | null; + /** @description The email address. */ + email?: string | null; + /** @description The password. Never echoed. */ + password: string | null; + /** @description The password again. Never echoed. */ + confirmPassword: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description The registration screen. A request binds RegisterForm, never this type; the passwords are always empty here. */ + RegisterViewModel: { + /** @description Whether the account was created but waits for an administrator (`Accounts:RequireApproval`). */ + awaitingApproval?: boolean; + /** @description Whether a confirmation link was mailed. */ + confirmationSent?: boolean; + /** @description Whether the screen asks for an email address. */ + emailRequired?: boolean; + session?: (null) | components["schemas"]["SessionModel"]; + /** @description The wanted user name. */ + userName: string | null; + /** @description The email address. */ + email?: string | null; + /** @description The password. Never echoed. */ + password: string | null; + /** @description The password again. Never echoed. */ + confirmPassword: string | null; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description What a remote repository holds and remembers. */ + RemoteCacheOverview: { + status: components["schemas"]["RemoteCacheStatus"]; + /** + * Format: int32 + * @description Package versions stored. + */ + packageCount: number; + /** + * Format: int32 + * @description Distinct package ids stored. + */ + packageIdCount: number; + /** + * Format: int64 + * @description Bytes of the blobs stored (a Docker repository: its layers); 0 when the format does not report it. + * @default 0 + */ + storedBytes: number; + }; + /** @description What the cache of one remote repository looks like right now (in memory, per node; resets on restart). */ + RemoteCacheStatus: { + /** + * Format: int32 + * @description Cached answers of the upstream (version lists and metadata), expired ones included until used or purged. + */ + metadataEntries: number; + /** + * Format: int32 + * @description Remembered "the upstream does not have it" answers still in force. + */ + negativeEntries: number; + /** + * Format: int64 + * @description Answers served from the cache. + */ + hits: number; + /** + * Format: int64 + * @description Questions that went to the upstream. + */ + misses: number; + /** + * Format: int64 + * @description Questions answered "not found" from the negative cache. + */ + negativeHits: number; + /** + * Format: int64 + * @description Expired answers served because the upstream could not be reached. + */ + staleServed: number; + /** + * Format: int64 + * @description Failed attempts to reach the upstream. + */ + failures: number; + /** + * Format: date-time + * @description The last time the upstream answered. + */ + lastSuccessUtc: string | null; + /** + * Format: date-time + * @description The last time it could not be reached. + */ + lastFailureUtc: string | null; + /** + * Format: date-time + * @description When the current run of failures began, or null while it answers. + */ + failingSinceUtc: string | null; + /** @description What failed, without URLs or credentials. */ + lastError: string | null; + }; + /** @description The outcome of asking an upstream whether it answers. */ + RemoteConnectionResult: { + /** @description Whether the upstream answered as the configured protocol requires. */ + success: boolean; + /** @description What was found or what failed, without URLs or credentials. */ + message: string; + /** + * Format: int32 + * @description The HTTP status, when there was an answer. + */ + statusCode: number | null; + /** + * Format: int64 + * @description How long the attempt took. + */ + elapsedMilliseconds: number; + }; + /** + * @description The fields of a remote repository's upstream settings as the create and edit pages post them (prefix + * `Remote`). The password is never rendered back: a blank one on save keeps the stored one. + */ + RemoteFormModel: { + format?: components["schemas"]["RepositoryFormat"]; + /** @description The upstream URL (V3 `index.json` or V2 feed, or an npm registry's base URL). */ + url?: string | null; + protocol?: components["schemas"]["RemoteProtocol"]; + /** @description The HTTP Basic user name, if the upstream needs one. */ + username?: string | null; + /** @description The HTTP Basic password or token; blank keeps the stored one. Input only: a screen never sends it back (the use cases clear it from every model they return). */ + password?: string | null; + /** @description Remove the stored password on save. */ + clearPassword?: boolean; + /** + * Format: int32 + * @description How long the upstream's answers are reused, in seconds (0 = ask every time). + */ + metadataTtlSeconds?: number; + /** + * Format: int32 + * @description How long "not found" is remembered, in seconds (0 = ask every time). + */ + negativeTtlSeconds?: number; + /** + * Format: int32 + * @description The download timeout in seconds. + */ + downloadTimeoutSeconds?: number; + /** @description Never contact the upstream. */ + offline?: boolean; + /** @description Keep what is fetched (off = pass-through). */ + storeLocally?: boolean; + /** @description For display: whether a password is stored. */ + hasPassword?: boolean; + /** @description For display: URL, protocol and timeout are fixed because `Mirror:*` sets them. */ + endpointFromMirror?: boolean; + }; + /** + * @description The protocol a remote repository's upstream speaks. + * @enum {string} + */ + RemoteProtocol: "V3" | "V2" | "Npm" | "Maven" | "Docker"; + /** @description A remote repository as the administration pages edit it. */ + RemoteRepositoryDetail: { + repository: components["schemas"]["RepositoryInfo"]; + settings: components["schemas"]["RemoteRepositorySettings"]; + /** @description Whether a password is stored. */ + hasPassword: boolean; + /** @description Whether it is the string Repository.MirrorName repository the default repository fetches through while `Mirror:Enabled` is set (its URL, protocol and timeout then come from `Mirror:*`). */ + isMirror: boolean; + }; + /** + * @description What a RepositoryKind.Remote repository knows about its upstream: kept as JSON in + * string? Repository.Settings. The password never appears in clear there: it is stored as + * string? RemoteRepositorySettings.ProtectedPassword (see IRemoteCredentialProtector) and string? RemoteRepositorySettings.Password only + * exists in memory. + */ + RemoteRepositorySettings: { + /** @description The upstream: a V3 `index.json` URL or a V2 feed URL, the base URL of an npm registry, the root of a Maven repository or the address of a Docker registry (absolute http or https). */ + url?: string | null; + protocol?: components["schemas"]["RemoteProtocol"]; + /** + * @description The user name sent with HTTP Basic to the upstream's own host, if any. An npm upstream with a password and no user name + * gets the password as a bearer token (npm's `_authToken`) instead. A Docker upstream gets the pair at its token service + * (HTTP Basic, the `docker login` flow) or, when it asks for Basic itself, at its own host; a password with no user name + * is sent as a ready-made bearer token to the registry's own host. + */ + username?: string | null; + /** @description The password as stored (protected). Opaque to everything but RemoteSettingsCodec. */ + protectedPassword?: string | null; + /** + * Format: int32 + * @description How long the upstream's version list and metadata of a package are reused before it is asked again. 0 asks + * every time (what the mirror always did). + */ + metadataTtlSeconds?: number; + /** + * Format: int32 + * @description How long "the upstream does not have it" (404) is remembered. 0 asks every time. + */ + negativeTtlSeconds?: number; + /** @description Offline mode: the upstream is never contacted; only what is already stored (and cached in memory) is served. */ + offline?: boolean; + /** + * @description Whether packages fetched from the upstream are stored (database and files) so later requests, and requests + * while the upstream is down, are served locally. Off, the repository is a pass-through: metadata comes from the + * upstream (cached by int RemoteRepositorySettings.MetadataTtlSeconds), downloads stream through and nothing is kept (so search + * and the package pages stay empty). + */ + storeLocally?: boolean; + /** + * Format: int32 + * @description The time before a download from the upstream times out. + */ + downloadTimeoutSeconds?: number; + }; + /** @description What the "remove a member" (or "leave") form posts. */ + RemoveOrganizationMemberForm: { + /** @description The organization. */ + organization?: string | null; + /** @description The member to remove. */ + userName?: string | null; + }; + /** @description Removing a named OpenID Connect provider saved on the Settings screen. */ + RemoveSignInProviderForm: { + /** @description The provider id. */ + id: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description Creating, saving or testing a replication, or any write of it that asks the password. */ + ReplicationBody: { + form: (null) | components["schemas"]["ReplicationForm"]; + /** @description The administrator's password. */ + password: string | null; + }; + /** + * @description One replication relationship: a local repository and a repository of another BaGet server, copied in one direction. Not + * repository-scoped (the administrator lists configurations across repositories). Its `RepositoryKey` is a Restrict foreign key, and + * so is `ConfigKey` of its runs and ledger: deleting the repository deletes its configurations, runs and ledger first (code, not cascade). + */ + ReplicationConfig: { + /** Format: int32 */ + key?: number; + /** @description Unique, AccessNames rules. */ + name?: string | null; + /** + * Format: int32 + * @description The local int Repository.Key: a local (not remote, not virtual) repository. + */ + repositoryKey?: number; + direction?: components["schemas"]["ReplicationDirection"]; + /** @description The peer server's base address (`https://other.example/`), not a repository feed. */ + peerUrl?: string | null; + /** @description The peer's repository (`default` or its name); it must be of the same format. */ + peerRepository?: string | null; + /** @description A disabled configuration is never run by the schedule or a deploy; a manual run is refused. */ + enabled?: boolean; + /** @description Push only: a deploy to the local repository starts a run (after a short quiet period). */ + onDeploy?: boolean; + /** + * Format: int32 + * @description Run every this many minutes. Null: only when started (or on deploy). + */ + scheduleMinutes?: number | null; + /** @description What was replicated and is later deleted at the source is deleted at the target too (only items this configuration copied). */ + propagateDeletes?: boolean; + conflict?: components["schemas"]["ReplicationConflict"]; + /** + * Format: date-time + * @description When the schedule was set or the configuration enabled; the first scheduled run is due this long after it. + */ + scheduleStart?: string | null; + /** + * Format: date-time + * @description When the last run started (the schedule counts from the later of this and DateTime? ReplicationConfig.ScheduleStart). + */ + lastRun?: string | null; + /** @description One line about the last run. */ + lastResult?: string | null; + /** Format: date-time */ + created?: string; + /** Format: date-time */ + modified?: string; + }; + /** @description A configuration with the names the page shows; the API key is never part of it. */ + ReplicationConfigView: { + config: components["schemas"]["ReplicationConfig"]; + /** @description The local repository's name, or null when it no longer exists. */ + repository: string | null; + format: (null) | components["schemas"]["RepositoryFormat"]; + /** @description Whether a key is stored. */ + hasApiKey: boolean; + lastRun: (null) | components["schemas"]["ReplicationRun"]; + }; + /** @description What one replication's screen (`/admin/replication/{key}`) shows. */ + ReplicationConfigViewModel: { + /** + * Format: int32 + * @description The configuration's key (route). + */ + key?: number; + form?: components["schemas"]["ReplicationForm"]; + view?: (null) | components["schemas"]["ReplicationConfigView"]; + /** @description The log, newest first. */ + runs?: components["schemas"]["ReplicationRun"][]; + job?: (null) | components["schemas"]["ReplicationJobStatus"]; + test?: (null) | components["schemas"]["ReplicationTestResult"]; + /** + * Format: int32 + * @description How many items the local repository holds, or null when it could not be listed. + */ + localItems?: number | null; + /** @description Whether a run is going here (the page refreshes itself). */ + running?: boolean; + /** @description The local repositories a replication can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + resumable?: components["schemas"]["ReplicationRun"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** + * @description What happens when both sides hold the same item with different content. + * @enum {string} + */ + ReplicationConflict: "TargetWins" | "SourceWins"; + /** + * @description Which way a ReplicationConfig copies. + * @enum {string} + */ + ReplicationDirection: "Push" | "Pull"; + /** + * @description What the replication form posts (`Form.*`): a ReplicationConfig as a person types it. The peer's API key is write + * only: it is never filled back into a page; an empty field keeps the stored key. + */ + ReplicationForm: { + name?: string | null; + repository?: string | null; + direction?: components["schemas"]["ReplicationDirection"]; + peerUrl?: string | null; + peerRepository?: string | null; + /** @description The peer's API key (write only). */ + apiKey?: string | null; + /** @description Forget the stored key. */ + clearApiKey?: boolean; + enabled?: boolean; + onDeploy?: boolean; + /** Format: int32 */ + scheduleMinutes?: number | null; + propagateDeletes?: boolean; + conflict?: components["schemas"]["ReplicationConflict"]; + }; + /** @description What the page knows of a replication started since the server began (in memory); the log table is the durable record. */ + ReplicationJobStatus: { + /** Format: int32 */ + configKey?: number; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + /** @description True while the run is going. */ + running?: boolean; + /** @description Why the job did not even begin a run (read-only server, disabled configuration, lease held elsewhere), or null. */ + refusal?: string | null; + }; + /** @description One run of a configuration: the replication log. */ + ReplicationRun: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The int ReplicationConfig.Key. + */ + configKey?: number; + status?: components["schemas"]["ReplicationRunStatus"]; + /** @description `manual`, `resume`, `schedule` or `deploy`. */ + trigger?: string | null; + /** @description The administrator, or `scheduler`. */ + actor?: string | null; + /** + * Format: int32 + * @description The interrupted or failed run this one continues, when started with Resume. + */ + resumedFrom?: number | null; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + /** + * Format: int32 + * @description Items the plan looked at (both sides listed). + */ + examined?: number; + /** + * Format: int32 + * @description Items copied to the target. + */ + transferred?: number; + /** + * Format: int32 + * @description Items the target already had. + */ + skipped?: number; + /** + * Format: int32 + * @description Items deleted at the target because they were deleted at the source. + */ + deleted?: number; + /** + * Format: int32 + * @description Items held differently on both sides that were left alone (target wins) or replaced (source wins). + */ + conflicts?: number; + /** Format: int32 */ + failures?: number; + /** + * Format: int64 + * @description Bytes of artifact content sent or received. + */ + bytes?: number; + /** @description Why the run failed as a whole, or null. */ + error?: string | null; + /** @description The first failures and conflicts, one per line. */ + detail?: string | null; + }; + /** + * @description How a ReplicationRun ended. + * @enum {string} + */ + ReplicationRunStatus: "Running" | "Succeeded" | "Failed" | "Interrupted"; + /** @description What Task<ReplicationTestResult> IReplicationAdministration.TestAsync(ReplicationInput input, CancellationToken cancellationToken) found. */ + ReplicationTestResult: { + /** @description Whether the peer answered as a BaGet server with this repository. */ + ok: boolean; + /** @description A sentence for the administrator (never the key). */ + message: string; + /** + * Format: int64 + * @description How long it took. + */ + elapsedMilliseconds: number; + peerFormat: (null) | components["schemas"]["RepositoryFormat"]; + /** + * Format: int32 + * @description How many items it holds, when it answered. + */ + peerItems: number | null; + }; + /** @description What the replications screen (`/admin/replication`) shows: every replication and the form that creates one. */ + ReplicationViewModel: { + form?: components["schemas"]["ReplicationForm"]; + /** @description Every replication. */ + replications?: components["schemas"]["ReplicationConfigView"][]; + /** @description The local repositories a replication can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the reporter fills in. The field names (Reason, Details, ReporterEmail) are the contract of the form and of the JSON body. */ + ReportAbuseForm: { + /** @description One of string[] AbuseReport.Reasons. */ + reason: string | null; + /** @description What the reporter saw. */ + details: string | null; + /** @description The address of the reporter, optional. */ + reporterEmail?: string | null; + }; + /** @description The report-abuse screen: the package it is about, what was typed, and whether the report was recorded. */ + ReportAbuseScreen: { + /** @description The package ID. */ + id: string | null; + /** @description The package version. */ + version: string | null; + /** @description Reports are kept in the database, which Azure Table storage cannot do. */ + canReport: boolean; + /** @description True once the report was recorded. */ + submitted: boolean; + form: components["schemas"]["ReportAbuseForm"]; + }; + /** + * @description What the repositories screen (`/admin/repositories`) shows: the repositories with their feed addresses, the list filter and + * the create forms. The posted fields of the create forms (string? RepositoriesViewModel.Name, RemoteFormModel RepositoriesViewModel.Remote) live here too, so a refused + * creation shows again what was typed (the typed upstream password excepted: it is never sent back). + */ + RepositoriesViewModel: { + /** @description The name for the repository to create. */ + name?: string | null; + remote?: components["schemas"]["RemoteFormModel"]; + /** @description The repositories. */ + repositories?: components["schemas"]["RepositorySummary"][]; + /** @description Whether the database can hold more than the default repository. */ + canCreate?: boolean; + message?: string | null; + /** @description Why the last action was refused. */ + error?: string | null; + /** @description The format to keep selected after a refused creation. */ + format?: string | null; + /** @description The format the list is narrowed to (`?format=`), or null. */ + filterFormat?: string | null; + /** @description The kind the list is narrowed to (`?kind=`), or null. */ + filterKind?: string | null; + /** @description The name fragment the list is narrowed to (`?q=`), or null. */ + filterName?: string | null; + /** @description Every format this server knows, for the list filter. */ + allFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The formats a remote repository can be created for. */ + remoteFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The formats a virtual repository can be created for. */ + virtualFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The formats other than NuGet that can be created here, with their form fields. */ + otherFormats?: components["schemas"]["RepositoryFormatChoice"][]; + /** @description The virtual repositories that have a deploy repository, so take uploads (a remote one takes none). */ + deployable?: string[]; + /** @description The feed address of each repository, by repository name. */ + feeds?: { + [key: string]: string; + }; + /** @description The base address of each repository (where its format's routes start, ends with a slash), by repository name. */ + baseUrls?: { + [key: string]: string; + }; + /** @description The links its format contributes for each repository (browse, upload...), without the upload link where it takes none, by repository name. */ + links?: { + [key: string]: components["schemas"]["FormatLink"][]; + }; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description One repository with what a user may do there and the grants behind it (the account and user pages). */ + RepositoryAccessRow: { + repository: components["schemas"]["RepositoryInfo"]; + explanation: components["schemas"]["AccessExplanation"]; + }; + /** @description Who holds what in one repository (Task<RepositoryAccessSummary> IAccessEvaluator.DescribeAsync(RepositoryInfo repository, CancellationToken cancellationToken)). */ + RepositoryAccessSummary: { + repository: components["schemas"]["RepositoryInfo"]; + /** @description The repository's anonymous-read switch. */ + anonymousRead: boolean; + /** @description The name of the project the repository belongs to, if any. */ + project: string | null; + /** + * @description False where there is no access model (Azure Table): everyone reads, any authenticated + * caller writes, subject to ownership. + */ + modelAvailable: boolean; + /** @description Every grant and project role that applies to the repository. */ + holders: components["schemas"]["AccessReason"][]; + }; + /** + * @description The body of the create forms of the repositories screen (`POST /api/ui/admin/repositories` and its `create/...` handlers). Which fields + * a handler reads is stated on its use case method; the others are ignored. + */ + RepositoryCreateForm: { + /** @description The name of the repository to create. */ + name?: string | null; + /** @description The format (`Npm`, `Maven`, `Docker`...); blank is NuGet where a format may be omitted. */ + format?: string | null; + remote?: components["schemas"]["RemoteFormModel"]; + /** + * @description Whether requests without credentials may read the repository. Null: the default (a local or virtual repository is readable by anyone; a remote + * one only when it has no credentials). + */ + anonymousRead?: boolean | null; + /** @description The administrator's password (creating a remote repository asks for it). */ + password?: string | null; + /** @description The format's own create fields (string FormatCreateField.Name to value) of a local repository of a format other than NuGet. */ + fields?: { + [key: string]: string; + } | null; + }; + /** @description What the delete-repository screen (`/admin/repositories/{name}/delete`) shows. */ + RepositoryDeleteViewModel: { + /** @description The repository's name (route). */ + name?: string | null; + repository?: (null) | components["schemas"]["RepositorySummary"]; + /** @description The virtual repositories that list this repository as a member (the deletion is refused while there are any). */ + referencedBy?: string[]; + /** @description Why the deletion was refused. */ + error?: string | null; + }; + /** + * @description The body of every action of the repository screen (`/api/ui/admin/repositories/{name}/...`), the JSON twin of what the page's forms post. Which fields + * an action reads is stated on its use case method; the others are ignored. + */ + RepositoryEditRequest: { + /** @description Whether requests without credentials may read the repository. */ + anonymousRead?: boolean; + remote?: components["schemas"]["RemoteFormModel"]; + /** @description The package id to resolve in the preview. */ + previewPackageId?: string | null; + /** @description The package version to resolve in the preview. */ + previewVersion?: string | null; + /** @description The package id to purge from the cache. */ + packageId?: string | null; + /** @description The version to purge (blank = every version). */ + packageVersion?: string | null; + /** @description The administrator's password (saving, testing and purging a remote repository ask for it). */ + password?: string | null; + /** @description The member to add, remove or move. */ + member?: string | null; + /** @description `up` or `down`. */ + direction?: string | null; + /** @description The member that receives uploads (blank: none). */ + deploy?: string | null; + /** @description The versions a Maven repository accepts (`Releases`, `Snapshots`, `Both`). */ + policy?: string | null; + /** @description Whether a Maven release may be redeployed (`Yes`/`No`). */ + redeploy?: string | null; + /** @description How many snapshot builds a Maven repository keeps. */ + snapshotBuilds?: string | null; + }; + /** + * @description What the repository screen (`/admin/repositories/{name}`) shows: the repository, its access summary and, by kind, its + * upstream and cache (remote), members and preview (virtual) or Maven settings. The posted fields (anonymous read, upstream, preview + * and purge inputs) live here too, so a refused action shows again what was typed. + */ + RepositoryEditViewModel: { + /** @description The repository's name (route). */ + name?: string | null; + /** @description Whether requests without credentials may read the repository. */ + anonymousRead?: boolean; + repository?: (null) | components["schemas"]["RepositorySummary"]; + remote?: components["schemas"]["RemoteFormModel"]; + remoteDetail?: (null) | components["schemas"]["RemoteRepositoryDetail"]; + mavenSettings?: (null) | components["schemas"]["MavenRepositorySettings"]; + cache?: (null) | components["schemas"]["RemoteCacheOverview"]; + virtualDetail?: (null) | components["schemas"]["VirtualRepositoryDetail"]; + /** @description The repositories that can still be added to a virtual repository. */ + memberCandidates?: components["schemas"]["RepositoryInfo"][]; + /** @description The virtual repositories that list this repository as a member. */ + referencedBy?: string[]; + /** @description The package id to resolve in the preview. */ + previewPackageId?: string | null; + /** @description The package version to resolve in the preview. */ + previewVersion?: string | null; + preview?: (null) | components["schemas"]["ResolutionPreview"]; + testResult?: (null) | components["schemas"]["RemoteConnectionResult"]; + message?: string | null; + /** @description Why the last action was refused. */ + error?: string | null; + /** @description The package id to purge from the cache. */ + packageId?: string | null; + /** @description The version to purge (blank = every version). */ + packageVersion?: string | null; + access?: (null) | components["schemas"]["RepositoryAccessSummary"]; + browseScreen?: components["schemas"]["ScreenRef"]; + /** @description The repository's feed address. */ + feedUrl?: string; + mirrorRepository?: (null) | components["schemas"]["RemoteRepositoryDetail"]; + /** @description Whether `Mirror:Enabled` makes the default repository fetch through RemoteRepositoryDetail? RepositoryEditViewModel.MirrorRepository. */ + mirrorActive?: boolean; + /** @description The name of what a package is called in this repository's format (shown in the labels). */ + packageWord?: string | null; + /** @description What the "version" of a package is called in this repository's format (a Docker image has a tag or a digest). */ + versionWord?: string | null; + /** @description The label of the field that names a package (a Docker image is an image name). */ + packageLabel?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** + * @description The package format a Repository serves. Stored as its name, so a value may be appended + * but never renumbered or renamed. + * @enum {string} + */ + RepositoryFormat: "NuGet" | "Npm" | "Maven" | "Docker"; + /** @description A package format a repository can be created for, with the extra fields its create form asks (the JSON form of an IFormatModule). */ + RepositoryFormatChoice: { + format: components["schemas"]["RepositoryFormat"]; + /** @description Its name for people (`npm`, `Maven`). */ + displayName: string; + /** @description What the administrator fills in to create a local repository of it, besides the name. */ + createFields: components["schemas"]["FormatCreateField"][]; + }; + /** + * @description What a request, job or command needs to know about the repository it works in: immutable, and small enough to + * copy around. + */ + RepositoryInfo: { + /** + * Format: int32 + * @description The int Repository.Key. + */ + key: number; + /** @description The string? Repository.Name. */ + name: string; + format: components["schemas"]["RepositoryFormat"]; + kind: components["schemas"]["RepositoryKind"]; + /** @description Whether this is the string Repository.DefaultName repository. */ + isDefault?: boolean; + /** + * @description The path in front of this repository's routes, feeds and pages, without a leading slash: nothing for the + * default repository (served at `/`), else `r/{name}/`. + */ + pathPrefix?: string | null; + }; + /** + * @description How a Repository gets its content. Stored as its name. + * @enum {string} + */ + RepositoryKind: "Local" | "Remote" | "Virtual"; + /** @description The packages the user owns in one repository. */ + RepositoryPackages: { + repository: components["schemas"]["RepositoryInfo"]; + packages: components["schemas"]["OwnedPackage"][]; + }; + /** @description A repository as the administration pages list it. */ + RepositorySummary: { + /** + * Format: int32 + * @description The int Repository.Key. + */ + key: number; + /** @description The string? Repository.Name. */ + name: string; + format: components["schemas"]["RepositoryFormat"]; + kind: components["schemas"]["RepositoryKind"]; + /** @description Whether requests without credentials may read it. */ + anonymousRead: boolean; + /** + * Format: date-time + * @description When the repository was created (UTC). + */ + created: string; + /** + * Format: int32 + * @description How many package versions it holds. + */ + packageCount: number; + /** @description Whether this is the string Repository.DefaultName repository, which can be neither renamed nor deleted. */ + isDefault?: boolean; + }; + /** @description What the new-password form behind a reset link posts. */ + ResetPasswordForm: { + /** @description The account named by the link. */ + userId?: string | null; + /** @description The encoded reset token of the link. */ + code?: string | null; + /** @description The new password. Never echoed. */ + password: string | null; + /** @description The new password again. Never echoed. */ + confirmPassword: string | null; + }; + /** @description The screen behind the link of a password reset email. A request binds ResetPasswordForm, never this type. */ + ResetPasswordViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The account named by the link. */ + userId?: string | null; + /** @description The encoded reset token of the link. */ + code?: string | null; + /** @description The new password. Never echoed. */ + password: string | null; + /** @description The new password again. Never echoed. */ + confirmPassword: string | null; + }; + /** + * @description What asking one member about a package version found. + * @enum {string} + */ + ResolutionOutcome: "Stored" | "WouldFetch" | "NotFound" | "Unavailable" | "NotAsked" | "Offline"; + /** @description Where a package version would come from, member by member. */ + ResolutionPreview: { + /** @description The package id asked about (`group:artifact` for Maven). */ + packageId: string; + /** @description The version asked about, as written for the format (a NuGet or npm version in its normalized form; a Maven version as typed). */ + version: string; + /** @description The effective members in resolution order and what each found. */ + steps: components["schemas"]["ResolutionStep"][]; + answers: (null) | components["schemas"]["RepositoryInfo"]; + }; + /** @description One member's part in ResolutionPreview. */ + ResolutionStep: { + member: components["schemas"]["RepositoryInfo"]; + outcome: components["schemas"]["ResolutionOutcome"]; + }; + /** @description Placing a legal hold. */ + RetentionHoldForm: { + /** @description The repository of the hold. */ + holdRepository: string | null; + /** @description The artifact name. */ + holdName: string | null; + /** @description The version; empty for every version. */ + holdVersion: string | null; + /** @description Why (a case number, a ticket). */ + reason: string | null; + }; + /** @description Lifting a legal hold. */ + RetentionHoldRemoval: { + /** + * Format: int32 + * @description The hold's number. + */ + key: number; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description What the legal holds screen (`/admin/retention/holds`) shows. */ + RetentionHoldsViewModel: { + /** @description Only the holds of this repository (query). */ + repository?: string | null; + /** @description The repository of the new hold. */ + holdRepository?: string | null; + /** @description The artifact name of the new hold. */ + holdName?: string | null; + /** @description The version of the new hold; empty for every version. */ + holdVersion?: string | null; + /** @description Why (a case number, a ticket). */ + reason?: string | null; + /** @description The holds. */ + holds?: components["schemas"]["RetentionHoldView"][]; + /** @description The repositories a hold can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description A legal hold with its repository's name. */ + RetentionHoldView: { + /** Format: int32 */ + key: number; + /** Format: int32 */ + repositoryKey: number; + repository: string; + name: string; + version: string; + reason: string | null; + createdBy: string | null; + /** Format: date-time */ + created: string; + }; + /** @enum {string} */ + RetentionJobState: "Running" | "Succeeded" | "Failed"; + /** @description The last run of a policy since the server started (in memory). */ + RetentionJobStatus: { + /** Format: int32 */ + policyKey?: number; + dryRun?: boolean; + state?: components["schemas"]["RetentionJobState"]; + /** @description The administrator, or `scheduler`. */ + actor?: string | null; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + report?: (null) | components["schemas"]["RetentionReport"]; + /** @description Why the run failed as a whole, or null. */ + error?: string | null; + }; + /** + * @description What happened (or, in a dry run, would happen) to one selected version. + * @enum {string} + */ + RetentionOutcome: "Planned" | "Deleted" | "Held" | "Failed"; + /** + * @description A retention policy: which stored versions of one repository (or of every repository of a project) are deleted, and when. + * A version is deleted when any enabled rule selects it and no RetentionHold covers it. Not repository-scoped: + * the administrator lists policies across repositories. `RepositoryKey` and `ProjectKey` are optional Restrict foreign keys; + * deleting a repository or a project deletes its policies first. + */ + RetentionPolicy: { + /** Format: int32 */ + key?: number; + /** @description Unique, AccessNames rules. */ + name?: string | null; + /** + * Format: int32 + * @description The int Repository.Key the policy applies to, or null when it applies to a project. + */ + repositoryKey?: number | null; + /** + * Format: int32 + * @description The int Project.Key: the policy applies to every repository of the project. Exactly one of the two keys is set. + */ + projectKey?: number | null; + /** @description A disabled policy is never run by the schedule and refuses a manual run (a dry run still reports). */ + enabled?: boolean; + /** + * @description Globs (AccessPatterns, one per line) naming the artifacts the policy looks at (package ids, npm names, Maven + * `group:artifact`, image names); empty means every artifact. + */ + namePatterns?: string | null; + /** + * Format: int32 + * @description Keep this many newest versions of each artifact (by publish time); older ones are selected. Null: rule off. + */ + keepLast?: number | null; + /** + * Format: int32 + * @description Select versions published more than this many days ago. Null: rule off. + */ + olderThanDays?: number | null; + /** + * Format: int32 + * @description Select versions not downloaded for this many days (the publish time counts when never downloaded). Null: rule off. + */ + unusedDays?: number | null; + /** @description The age and count rules look at prerelease versions (NuGet pre-release, npm prerelease, Maven snapshot) only. */ + prereleaseOnly?: boolean; + /** + * Format: int64 + * @description Remote repositories only: when what the repository cached is larger than this many bytes, the least recently used versions are + * selected until it fits. Null: rule off. + */ + cacheLimitBytes?: number | null; + /** + * Format: int32 + * @description Docker only: select manifests no tag, index or referrer relationship points at that were pushed more than this many days ago. + * Null: rule off. + */ + untaggedAfterDays?: number | null; + /** @description Docker only: run the garbage collection (IOciGarbageCollector) after the rules, to free the blobs. */ + collectGarbage?: boolean; + /** + * Format: int32 + * @description Run every this many hours (a real run, by the background worker). Null: only when an administrator starts it. + */ + scheduleHours?: number | null; + /** + * Format: date-time + * @description When the schedule was set or the policy enabled; the first scheduled run is due this long after it. + */ + scheduleStart?: string | null; + /** + * Format: date-time + * @description When the last real run started (the schedule counts from the later of this and DateTime? RetentionPolicy.ScheduleStart). + */ + lastRun?: string | null; + /** @description One line about the last real run. */ + lastResult?: string | null; + /** Format: date-time */ + created?: string; + /** + * Format: date-time + * @description Since when the unused rule has been watching the policy's scope (set when the rule is enabled or changed, or the repository, + * project or name patterns change; null on rows that predate it, which fall back to DateTime RetentionPolicy.Created). A version never + * downloaded counts as unused from the later of its publication and this time: downloads are recorded only while watched. + */ + unusedSince?: string | null; + /** Format: date-time */ + modified?: string; + }; + /** @description Creating or saving a retention policy, or any write of it that asks the password. */ + RetentionPolicyBody: { + form: (null) | components["schemas"]["RetentionPolicyForm"]; + /** @description The administrator's password. */ + password: string | null; + }; + /** + * @description What the policy form posts (`Form.*`): the rules of a RetentionPolicy in the units a person types + * (the cache limit in MiB). RetentionPolicyInput RetentionPolicyForm.ToInput(int key) turns it into the administration's input. + */ + RetentionPolicyForm: { + name?: string | null; + /** @description `repository` or `project`. */ + scopeKind?: string | null; + /** @description The repository or project name. */ + scopeName?: string | null; + enabled?: boolean; + namePatterns?: string | null; + /** Format: int32 */ + keepLast?: number | null; + /** Format: int32 */ + olderThanDays?: number | null; + /** Format: int32 */ + unusedDays?: number | null; + prereleaseOnly?: boolean; + /** + * Format: int64 + * @description The remote cache limit in MiB. + */ + cacheLimitMb?: number | null; + /** Format: int32 */ + untaggedAfterDays?: number | null; + collectGarbage?: boolean; + /** Format: int32 */ + scheduleHours?: number | null; + }; + /** @description A policy with the name of what it applies to. */ + RetentionPolicyView: { + policy: components["schemas"]["RetentionPolicy"]; + /** @description The repository name, when it applies to one. */ + repository: string | null; + /** @description The project name, when it applies to a project. */ + project: string | null; + /** + * Format: int32 + * @description How many repositories it currently applies to. + */ + targets: number; + }; + /** @description What one retention policy's screen (`/admin/retention/{key}`) shows. */ + RetentionPolicyViewModel: { + /** + * Format: int32 + * @description The policy's key (route). + */ + key?: number; + form?: components["schemas"]["RetentionPolicyForm"]; + view?: (null) | components["schemas"]["RetentionPolicyView"]; + status?: (null) | components["schemas"]["RetentionJobStatus"]; + /** @description Whether a run is in progress (the page refreshes itself). */ + running?: boolean; + /** @description The repositories a policy can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + /** @description The names of the projects a policy can name. */ + projectNames?: string[]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The result of running (or dry-running) a policy over its repositories. */ + RetentionReport: { + /** Format: int32 */ + policyKey?: number; + policyName?: string; + /** @description Whether nothing was changed. */ + dryRun?: boolean; + /** Format: date-time */ + started?: string; + /** Format: date-time */ + finished?: string | null; + repositories?: components["schemas"]["RetentionRepositoryReport"][] | null; + /** Format: int32 */ + selected?: number; + /** Format: int32 */ + deleted?: number; + /** Format: int32 */ + held?: number; + /** Format: int32 */ + failed?: number; + /** Format: int64 */ + bytes?: number; + /** @description One line for the policy page, the job status and the audit log. */ + summary?: string | null; + }; + /** @description One version in a report. */ + RetentionReportItem: { + repository: string; + name: string; + version: string; + /** Format: date-time */ + published: string; + /** Format: date-time */ + lastDownloaded: string | null; + /** Format: int64 */ + size: number | null; + rules: string; + outcome: components["schemas"]["RetentionOutcome"]; + error: string | null; + }; + /** @description The part of a RetentionReport that concerns one repository. */ + RetentionRepositoryReport: { + repository?: string; + format?: components["schemas"]["RepositoryFormat"]; + /** + * Format: int32 + * @description Versions looked at (matching the policy's name patterns). + */ + examined?: number; + /** + * Format: int32 + * @description Versions selected by a rule and not held (dry run: to be deleted). + */ + selected?: number; + /** + * Format: int32 + * @description Versions deleted (always 0 in a dry run). + */ + deleted?: number; + /** + * Format: int32 + * @description Versions a rule selected that a legal hold kept. + */ + held?: number; + /** + * Format: int32 + * @description Versions whose deletion failed. + */ + failed?: number; + /** + * Format: int64 + * @description Bytes of the deleted versions (dry run: of the selected ones), as far as known. + */ + bytes?: number; + items?: components["schemas"]["RetentionReportItem"][] | null; + itemsTruncated?: boolean; + /** @description Rules that did not apply, and similar remarks. */ + notes?: string[] | null; + garbageCollection?: (null) | components["schemas"]["OciGcReport"]; + /** @description Why the repository could not be processed, or null. */ + error?: string | null; + }; + /** @description What the retention policies screen (`/admin/retention`) shows: every policy and the form that creates one. */ + RetentionViewModel: { + form?: components["schemas"]["RetentionPolicyForm"]; + /** @description Every policy. */ + policies?: components["schemas"]["RetentionPolicyView"][]; + /** @description The repositories a policy can name. */ + repositories?: components["schemas"]["RepositoryInfo"][]; + /** @description The names of the projects a policy can name. */ + projectNames?: string[]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description The body of the scan twin's POST: the artifact and version to scan, and where the link back goes. */ + ScanArtifactForm: { + /** @description The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image). */ + name?: string | null; + /** @description The version (Docker: the manifest digest). */ + version?: string | null; + /** @description Where the link back goes (a local address only). */ + returnUrl?: string | null; + }; + /** @description Whether the repository of the request can be scanned now, and by what. */ + ScanEngineStatus: { + /** @description Whether a scan can run. */ + available: boolean; + /** @description What scans the repository's artifacts (`OSV.dev`, `OSV offline copy`, `Trivy`), or null. */ + engine: string | null; + /** @description Why it cannot, or null. Safe to show. */ + reason: string | null; + }; + /** @description One vulnerability a scan found in an artifact or one of its components. */ + ScanFinding: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The int ScanResult.Key. Required; deleting the result deletes its findings. + */ + resultKey?: number; + /** @description The advisory id (`GHSA-…`, `CVE-…`), as the source names it. */ + vulnerabilityId?: string | null; + /** @description The component that is vulnerable: the artifact itself or one of its dependencies (package, OS package…). */ + component?: string | null; + /** @description The version of string? ScanFinding.Component. */ + componentVersion?: string | null; + /** + * Format: int32 + * @description 0 low, 1 moderate, 2 high, 3 critical (the numbering of NuGet's vulnerability resource). + */ + severity?: number; + /** @description A one-line description from the source, or null. */ + summary?: string | null; + /** @description Where the advisory is described (an absolute http(s) URL). */ + advisoryUrl?: string | null; + /** @description The first version that fixes it, when the source says. */ + fixedVersion?: string | null; + }; + /** @description One project of the scanning overview. */ + ScanningProjectRow: { + project: components["schemas"]["ProjectSummary"]; + /** @description Whether it has a scanning policy of its own. */ + hasPolicy: boolean; + }; + /** @description One repository of the scanning overview. */ + ScanningRepositoryRow: { + repository: components["schemas"]["RepositoryInfo"]; + summary: components["schemas"]["ScanSummary"]; + policy: components["schemas"]["EffectiveScanPolicy"]; + }; + /** @description The scanning options the overview shows. */ + ScanningSettingsView: { + /** @description Whether artifacts are scanned. */ + enabled: boolean; + /** @description Whether a stored version is queued for a scan at once. */ + scanOnDeploy: boolean; + /** @description The OSV API root. */ + osvUrl: string; + /** @description The offline copy of the OSV data, or null. */ + osvOfflinePath: string | null; + /** @description The age after which an artifact is scanned again (zero or negative: never). */ + rescanInterval: string; + }; + /** @description What the vulnerability scanning overview (`/admin/scanning`) shows. */ + ScanningViewModel: { + settings?: components["schemas"]["ScanningSettingsView"]; + /** @description Whether Trivy is configured (container images are scanned). */ + trivyConfigured?: boolean; + /** @description The repositories that can hold artifacts (virtual ones hold none). */ + repositories?: components["schemas"]["ScanningRepositoryRow"][]; + /** @description The projects. */ + projects?: components["schemas"]["ScanningProjectRow"][]; + }; + /** + * @description What a repository (or a project's repositories) does about findings: a threshold severity per action, or none (null) for + * the action. A repository's own policy wins over its project's. Exactly one of int? ScanPolicy.RepositoryKey and + * int? ScanPolicy.ProjectKey is set. + */ + ScanPolicy: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The repository this policy is for, or null for a project policy. + */ + repositoryKey?: number | null; + /** + * Format: int32 + * @description The project this policy is for, or null for a repository policy. + */ + projectKey?: number | null; + /** + * Format: int32 + * @description Findings at or above this severity (0..3) are shown as a warning. Null: no warning. + */ + warnSeverity?: number | null; + /** + * Format: int32 + * @description A version with a finding at or above this severity cannot be downloaded (403 with the reason). Null: never. + */ + blockDownloadSeverity?: number | null; + /** + * Format: int32 + * @description A deploy whose artifact or declared dependencies have a finding at or above this severity is refused (403). Null: never. + */ + blockDeploySeverity?: number | null; + /** @description Whether a version that has not been scanned (yet, or at all) cannot be downloaded. */ + blockUnscanned?: boolean; + /** + * Format: date-time + * @description When the policy was last saved (UTC). + */ + modified?: string; + /** @description The administrator who saved it, or null. */ + modifiedBy?: string | null; + }; + /** @description Saving the scanning policy of a repository or project (empty values remove it). */ + ScanPolicyBody: { + /** @description Warn from this severity (0 to 3, or empty). */ + warn: string | null; + /** @description Refuse downloads from this severity. */ + blockDownload: string | null; + /** @description Refuse deploys from this severity. */ + blockDeploy: string | null; + /** @description Refuse downloads of versions that were not scanned. */ + blockUnscanned: boolean; + /** @description The administrator's password. */ + password: string | null; + }; + /** @enum {string} */ + ScanPolicyScope: "Repository" | "Project"; + /** @description The thresholds of a policy; null disables the action. */ + ScanPolicyValues: { + /** + * Format: int32 + * @description Show a warning from this severity (0 low … 3 critical). + */ + warnSeverity: number | null; + /** + * Format: int32 + * @description Refuse downloads from this severity. + */ + blockDownloadSeverity: number | null; + /** + * Format: int32 + * @description Refuse deploys from this severity. + */ + blockDeploySeverity: number | null; + /** @description Refuse downloads of versions that were not scanned. */ + blockUnscanned: boolean; + /** @description Whether nothing is enabled. */ + isEmpty?: boolean; + }; + /** @description What the scanning policy of a project (`/admin/scanning/projects/{name}`) shows. */ + ScanProjectViewModel: { + /** @description The project's name (route). */ + name?: string | null; + project?: (null) | components["schemas"]["ProjectDetails"]; + own?: (null) | components["schemas"]["ScanPolicy"]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the scanning dashboard of one repository (`/admin/scanning/{name}`) shows. */ + ScanRepositoryViewModel: { + /** @description The repository's name (route). */ + name?: string | null; + /** + * Format: int32 + * @description The lowest severity listed (0 low ... 3 critical). + */ + minSeverity?: number; + /** + * Format: int32 + * @description The page of the list, from 1. + */ + pageNumber?: number; + repository?: (null) | components["schemas"]["RepositoryInfo"]; + summary?: (null) | components["schemas"]["ScanSummary"]; + effective?: components["schemas"]["EffectiveScanPolicy"]; + own?: (null) | components["schemas"]["ScanPolicy"]; + /** @description The versions with findings on this page. */ + findings?: components["schemas"]["ScanResult"][]; + /** @description Whether there is another page. */ + hasMore?: boolean; + job?: (null) | components["schemas"]["AdminJobStatus"]; + /** @description The package screen of each finding's version (by int ScanResult.Key), when its format has one. */ + packageLinks?: { + [key: string]: components["schemas"]["ScreenLink"]; + }; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** + * @description What the last scans of one artifact version found, in one repository (table `ScanResults`). The artifact is named the way + * its format names it: NuGet package id (as stored), npm package name, Maven `group:artifact`, Docker image name; the + * version is the package version, npm version, Maven version or the Docker manifest digest. A row exists once a scan was + * attempted; there is no foreign key to the artifact (it may be deleted, and each format keeps its own tables), so stale rows are + * dropped by the next sweep. + */ + ScanResult: { + /** Format: int32 */ + key?: number; + /** + * Format: int32 + * @description The owning repository; see IRepositoryScoped. + */ + repositoryKey?: number; + /** @description The artifact name (see the class remarks). At most `ScanLimits.NameLength` characters. */ + name?: string | null; + /** @description The artifact version. At most `ScanLimits.VersionLength` characters. */ + version?: string | null; + /** @description The scanner that produced the findings: `osv` or `trivy`. */ + scanner?: string | null; + /** + * Format: date-time + * @description When the last scan succeeded (UTC); null when none ever did (the artifact counts as unscanned). + */ + scannedAt?: string | null; + /** + * Format: date-time + * @description When a scan was last attempted (UTC). + */ + attempted?: string; + /** @description The scrubbed reason the last attempt failed, or null. The findings of the last success stay while this is set. */ + error?: string | null; + /** + * Format: int32 + * @description The highest severity among List<ScanFinding>? ScanResult.Findings (0 low … 3 critical), or -1 when there are none. + */ + highest?: number; + /** + * Format: int32 + * @description How many findings the last success recorded. + */ + findingCount?: number; + findings?: components["schemas"]["ScanFinding"][] | null; + }; + /** @description The repository dashboard numbers. */ + ScanSummary: { + engine: components["schemas"]["ScanEngineStatus"]; + /** + * Format: int32 + * @description Artifacts stored in the repository. + */ + artifacts: number; + /** + * Format: int32 + * @description Artifacts with no successful scan. + */ + unscanned: number; + /** + * Format: int32 + * @description Of those, the ones whose last attempt failed. + */ + failed: number; + /** + * Format: int32 + * @description Artifacts scanned without findings. + */ + clean: number; + /** @description Artifacts by their highest finding: index 0 low … 3 critical. */ + bySeverity: number[]; + }; + /** @description What the Scan now screen (`/scan-artifact`) shows; filled by the screen's workflow. */ + ScanViewModel: { + /** @description The artifact name (NuGet id, npm name, Maven `group:artifact`, Docker image). */ + name?: string | null; + /** @description The version (Docker: the manifest digest). */ + version?: string | null; + /** @description Where the link back goes: the package page the user came from (a local address only). */ + returnUrl?: string | null; + /** @description What happened, for the screen to show. */ + message?: string | null; + /** @description Whether string? ScanViewModel.Message reports a refusal. */ + failed?: boolean; + result?: (null) | components["schemas"]["ScanResult"]; + engine?: (null) | components["schemas"]["ScanEngineStatus"]; + /** @description The address the link back leads to (the return address when it is local, else the home page). */ + backUrl?: string; + }; + /** @description A screen as a client links to it: the screen (controller and action) and its route values; the view turns it into an address. */ + ScreenLink: { + screen: components["schemas"]["ScreenRef"]; + /** @description Route values; a null value (`repo` of the default repository) is kept. */ + routeValues: Record; + }; + /** @description Where a finished action leads: the screen (controller and action, see ScreenCatalog), its route values and the message to show there. */ + ScreenNext: { + screen: (null) | components["schemas"]["ScreenRef"]; + /** @description Route and query values of the next screen (`repo`, `name`, `handler`). */ + routeValues?: Record | null; + /** @description The outcome to show on the next screen (a flash message). */ + message?: string | null; + /** @description The refusal to show on the next screen (a flash error). */ + error?: string | null; + /** + * @description Instead of a screen: a local address to continue at (`/packages`, or `~/` for the site root, which the view prefixes with the path + * base). Always safe to follow: a use case only puts a validated local address here (LocalUrls). + */ + localUrl?: string | null; + /** @description The URL fragment (`#id`) to leave the next screen at, or null. */ + fragment?: string | null; + }; + /** + * @description A screen of the web UI: the MVC controller (without the `Controller` suffix, as `asp-controller` writes it) and the action that + * answers a plain `GET` for it (`AdminUsers` / `Index`). The Application projects have no MVC reference, so the UI project + * turns it into a link. ScreenCatalog lists every screen. + */ + ScreenRef: { + /** @description The controller name without the `Controller` suffix (`AdminUsers`). */ + controller: string; + /** @description The action that shows the screen (`Index`). */ + action: string; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAbuseViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AbuseViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAccessUnavailableViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AccessUnavailableViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAccountAccessViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AccountAccessViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAccountPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AccountPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAdminOrganizationsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AdminOrganizationsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAdminPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AdminPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAdminSettingsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AdminSettingsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAntiforgeryTokenModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AntiforgeryTokenModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfApiCatalogViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ApiCatalogViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfApiKeysViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ApiKeysViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfAuditViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["AuditViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfClusterViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ClusterViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfConfirmEmailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ConfirmEmailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfContactOwnersViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ContactOwnersViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDatabaseCopyStatusView: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DatabaseCopyStatusView"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDeleteUserViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DeleteUserViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDockerImagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DockerImagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDockerImageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DockerImageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfDockerManageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["DockerManageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfEmptyScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["EmptyScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfForgotPasswordViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ForgotPasswordViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfFormatsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["FormatsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfGroupDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["GroupDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfGroupsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["GroupsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfIndexScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["IndexScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfLegalScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["LegalScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfLoginViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["LoginViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenArtifactsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenArtifactsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenArtifactViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenArtifactViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenManageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenManageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfMavenUploadViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["MavenUploadViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmManageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmManageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmPackageViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmPackageViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfNpmUploadViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["NpmUploadViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfOperationsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["OperationsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfOrganizationDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["OrganizationDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfOrganizationsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["OrganizationsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPackageManageScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PackageManageScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPackageScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PackageScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPermissionDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PermissionDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfPermissionsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["PermissionsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfProfileViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ProfileViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfProjectDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ProjectDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfProjectsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ProjectsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReauthenticateViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReauthenticateViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRecoveryCodeLoginViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RecoveryCodeLoginViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRegisterViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RegisterViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReplicationConfigViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReplicationConfigViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReplicationViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReplicationViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfReportAbuseScreen: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ReportAbuseScreen"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRepositoriesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RepositoriesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRepositoryDeleteViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RepositoryDeleteViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRepositoryEditViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RepositoryEditViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfResetPasswordViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ResetPasswordViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRetentionHoldsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RetentionHoldsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRetentionPolicyViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RetentionPolicyViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfRetentionViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["RetentionViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanningViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanningViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanProjectViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanProjectViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanRepositoryViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanRepositoryViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfScanViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ScanViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfSessionModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["SessionModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfSessionProvidersModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["SessionProvidersModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfSettingsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["SettingsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfStatisticsViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["StatisticsViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfTwoFactorLoginViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["TwoFactorLoginViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfTwoFactorViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["TwoFactorViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUploadViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UploadViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUserDetailViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UserDetailViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUserPackagesViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UserPackagesViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfUsersViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["UsersViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfValidationStatusViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ValidationStatusViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is + * (`status`, `model`, `errors`, `next`); the view controllers turn it into a view, an error status or a redirect. + * A use case holds the rules and never sees `HttpContext`, `ModelState` or `TempData`. + */ + ScreenResultOfValidationViewModel: { + status?: components["schemas"]["ScreenStatus"]; + model?: components["schemas"]["ValidationViewModel"]; + errors?: { + [key: string]: string[]; + } | null; + next?: components["schemas"]["ScreenNext"]; + /** Format: int32 */ + statusCode?: number | null; + }; + /** + * @description What a use case decided about a screen. + * @enum {string} + */ + ScreenStatus: "Ok" | "Invalid" | "NotFound" | "Forbidden" | "SignIn" | "Next"; + /** + * @description A package that matched a search query. + * + * See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + */ + SearchResult: { + /** @description The ID of the matched package. */ + id?: string | null; + /** + * @description The latest version of the matched pacakge. This is the full NuGet version after normalization, + * including any SemVer 2.0.0 build metadata. + */ + version?: string | null; + /** @description The description of the matched package. */ + description?: string | null; + /** @description The authors of the matched package. */ + authors?: string[] | null; + /** @description The URL of the matched package's icon. */ + iconUrl?: string | null; + /** @description The URL of the matched package's license. */ + licenseUrl?: string | null; + /** @description The package types defined by the package author. */ + packageTypes?: components["schemas"]["SearchResultPackageType"][] | null; + /** @description The URL of the matched package's homepage. */ + projectUrl?: string | null; + /** @description The URL for the matched package's registration index. */ + registration?: string | null; + /** @description The summary of the matched package. */ + summary?: string | null; + /** @description The tags of the matched package. */ + tags?: string[] | null; + /** @description The title of the matched package. */ + title?: string | null; + /** + * Format: int64 + * @description The total downloads for all versions of the matched package. + */ + totalDownloads?: number; + /** @description The versions of the matched package. */ + versions?: components["schemas"]["SearchResultVersion"][] | null; + deprecation?: (null) | components["schemas"]["PackageDeprecation"]; + /** @description The latest version's known vulnerabilities, or null if it has none. */ + vulnerabilities?: components["schemas"]["PackageVulnerabilityMetadata"][] | null; + /** @description The package's owners, or null if it has none. */ + owners?: string[] | null; + /** @description Whether the package ID is reserved for its owners. Null if it has no owners. */ + verified?: boolean | null; + }; + /** + * @description A single package type from a SearchResult. + * + * See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + */ + SearchResultPackageType: { + /** @description The name of the package type. */ + name?: string | null; + }; + /** + * @description A single version from a SearchResult. + * + * See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + */ + SearchResultVersion: { + /** @description The registration leaf URL for this single version of the matched package. */ + "@id"?: string | null; + /** @description The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata. */ + version?: string | null; + /** + * Format: int64 + * @description The downloads for this single version of the matched package. + */ + downloads?: number; + }; + /** + * @description How the web UI orders search results. The V3 search API has no sort parameter, so + * it always uses SearchSort.Relevance. + * @enum {string} + */ + SearchSort: "Relevance" | "TotalDownloads" | "LastUpdated"; + /** @enum {string} */ + SemVerLevel: "Unknown" | "SemVer2"; + /** + * @description The body of `POST /api/ui/session/cookie` (a same-origin client that signs in with the cookie): the password step (string? SessionCookieForm.UserName, + * string? SessionCookieForm.Password), or, when the account has two-factor, the second step (string? SessionCookieForm.Ticket with string? SessionCookieForm.Code or string? SessionCookieForm.RecoveryCode). + */ + SessionCookieForm: { + /** @description The username (password step). */ + userName?: string | null; + /** @description The password (password step). */ + password?: string | null; + /** @description The `twoFactorTicket` of the password step (second step). */ + ticket?: string | null; + /** @description A code of the authenticator app (second step). */ + code?: string | null; + /** @description A recovery code (second step). */ + recoveryCode?: string | null; + }; + /** @description The body of `POST /api/ui/session/exchange`. */ + SessionExchangeForm: { + /** @description The `exchange_token` of the external sign-in's redirect. */ + exchangeToken: string | null; + }; + /** @description What `/api/ui/session` answers: a pair of tokens, or the ticket for the second factor of a sign-in. */ + SessionModel: { + /** @description Authenticates requests to `/api/ui` (`Authorization: Bearer`); null while bool SessionModel.TwoFactorRequired. */ + accessToken?: string | null; + /** + * Format: date-time + * @description When the access token stops being accepted (UTC). + */ + expiresAt?: string | null; + /** @description Exchanged for a new pair at `/api/ui/session/refresh`; each refresh returns a new one and the old one stays valid until it expires. */ + refreshToken?: string | null; + /** + * Format: date-time + * @description When the refresh token stops being accepted (UTC). + */ + refreshExpiresAt?: string | null; + /** @description The signed-in user's name. */ + userName?: string | null; + /** @description The password was right but the account asks for a second factor: post the string? SessionModel.TwoFactorTicket and a code to `/api/ui/session/two-factor` or `/recovery-code`. */ + twoFactorRequired?: boolean; + /** @description Proves the password step; valid for five minutes, and useless without a code. */ + twoFactorTicket?: string | null; + /** + * Format: date-time + * @description When the ticket stops being accepted (UTC). + */ + twoFactorTicketExpiresAt?: string | null; + /** @description External sign-in only: a single-use-in-practice token (60 seconds) to exchange for the real ones at `POST /api/ui/session/exchange`. */ + exchangeToken?: string | null; + /** + * Format: date-time + * @description When the exchange token stops being accepted (UTC). + */ + exchangeExpiresAt?: string | null; + /** @description Something to tell the user when there are no tokens yet (external sign-in: the account was created and awaits approval or a confirmed email address). */ + notice?: string | null; + }; + /** @description The external sign-in providers a client can offer (`GET /api/ui/session/providers`): one button each, started at `/api/ui/session/external/{id}`. */ + SessionProvidersModel: { + /** @description The configured providers, empty when there is none. */ + providers?: components["schemas"]["ExternalProviderInfo"][]; + }; + /** @description The body of `POST /api/ui/session/recovery-code`: the ticket of the password step and one of the account's recovery codes (each works once). */ + SessionRecoveryCodeForm: { + /** @description The `twoFactorTicket` the password step answered. */ + ticket: string | null; + /** @description A recovery code. */ + recoveryCode: string | null; + }; + /** @description The body of `POST /api/ui/session/refresh`. */ + SessionRefreshForm: { + /** @description The `refreshToken` of the last answer. */ + refreshToken: string | null; + }; + /** @description The body of `POST /api/ui/session`: the same credentials as the sign-in page. */ + SessionSignInForm: { + /** @description The user name. */ + userName: string | null; + /** @description The password. */ + password: string | null; + }; + /** @description The body of `POST /api/ui/session/sign-out`. */ + SessionSignOutForm: { + /** @description The refresh token to end the session with when the request carries no access token. */ + refreshToken?: string | null; + /** + * @description Also ends every other session of the account (cookie sessions and tokens) by changing its security stamp. Without it nothing is + * revoked: the tokens are stateless, so the client simply forgets them, and they expire. + */ + everywhere?: boolean; + }; + /** @description The body of `POST /api/ui/session/two-factor`: the ticket of the password step and a code of the authenticator app. */ + SessionTwoFactorForm: { + /** @description The `twoFactorTicket` the password step answered. */ + ticket: string | null; + /** @description The code from the authenticator app. */ + code: string | null; + }; + /** @description One configuration key the Settings page can show. */ + SettingDescriptor: { + /** @description The full key, such as "Email:Smtp:Host". */ + key: string; + /** @description The first segment of the key, or an empty string for a top-level key. */ + section: string; + /** @description The options type's name without "Options", such as "AzureBlobStorage". */ + group: string; + kind: components["schemas"]["SettingKind"]; + /** @description The allowed names of an SettingKind.Enum, otherwise empty. */ + enumValues: string[]; + /** @description The value is a credential: masked and write-only. */ + isSensitive: boolean; + /** @description A change applies after a restart. */ + requiresRestart: boolean; + /** @description The property's XML documentation summary, or an empty string. */ + description: string; + /** + * @description The full key of the setting that selects Examples (see + * SettingExampleAttribute), or null. + */ + exampleDependsOnKey?: string | null; + /** @description Example values by the value of ExampleDependsOnKey (case-insensitive), or null. */ + examples?: { + [key: string]: string; + } | null; + }; + /** + * @description The editable type of a setting. + * @enum {string} + */ + SettingKind: "Boolean" | "Integer" | "Number" | "String" | "Enum" | "TimeSpan" | "StringList" | "ReadOnly"; + /** @description One section of the settings screen: its key (empty for the top-level keys), its DOM id and its settings. */ + SettingsSection: { + /** @description The section's key; empty for the settings that sit at the top level. */ + key: string; + /** @description The stable DOM id (string AdminSettingsViewModel.SectionId(string key)). */ + id: string; + /** @description The settings of the section; a sensitive one never carries its value. */ + settings: components["schemas"]["SettingState"][]; + }; + /** + * @description The fields of a submitted Settings form, per setting key (`v:<key>` the value, `reset:<key>`, `clear:<key>`; a checkbox posts + * `true` next to a hidden `false`, a list is one entry per line) and the section they belong to. The same shape whether it comes from the + * page's form or from a JSON body. + */ + SettingsSubmission: { + /** @description The section being saved (the empty section holds the top-level keys). */ + section: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + /** @description The posted fields; a field may repeat. */ + fields: { + [key: string]: string[]; + }; + }; + /** @description A setting as the Settings page shows it. */ + SettingState: { + descriptor: components["schemas"]["SettingDescriptor"]; + /** + * @description The value in effect, as text (a list one entry per line). Always null for a sensitive + * setting: only HasValue says whether one is set. + */ + effectiveValue: string | null; + /** @description The setting has a non-empty value. */ + hasValue: boolean; + /** @description The setting is saved in the overrides file. */ + isOverridden: boolean; + /** + * @description What overrides the saved value ("environment variable", "command line", ...), or null. + * While set, a saved value has no effect. + */ + shadowedBy: string | null; + /** @description A restart-only setting whose value changed since startup. */ + pendingRestart: boolean; + }; + /** @description What the account settings screen shows (change email, change password, delete the account). */ + SettingsViewModel: { + /** @description The account's email address. */ + email?: string | null; + /** @description Whether the address is confirmed. */ + emailConfirmed?: boolean; + /** @description Whether the account has a password (else it signs in through a provider). */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is configured to sign in again with. */ + canReauthenticate?: boolean; + /** @description Whether mail is configured. */ + canSendEmail?: boolean; + /** @description Every configured external provider with whether this account has linked a login at it (empty when there is none). */ + externalLogins?: components["schemas"]["ExternalLoginStatus"][]; + /** @description The success message to show. */ + message?: string | null; + /** @description The refusal to show. */ + error?: string | null; + blockers?: (null) | components["schemas"]["DeletionBlockers"]; + }; + /** + * @description What the "Sign-in providers" panel of the Settings screen posts to add or edit a named OpenID Connect provider (the body of + * `POST /api/ui/admin/settings/save-provider`). The id is the key and cannot change once created; a blank secret keeps the saved one. + * string? SignInProviderForm.Parameters and string? SignInProviderForm.GroupMappings are one `name=value` per line. + */ + SignInProviderForm: { + /** @description The provider id (lower-case letters, digits and `-`, 1 to 32). */ + id?: string | null; + /** @description The name on the sign-in button. */ + displayName?: string | null; + /** @description The issuer address. */ + authority?: string | null; + /** @description The client id. */ + clientId?: string | null; + /** @description The client secret; blank keeps the saved one. Never sent back. */ + clientSecret?: string | null; + /** @description Extra scopes, separated by spaces or semicolons. */ + scopes?: string | null; + /** @description Extra authorization request parameters, one `name=value` per line. */ + parameters?: string | null; + /** @description The claim holding the user name. */ + userNameClaim?: string | null; + /** @description The claim holding the email address. */ + emailClaim?: string | null; + /** @description The claim saying the address is verified. */ + emailVerifiedClaim?: string | null; + /** @description The claim that decides the administrator flag (the provider becomes authoritative for it). */ + administratorClaim?: string | null; + /** @description The value of that claim that makes a user an administrator. */ + administratorValue?: string | null; + /** @description The claim holding the user's groups. */ + groupClaim?: string | null; + /** @description Claim value to BaGet group, one `value=group` per line. */ + groupMappings?: string | null; + /** @description The administrator's password, asked again. */ + password?: string | null; + }; + /** @description A named OpenID Connect provider as the Settings screen lists it. The client secret is never carried, only whether one is set. */ + SignInProviderView: { + /** @description The provider id. */ + id?: string; + /** @description The name on the sign-in button. */ + displayName?: string | null; + /** @description The issuer address. */ + authority?: string | null; + /** @description The client id. */ + clientId?: string | null; + /** @description Whether a client secret is set. */ + hasSecret?: boolean; + /** @description Extra scopes. */ + scopes?: string | null; + /** @description Extra request parameters, one `name=value` per line. */ + parameters?: string | null; + /** @description The claim holding the user name. */ + userNameClaim?: string | null; + /** @description The claim holding the email address. */ + emailClaim?: string | null; + /** @description The claim saying the address is verified. */ + emailVerifiedClaim?: string | null; + /** @description The claim that decides the administrator flag. */ + administratorClaim?: string | null; + /** @description The value of that claim that makes a user an administrator. */ + administratorValue?: string | null; + /** @description The claim holding the user's groups. */ + groupClaim?: string | null; + /** @description Claim value to BaGet group, one `value=group` per line. */ + groupMappings?: string | null; + /** @description Whether the overrides file holds it, so this screen can edit or remove it; false when a configuration file or the environment sets it. */ + editable?: boolean; + /** @description Whether the running server has a handler for it (false: saved or removed since startup). */ + active?: boolean; + /** @description Whether what is saved differs from what the running server uses, so a restart is needed. */ + pendingRestart?: boolean; + }; + /** @description A package ID in one repository that only one user owns. */ + SoleOwnedPackage: { + /** + * Format: int32 + * @description The repository's key. + */ + repositoryKey: number; + /** @description The repository's name (string Repository.DefaultName for the default). */ + repositoryName: string; + /** @description The package ID. */ + packageId: string | null; + format?: components["schemas"]["RepositoryFormat"]; + /** @description The ID for the default repository, `ID (name)` for any other, for messages that mix repositories. */ + label?: string | null; + }; + /** @description What the statistics page shows. */ + StatisticsViewModel: { + statistics: (null) | components["schemas"]["FeedStatistics"]; + }; + /** Format: binary */ + Stream: string | null; + /** @description A decision on a stuck submission of the validation queue. */ + SubmissionForm: { + /** @description The submission. */ + submissionId: string | null; + /** @description The administrator's password (asked to release or reject). */ + password: string | null; + }; + /** @description A permission target with its grants. */ + TargetDetails: { + target: components["schemas"]["TargetSummary"]; + grants: components["schemas"]["GrantInfo"][]; + }; + TargetFramework: { + /** Format: int32 */ + key?: number; + moniker?: string | null; + package?: (null) | components["schemas"]["Package"]; + }; + /** @description A permission target as the admin pages list it. */ + TargetSummary: { + /** Format: int32 */ + key: number; + name: string; + repositoryPatterns: string[]; + includePatterns: string[]; + excludePatterns: string[]; + /** Format: int32 */ + projectKey: number | null; + projectName: string | null; + isBuiltIn: boolean; + /** Format: int32 */ + grantCount: number; + }; + /** @description One signal's state. string? TelemetrySignalReport.LastError is already scrubbed (no headers, credentials or URL paths). */ + TelemetrySignalReport: { + signal: string; + state: components["schemas"]["TelemetrySignalState"]; + /** Format: date-time */ + lastSuccess: string | null; + /** Format: date-time */ + failingSince: string | null; + lastError: string | null; + /** Format: int64 */ + dropped: number; + }; + /** + * @description What one telemetry signal is doing, as the Settings page shows it. + * @enum {string} + */ + TelemetrySignalState: "Off" | "NotConfigured" | "Waiting" | "Ok" | "Failing"; + /** @description The outcome of a connection test; string TelemetryTestOutcome.Message and string? TelemetryTestOutcome.Target are scrubbed. */ + TelemetryTestOutcome: { + /** @description The collector accepted a test span. */ + ok: boolean; + /** @description What happened. */ + message: string; + /** @description The endpoint that was tested, cut to scheme, host and port. */ + target: string | null; + }; + /** @description What the "turn two-factor authentication on" form posts. */ + TwoFactorCodeForm: { + /** @description The password, asked again. Needed over `/api/ui` (a session token or the cookie with an antiforgery header); the screen's form does not post it. */ + password?: string | null; + /** @description The code from the authenticator app. */ + code?: string | null; + }; + /** @description What the authenticator-code form posts. */ + TwoFactorLoginForm: { + /** @description The code from the authenticator app. */ + code: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description The second step of signing in: an authenticator code. A request binds TwoFactorLoginForm, never this type. */ + TwoFactorLoginViewModel: { + /** @description The refusal to show. */ + error?: string | null; + /** @description The code from the authenticator app. */ + code: string | null; + /** @description Whether the session outlives the browser. */ + rememberMe?: boolean; + /** @description Where to go after signing in; only a local URL is followed. */ + returnUrl?: string | null; + }; + /** @description What the two-factor authentication screen shows. */ + TwoFactorViewModel: { + /** @description Whether two-factor authentication is on. */ + twoFactorEnabled?: boolean; + /** @description The key to type into an authenticator that cannot scan the QR code. */ + sharedKey?: string | null; + /** @description The QR code of the setup link, an SVG built from the user's own key. */ + qrCodeSvg?: string | null; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is configured to sign in again with. */ + canReauthenticate?: boolean; + /** + * Format: int32 + * @description How many recovery codes are unused. + */ + recoveryCodesLeft?: number; + /** @description Whether the account has a password (else it signs in through a provider). */ + hasPassword?: boolean; + /** @description The new recovery codes. Shown once, when two-factor authentication is turned on. */ + recoveryCodes?: string[]; + /** @description The refusal to show. */ + error?: string | null; + /** @description The success message to show. */ + message?: string | null; + }; + /** @description What unlinking an external provider posts. */ + UnlinkExternalForm: { + /** @description The id of the provider to unlink. */ + provider?: string | null; + /** @description The password, asked again. */ + password?: string | null; + }; + /** @description What a staged NuGet upload contains, as the preview of the upload page shows it (read from the archive itself). */ + UploadPreview: { + /** @description The handle of the staged file; only the user who staged it can open it. */ + token?: string | null; + /** @description Whether the file is a symbol package (`.snupkg`, by its nuspec's package type). */ + isSymbolPackage?: boolean; + /** @description The package ID, from the nuspec. */ + id?: string | null; + /** @description The normalized version, from the nuspec. */ + version?: string | null; + /** @description The description. */ + description?: string | null; + /** @description The authors. */ + authors?: string[]; + /** @description The license expression or license file the package declares, if any. */ + license?: string | null; + /** @description The license URL, if any. */ + licenseUrl?: string | null; + /** @description The dependencies by target framework. */ + dependencyGroups?: components["schemas"]["DependencyGroupModel"][]; + readme?: (null) | components["schemas"]["HtmlString"]; + /** @description The PDBs of a symbol package. */ + symbolFiles?: string[]; + /** @description Whether the version a symbol package belongs to is on this server. */ + targetPackageExists?: boolean; + /** @description What to tell about a symbol package whose package is missing. */ + targetPackageMessage?: string | null; + }; + /** + * @description What the second and third step of the NuGet upload send (publish and discard a staged upload): the handle of the staged file and, while accounts are + * off, the API key that authenticates the uploader. The key is read and never echoed in an answer. + */ + UploadTokenRequest: { + /** @description The handle of the staged upload (string? UploadPreview.Token). */ + token?: string; + /** @description The API key of the uploader while accounts are off (otherwise the signed-in session or the key of the request authenticates). */ + apiKey?: string | null; + /** @description The confirmation that the uploader may publish the package (required to publish, ignored when discarding). */ + acceptTerms?: boolean; + }; + /** @description What the NuGet upload page (`/upload`) shows: the form, the preview of a staged file, or the outcome of a step. */ + UploadViewModel: { + /** + * @description The package ID a link arrived with, as "upload a new version of this" does. A hint for the page only: the ID and version that + * are published are read from the file, never from the request. + */ + id?: string | null; + /** @description Whether accounts are on (the uploader then signs in). */ + accountsEnabled?: boolean; + /** @description Whether the server is read-only. */ + isReadOnlyMode?: boolean; + /** @description Whether the visitor is signed in. */ + signedIn?: boolean; + /** @description With accounts off there is no user to own an upload, so the pusher proves itself with an API key. */ + needsApiKey?: boolean; + /** @description Nothing on this server can tell one caller from another (accounts off and no global API key): the browser upload is closed. */ + nothingCanAuthenticate?: boolean; + /** @description What the page says in that state, so the explanation and the refusal are one sentence. */ + noApiKeyExplanation?: string | null; + /** @description Whether to render the form at all. */ + canUpload?: boolean; + staged?: (null) | components["schemas"]["UploadPreview"]; + /** @description What happened, for the page to show. */ + message?: string | null; + /** @description Whether string? UploadViewModel.Message reports a failure. */ + failed?: boolean; + published?: (null) | components["schemas"]["UploadPreview"]; + /** @description The token of a staged upload whose API key was rejected, so the key can be entered again. */ + retryToken?: string | null; + /** + * Format: int32 + * @description The HTTP status the page is answered with (200, or the refusal's). + */ + statusCode?: number; + }; + /** @description The account an administrator looks at, without anything that signs in as it (no password hash, security stamp or tokens). */ + UserAccountInfo: { + /** @description The user name. */ + userName: string | null; + /** @description The email address, or null. */ + email: string | null; + /** + * Format: date-time + * @description When the account was created. + */ + created: string; + /** @description Whether it is a server administrator. */ + isAdministrator: boolean; + /** @description Whether it waits for an administrator to enable it. */ + pendingApproval: boolean; + }; + /** @description A change to one account from the Users screen, with the list's filter and page to come back to. */ + UserChange: { + /** @description The account the change applies to. */ + userName: string | null; + /** @description The administrator's password, asked again. */ + password: string | null; + /** @description The list's user-name filter. */ + q?: string | null; + /** + * Format: int32 + * @description The list's page. + * @default 1 + */ + pageNumber: number; + /** @description For a password reset: the address to mail the new password to, if the administrator typed one. */ + resetEmail?: string | null; + }; + /** @description A new account from the Users screen. */ + UserCreation: { + /** @description The new account's name. */ + newUserName: string | null; + /** @description Its address, or null. */ + newEmail: string | null; + /** @description The password typed; empty means generate one (unless Invite). */ + newPassword: string | null; + /** @description Mail the user a link to choose their own password. */ + invite: boolean; + /** @description The administrator's password, asked again. */ + password: string | null; + /** @description The list's user-name filter. */ + q?: string | null; + /** + * Format: int32 + * @description The list's page. + * @default 1 + */ + pageNumber: number; + }; + /** @description Deleting an account. */ + UserDeletionForm: { + /** @description "keep" (default) or "delete": what to do with the package IDs only this user owns. */ + soleOwned: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description What the user detail screen (`/admin/users/{name}`) shows: the account, its keys, organizations and access. */ + UserDetailViewModel: { + /** @description A package ID to evaluate the effective permissions for; empty means each repository as a whole. */ + package?: string | null; + /** @description The user name (route). */ + name?: string | null; + /** @description Whether the configured database has an access model (else the access sections are hidden). */ + modelAvailable?: boolean; + /** @description The names of the groups the account belongs to (the implicit built-ins excluded). */ + groups?: string[]; + /** @description The roles the account holds in projects, directly or through a group. */ + projectRoles?: components["schemas"]["UserProjectRole"][]; + /** @description What the account may do in each NuGet repository, and why. */ + access?: components["schemas"]["RepositoryAccessRow"][]; + account?: (null) | components["schemas"]["UserAccountInfo"]; + /** @description The account's API keys; the key and its hash are never shown. */ + keys?: components["schemas"]["UserKeyRow"][]; + /** @description The organizations the account belongs to. */ + organizations?: components["schemas"]["Organization"][]; + /** + * Format: int32 + * @description How many package IDs the account owns, in every repository. + */ + ownedPackageIds?: number; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description Adding an account to a group or removing it. */ + UserGroupForm: { + /** @description The group's name. */ + group: string | null; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description Revoking one of an account's API keys. */ + UserKeyForm: { + /** + * Format: int32 + * @description The key's number (int UserKeyRow.Key). + */ + key: number; + /** @description The administrator's password. */ + password: string | null; + }; + /** @description One of an account's API keys as the administrator sees it; the key itself and its hash are never shown. */ + UserKeyRow: { + /** + * Format: int32 + * @description The key's number (what revoking names). + */ + key: number; + /** @description The description the owner gave it. */ + description: string | null; + /** @description What it may do. */ + scopes: string[]; + /** @description The package IDs it applies to. */ + packageGlobPattern: string | null; + /** + * Format: date-time + * @description When it was created. + */ + created: string; + /** + * Format: date-time + * @description When it expires, or null. + */ + expires: string | null; + /** @description Where it may be used: the repositories it is limited to, or "all repositories". */ + repositories: string; + }; + /** @description What the user packages screen (`/admin/users/{name}/packages`) shows: the package IDs one user owns. */ + UserPackagesViewModel: { + /** @description The user name, from the route. */ + name?: string | null; + /** @description The user's packages. */ + packages?: components["schemas"]["AdminPackageRow"][]; + }; + /** @description A role a user holds in a project, directly or through a group. */ + UserProjectRole: { + project: string; + role: components["schemas"]["ProjectRole"]; + via: string; + }; + /** @description A user as the Users page lists them. */ + UserRow: { + /** @description The user name. */ + userName: string | null; + /** @description The email address, if any. */ + email: string | null; + /** + * Format: date-time + * @description When the account was created. + */ + created: string; + /** @description Whether the user is an administrator. */ + isAdministrator: boolean; + /** @description The avatar's address, or null for the initial. */ + avatarUrl: string | null; + /** + * @description Whether the account waits for an administrator to enable it (`Accounts:RequireApproval`). + * @default false + */ + pendingApproval: boolean; + }; + /** @description What the Users screen (`/admin/users`) shows: the filtered, paged accounts and the state of the last action. */ + UsersViewModel: { + /** @description User-name filter (contains). */ + q?: string | null; + /** + * Format: int32 + * @description One-based page number (the `p` query value; not "page", which Razor Pages reserved for the page path). + */ + pageNumber?: number; + /** @description The users on this page. */ + users?: components["schemas"]["UserRow"][]; + /** + * Format: int32 + * @description How many accounts, in all pages, wait for approval. + */ + pendingCount?: number; + /** + * Format: int32 + * @description The number of pages for the current filter. + */ + pageCount?: number; + /** @description The signed in administrator's user name; their own row has no actions. */ + currentUserName?: string | null; + /** @description Whether a reset link can be mailed: SMTP is configured. */ + canEmailResetLink?: boolean; + /** @description Whether an invitation (a reset link mailed to the new user) can be offered: SMTP is configured. */ + canInvite?: boolean; + /** @description The password just generated. Only ever rendered by the response to the reset itself, never kept in TempData or a cookie. */ + generatedPassword?: string | null; + /** @description The user string? UsersViewModel.GeneratedPassword belongs to. */ + generatedFor?: string | null; + /** @description Whether string? UsersViewModel.GeneratedPassword is a new account's first password rather than a reset. */ + generatedForNewUser?: boolean; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description What the validation status screen (`/packages/{id}/validation`) shows; filled by the screen's workflow. */ + ValidationStatusViewModel: { + /** @description The package ID from the address. */ + id?: string | null; + /** @description The newest submission of each version, newest version first. */ + submissions?: components["schemas"]["ValidationSubmission"][]; + }; + /** @description One version's newest validation submission and the verdict of every step. */ + ValidationSubmission: { + version: string; + submissionId: string | null; + status: string; + steps: components["schemas"]["PackageValidation"][]; + }; + /** + * @description Where a submission stands: still to run, or stopped without being indexed. + * @enum {string} + */ + ValidationSubmissionState: "Pending" | "Quarantined"; + /** @description One submission awaiting validation or quarantined. */ + ValidationSubmissionSummary: { + submissionId: string; + repository: string; + packageId: string | null; + packageVersion: string | null; + state: components["schemas"]["ValidationSubmissionState"]; + /** Format: date-time */ + created: string; + failureMessages: string[]; + }; + /** @description What the validation queue screen (`/admin/validation`) shows: pending and quarantined submissions. */ + ValidationViewModel: { + /** @description Whether validation can be administered here. */ + isSupported?: boolean; + /** @description The pending and quarantined submissions. */ + submissions?: components["schemas"]["ValidationSubmissionSummary"][]; + message?: string | null; + error?: string | null; + /** @description Whether the signed in administrator has a password to confirm with. */ + hasPassword?: boolean; + /** @description For an account without a password: it signed in again with its provider a moment ago. */ + reauthenticated?: boolean; + /** @description Whether an external provider is available to sign in again with. */ + canReauthenticate?: boolean; + /** @description The page to come back to after signing in again (the model of the confirmation partial). */ + returnPage?: string; + }; + /** @description One member of a virtual repository as the administration page lists it. */ + VirtualMemberDetail: { + /** @description The member's name, as stored. */ + name: string; + repository: (null) | components["schemas"]["RepositoryInfo"]; + /** @description Whether a repository of that name exists. */ + exists?: boolean; + }; + /** @description A virtual repository as the administration pages edit it. */ + VirtualRepositoryDetail: { + repository: components["schemas"]["RepositoryInfo"]; + /** @description Its direct members in resolution order. */ + members: components["schemas"]["VirtualMemberDetail"][]; + /** @description The name of the member that receives deployments, if any. */ + deployRepository: string | null; + deployTarget: (null) | components["schemas"]["RepositoryInfo"]; + /** @description The local and remote repositories that answer, in order, nested virtual members expanded. */ + effectiveMembers: components["schemas"]["RepositoryInfo"][]; + }; + }; + responses: never; + parameters: never; + requestBodies: never; + headers: never; + pathItems: never; +} +export type $defs = Record; +export type operations = Record; diff --git a/samples/BaGet.Frontend.React/src/api/screen.ts b/samples/BaGet.Frontend.React/src/api/screen.ts new file mode 100644 index 000000000..f7fae3779 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/api/screen.ts @@ -0,0 +1,49 @@ +import { routeFor } from '../routes'; +import type { components } from './schema'; + +export type Status = components['schemas']['ScreenStatus']; +export type ScreenNext = components['schemas']['ScreenNext']; + +/** The shape of every /api/ui answer; the generated client types `model` per endpoint. */ +export interface ScreenResultLike { + status?: Status; + model?: T | null; + errors?: { [field: string]: string[] } | null; + next?: ScreenNext | null; +} + +/** What the screens work with: the status, the HTTP status and the typed model. */ +export interface Screen { + status: Status; + http: number; + model: T | null; + errors: Record; + next: ScreenNext | null; +} + +/** + * Turns an openapi-fetch answer into a `Screen`. The document describes 200 and the 400/401/403/404 + * errors with the same ScreenResult schema, so `data` or `error` holds a typed body. The status is + * inferred from the HTTP code only when there is no body (a proxy error, a 503). + */ +export function toScreen(r: { data?: ScreenResultLike; error?: ScreenResultLike; response: Response }): Screen { + const body = r.data ?? r.error; + const http = r.response.status; + const status: Status = body?.status ?? (http === 401 ? 'SignIn' : http === 403 ? 'Forbidden' : http === 404 ? 'NotFound' : http === 400 ? 'Invalid' : 'Ok'); + return { status, http, model: body?.model ?? null, errors: body?.errors ?? {}, next: body?.next ?? null }; +} + +/** The message of a refusal: the form-level error, else a generic text for the status. */ +export function refusalText(s: Screen): string { + const form = s.errors['']; + if (form?.length) return form.join(' '); + if (s.status === 'SignIn') return 'Sign in to see this.'; + if (s.status === 'Forbidden') return 'You may not see this.'; + if (s.status === 'NotFound') return 'Not found.'; + return 'The server refused the request (HTTP ' + s.http + ').'; +} + +/** The SPA route a successful write sends the user to, or undefined when it stays here. */ +export function nextRoute(s: Screen): string | undefined { + return s.next?.screen ? routeFor(s.next.screen, s.next.routeValues ?? {}) : undefined; +} diff --git a/samples/BaGet.Frontend.React/src/api/session.ts b/samples/BaGet.Frontend.React/src/api/session.ts new file mode 100644 index 000000000..21dbf429b --- /dev/null +++ b/samples/BaGet.Frontend.React/src/api/session.ts @@ -0,0 +1,53 @@ +import type { components } from './schema'; + +export type SessionModel = components['schemas']['SessionModel']; + +/** + * Token storage. + * + * Trade-off: the access token (15 min) lives in memory only, so it never touches disk, but a script + * injected into the page can still read it. The refresh token (14 days) is kept in sessionStorage so a + * reload of the tab stays signed in; sessionStorage is per tab and cleared when the tab closes, but any + * XSS can read it. localStorage would survive restarts and be shared across tabs (worse); a backend for + * frontend with an HttpOnly cookie, or BaGet's same-origin cookie mode, avoids script-readable tokens. + */ +const REFRESH_KEY = 'baget.refresh'; + +export interface SessionState { + accessToken: string | null; + refreshToken: string | null; + userName: string | null; +} + +let state: SessionState = { accessToken: null, refreshToken: sessionStorage.getItem(REFRESH_KEY), userName: null }; +const listeners = new Set<() => void>(); + +function set(next: SessionState) { + state = next; + if (next.refreshToken) sessionStorage.setItem(REFRESH_KEY, next.refreshToken); + else sessionStorage.removeItem(REFRESH_KEY); + listeners.forEach((l) => l()); +} + +export const sessionStore = { + subscribe(l: () => void) { + listeners.add(l); + return () => { + listeners.delete(l); + }; + }, + get: () => state, + /** Keeps the tokens of a `POST /session*` answer. */ + adopt(m: SessionModel) { + set({ accessToken: m.accessToken ?? null, refreshToken: m.refreshToken ?? null, userName: m.userName ?? state.userName }); + }, + /** Applies the X-Session-* headers of an answer that renewed the pair (password change, ...). */ + adoptHeaders(h: Headers) { + const access = h.get('X-Session-Access-Token'); + if (!access) return; + set({ ...state, accessToken: access, refreshToken: h.get('X-Session-Refresh-Token') ?? state.refreshToken }); + }, + clear() { + set({ accessToken: null, refreshToken: null, userName: null }); + }, +}; diff --git a/samples/BaGet.Frontend.React/src/auth.tsx b/samples/BaGet.Frontend.React/src/auth.tsx new file mode 100644 index 000000000..312078c00 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/auth.tsx @@ -0,0 +1,55 @@ +import { createContext, useContext, useEffect, useState, useSyncExternalStore, type ReactNode } from 'react'; +import { api, refreshSession } from './api/client'; +import { toScreen } from './api/screen'; +import { sessionStore, type SessionModel } from './api/session'; + +interface Auth { + /** False until the stored refresh token (if any) has been tried once. */ + ready: boolean; + userName: string | null; + signedIn: boolean; + /** Stores the tokens of a finished sign-in. */ + adopt(m: SessionModel): void; + signOut(everywhere?: boolean): Promise; +} + +const Ctx = createContext(null); + +export function AuthProvider({ children }: { children: ReactNode }) { + const s = useSyncExternalStore(sessionStore.subscribe, sessionStore.get); + const [ready, setReady] = useState(false); + + // A reload loses the in-memory access token: get a new one from the refresh token in sessionStorage. + useEffect(() => { + const { accessToken, refreshToken } = sessionStore.get(); + if (accessToken || !refreshToken) { + setReady(true); + return; + } + void refreshSession().finally(() => setReady(true)); + }, []); + + const value: Auth = { + ready, + userName: s.userName, + signedIn: s.accessToken !== null, + adopt: (m) => sessionStore.adopt(m), + async signOut(everywhere = false) { + const { refreshToken } = sessionStore.get(); + // "Everywhere" changes the account's security stamp, ending every token and cookie session. + // Plain sign-out revokes nothing server side: the client simply forgets its tokens. + try { + toScreen(await api.POST('/api/ui/session/sign-out', { body: { everywhere, refreshToken: refreshToken ?? undefined } })); + } finally { + sessionStore.clear(); + } + }, + }; + return {children}; +} + +export function useAuth(): Auth { + const v = useContext(Ctx); + if (!v) throw new Error('useAuth outside AuthProvider'); + return v; +} diff --git a/samples/BaGet.Frontend.React/src/components/Form.tsx b/samples/BaGet.Frontend.React/src/components/Form.tsx new file mode 100644 index 000000000..839a374e3 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/components/Form.tsx @@ -0,0 +1,52 @@ +import type { InputHTMLAttributes, ReactNode } from 'react'; +import { refusalText, type Screen } from '../api/screen'; + +type Errors = Record; + +/** Messages for one field; server names may be cased differently (userName / UserName). */ +export function fieldErrors(errors: Errors, name: string): string[] { + const hit = Object.keys(errors).find((k) => k.toLowerCase() === name.toLowerCase()); + return hit ? errors[hit] : []; +} + +/** Form-level messages: the "" key, plus any key that matches no field of the form. */ +export function FormErrors({ errors, fields }: { errors: Errors; fields: string[] }) { + const known = fields.map((f) => f.toLowerCase()); + const messages = Object.entries(errors) + .filter(([k]) => k === '' || !known.includes(k.toLowerCase())) + .flatMap(([, v]) => v); + if (!messages.length) return null; + return ( +
    + {messages.map((m, i) => ( +
  • {m}
  • + ))} +
+ ); +} + +export function Field({ label, name, errors, ...input }: { label: string; name: string; errors: Errors } & InputHTMLAttributes) { + const own = fieldErrors(errors, name); + return ( + + ); +} + +/** The answer a screen could not use (401 / 403 / 404 / server error), as a message with a hint. */ +export function Refusal({ screen, children }: { screen: Screen; children?: ReactNode }) { + return ( +
+ {screen.status === 'SignIn' ? 'Signed out' : screen.status === 'Forbidden' ? 'Forbidden' : 'Problem'} +

{refusalText(screen)}

+ {children} +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/components/useScreen.ts b/samples/BaGet.Frontend.React/src/components/useScreen.ts new file mode 100644 index 000000000..29306fe12 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/components/useScreen.ts @@ -0,0 +1,21 @@ +import { useEffect, useState } from 'react'; +import type { Screen } from '../api/screen'; + +/** Loads a screen when `deps` change; `null` while loading. A network failure becomes an Invalid screen. */ +export function useScreen(load: () => Promise>, deps: unknown[]): Screen | null { + const [screen, setScreen] = useState | null>(null); + useEffect(() => { + let live = true; + setScreen(null); + load() + .catch((e: unknown): Screen => ({ status: 'Invalid', http: 0, model: null, errors: { '': [String(e)] }, next: null })) + .then((s) => { + if (live) setScreen(s); + }); + return () => { + live = false; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, deps); + return screen; +} diff --git a/samples/BaGet.Frontend.React/src/config.ts b/samples/BaGet.Frontend.React/src/config.ts new file mode 100644 index 000000000..f333f64bb --- /dev/null +++ b/samples/BaGet.Frontend.React/src/config.ts @@ -0,0 +1,5 @@ +/** BaGet base URL without a trailing slash; empty = same origin. */ +export const baseUrl = (import.meta.env.VITE_BAGET_URL ?? '').replace(/\/$/, ''); + +/** Where the build is served (Vite `base`, BaGet's Frontend:SpaBasePath), without the trailing slash. */ +export const basePath = import.meta.env.BASE_URL.replace(/\/$/, ''); diff --git a/samples/BaGet.Frontend.React/src/main.tsx b/samples/BaGet.Frontend.React/src/main.tsx new file mode 100644 index 000000000..1fceb88d6 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/main.tsx @@ -0,0 +1,17 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { BrowserRouter } from 'react-router-dom'; +import { App } from './App'; +import { AuthProvider } from './auth'; +import { basePath } from './config'; +import './styles.css'; + +createRoot(document.getElementById('root')!).render( + + + + + + + , +); diff --git a/samples/BaGet.Frontend.React/src/pages/AdminUsers.tsx b/samples/BaGet.Frontend.React/src/pages/AdminUsers.tsx new file mode 100644 index 000000000..722d07e33 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/AdminUsers.tsx @@ -0,0 +1,62 @@ +import { Link, useLocation, useSearchParams } from 'react-router-dom'; +import { api } from '../api/client'; +import { toScreen } from '../api/screen'; +import { Refusal } from '../components/Form'; +import { useScreen } from '../components/useScreen'; + +/** + * `GET /api/ui/admin/users`: needs an administrator's session. The other answers are shown as they come: + * SignIn (401, no or expired session), Forbidden (403, signed in but not an administrator). + */ +export function AdminUsers() { + const location = useLocation(); + const [params, setParams] = useSearchParams(); + const q = params.get('q') ?? ''; + const p = Number(params.get('p') ?? '1') || 1; + const screen = useScreen(async () => toScreen(await api.GET('/api/ui/admin/users', { params: { query: { q, p } } })), [q, p]); + + if (!screen) return

Loading...

; + if (!screen.model || screen.status === 'SignIn' || screen.status === 'Forbidden') { + return ( + + {screen.status === 'SignIn' && Sign in} + {screen.status === 'Forbidden' &&

This screen is for administrators.

} +
+ ); + } + const m = screen.model; + return ( +
+

Users

+
{ + e.preventDefault(); + setParams({ q: String(new FormData(e.currentTarget).get('q') ?? '') }); + }} + > + + +
+ + + + + + {(m.users ?? []).map((u) => ( + + + + + + + ))} + +
UserEmailCreatedRole
{u.userName}{u.pendingApproval ? ' (pending)' : ''}{u.email}{u.created ? new Date(u.created).toLocaleDateString() : ''}{u.isAdministrator ? 'administrator' : 'user'}
+ +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/pages/ConfirmEmail.tsx b/samples/BaGet.Frontend.React/src/pages/ConfirmEmail.tsx new file mode 100644 index 000000000..9935f8a28 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/ConfirmEmail.tsx @@ -0,0 +1,54 @@ +import { useState } from 'react'; +import { Link, useSearchParams } from 'react-router-dom'; +import { api } from '../api/client'; +import { toScreen } from '../api/screen'; +import { useScreen } from '../components/useScreen'; +import { Field, FormErrors } from '../components/Form'; + +/** The email link is /confirm-email?userId=&code=[&email=]; the GET confirms. */ +export function ConfirmEmail() { + const [params] = useSearchParams(); + const userId = params.get('userId') ?? ''; + const code = params.get('code') ?? ''; + const email = params.get('email') ?? undefined; + const screen = useScreen( + async () => toScreen(await api.GET('/api/ui/account/confirmemail', { params: { query: { userId, code, email } } })), + [userId, code, email], + ); + const [resent, setResent] = useState(false); + const [resendErrors, setResendErrors] = useState>({}); + + if (!screen) return

Confirming...

; + if (screen.model?.succeeded) { + return ( +
+

Email confirmed

+ {screen.model.pendingApproval ?

An administrator still has to approve your account.

:

Sign in.

} +
+ ); + } + return ( +
+

This link did not work

+

It may have expired or been used already. Enter your user name or email to receive a new one.

+ {resent ? ( +

If an unconfirmed account matches, a new link is on its way.

+ ) : ( +
{ + e.preventDefault(); + const identifier = String(new FormData(e.currentTarget).get('identifier') ?? ''); + const s = toScreen(await api.POST('/api/ui/account/resend-confirmation', { body: { identifier } })); + if (s.status === 'Invalid') setResendErrors(s.errors); + else setResent(true); + }} + > + + + + + )} +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/pages/ForgotPassword.tsx b/samples/BaGet.Frontend.React/src/pages/ForgotPassword.tsx new file mode 100644 index 000000000..fc387d638 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/ForgotPassword.tsx @@ -0,0 +1,35 @@ +import { useState, type FormEvent } from 'react'; +import { api } from '../api/client'; +import { toScreen, type Screen } from '../api/screen'; +import { Field, FormErrors } from '../components/Form'; + +export function ForgotPassword() { + const [result, setResult] = useState | null>(null); + + async function submit(e: FormEvent) { + e.preventDefault(); + const identifier = String(new FormData(e.currentTarget).get('identifier') ?? ''); + setResult(toScreen(await api.POST('/api/ui/account/forgotpassword', { body: { identifier } }))); + } + + // The server answers the same whoever the name belongs to, so does the page. + if (result && result.status !== 'Invalid') { + return ( +
+

Check your email

+

If an account matches, a link to choose a new password is on its way.

+
+ ); + } + const errors = result?.errors ?? {}; + return ( +
+

Forgot password

+
+ + + + +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/pages/Home.tsx b/samples/BaGet.Frontend.React/src/pages/Home.tsx new file mode 100644 index 000000000..dc2130593 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/Home.tsx @@ -0,0 +1,51 @@ +import { Link, useSearchParams } from 'react-router-dom'; +import { api } from '../api/client'; +import { toScreen } from '../api/screen'; +import { Refusal } from '../components/Form'; +import { useScreen } from '../components/useScreen'; + +/** Package list and search: the twin of the home page, `GET /api/ui/packages?q=&p=`. */ +export function Home() { + const [params, setParams] = useSearchParams(); + const q = params.get('q') ?? ''; + const p = Number(params.get('p') ?? '1') || 1; + const screen = useScreen(async () => toScreen(await api.GET('/api/ui/packages', { params: { query: { q, p } } })), [q, p]); + + return ( +
+

Packages

+
{ + e.preventDefault(); + setParams({ q: String(new FormData(e.currentTarget).get('q') ?? '') }); + }} + > + + +
+ {!screen &&

Loading...

} + {screen && !screen.model && } + {screen?.model && ( + <> +
    + {(screen.model.packages ?? []).map((pkg) => ( +
  • + + {pkg.title || pkg.id} {pkg.version} + + {String(pkg.totalDownloads ?? 0)} downloads +

    {pkg.summary || pkg.description}

    +
  • + ))} + {!screen.model.packages?.length &&
  • No package found.
  • } +
+ + + )} +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/pages/PackageDetail.tsx b/samples/BaGet.Frontend.React/src/pages/PackageDetail.tsx new file mode 100644 index 000000000..00ad2a4d2 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/PackageDetail.tsx @@ -0,0 +1,48 @@ +import { Link, useParams } from 'react-router-dom'; +import { api } from '../api/client'; +import { toScreen } from '../api/screen'; +import { Refusal } from '../components/Form'; +import { useScreen } from '../components/useScreen'; + +/** `GET /api/ui/packages/{id}` (latest) or `/api/ui/packages/{id}/{version}`. A missing package is a NotFound screen (404), not an exception. */ +export function PackageDetail() { + const { id = '', version } = useParams(); + const screen = useScreen(async () => + toScreen( + version === undefined + ? await api.GET('/api/ui/packages/{id}', { params: { path: { id } } }) + : await api.GET('/api/ui/packages/{id}/{version}', { params: { path: { id, version } } }), + ), + [id, version], + ); + + if (!screen) return

Loading...

; + const m = screen.model; + if (!m || m.found === false) return Back to the list; + return ( +
+

+ {m.package?.id} {m.package?.version} +

+

{m.package?.description}

+

+ {String(m.totalDownloads ?? 0)} downloads, by {(m.package?.authors ?? []).join(', ') || 'unknown'} +

+ {m.installTabs?.map((t) => ( +
+ {t.name} +
{(t.lines ?? []).join('\n')}
+
+ ))} +

Versions

+
    + {(m.versions ?? []).map((v) => ( +
  • + {v.selected ? {v.version} : {v.version}} +
  • + ))} +
+ {m.readmeHtml &&

This package has a readme (HTML, not rendered here: sanitise it before injecting it).

} +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/pages/Register.tsx b/samples/BaGet.Frontend.React/src/pages/Register.tsx new file mode 100644 index 000000000..b1f49ea0a --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/Register.tsx @@ -0,0 +1,58 @@ +import { useState, type FormEvent } from 'react'; +import { Link, useNavigate } from 'react-router-dom'; +import { api } from '../api/client'; +import { toScreen, type Screen } from '../api/screen'; +import { useAuth } from '../auth'; +import { Field, FormErrors } from '../components/Form'; +import type { components } from '../api/schema'; + +type RegisterModel = components['schemas']['RegisterViewModel']; + +export function Register() { + const auth = useAuth(); + const navigate = useNavigate(); + const [result, setResult] = useState | null>(null); + + async function submit(e: FormEvent) { + e.preventDefault(); + const f = new FormData(e.currentTarget); + const text = (k: string) => String(f.get(k) ?? ''); + const s = toScreen( + await api.POST('/api/ui/account/register', { + body: { userName: text('userName'), email: text('email'), password: text('password'), confirmPassword: text('confirmPassword') }, + }), + ); + setResult(s); + // The account could sign in at once: the answer carries its tokens. + if (s.status !== 'Invalid' && s.model?.session?.accessToken) { + auth.adopt(s.model.session); + navigate('/', { replace: true }); + } + } + + const m = result?.status === 'Invalid' ? null : result?.model; + if (m && !m.session) { + return ( +
+

Account created

+ {m.confirmationSent &&

We sent you an email: follow its link to confirm your address.

} + {m.awaitingApproval &&

An administrator has to approve your account before you can sign in.

} + {!m.confirmationSent && !m.awaitingApproval &&

You can now sign in.

} +
+ ); + } + const errors = result?.errors ?? {}; + return ( +
+

Register

+
+ + + + + + + +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/pages/ResetPassword.tsx b/samples/BaGet.Frontend.React/src/pages/ResetPassword.tsx new file mode 100644 index 000000000..829fc07e7 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/ResetPassword.tsx @@ -0,0 +1,44 @@ +import { useState, type FormEvent } from 'react'; +import { Link, useSearchParams } from 'react-router-dom'; +import { api } from '../api/client'; +import { toScreen, type Screen } from '../api/screen'; +import { Field, FormErrors } from '../components/Form'; + +/** The email link is /reset-password?userId=&code=; `code` is posted back unchanged. */ +export function ResetPassword() { + const [params] = useSearchParams(); + const userId = params.get('userId') ?? ''; + const code = params.get('code') ?? ''; + const [result, setResult] = useState | null>(null); + + async function submit(e: FormEvent) { + e.preventDefault(); + const f = new FormData(e.currentTarget); + const text = (k: string) => String(f.get(k) ?? ''); + setResult( + toScreen(await api.POST('/api/ui/account/resetpassword', { body: { userId, code, password: text('password'), confirmPassword: text('confirmPassword') } })), + ); + } + + if (!userId || !code) return

This link is incomplete. Ask for a new one on the forgot password page.

; + if (result && result.status !== 'Invalid') { + return ( +
+

Password changed

+

Sign in with your new password.

+
+ ); + } + const errors = result?.errors ?? {}; + return ( +
+

Choose a new password

+
+ + + + + +
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/pages/SignIn.tsx b/samples/BaGet.Frontend.React/src/pages/SignIn.tsx new file mode 100644 index 000000000..34631eb41 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/pages/SignIn.tsx @@ -0,0 +1,142 @@ +import { useEffect, useRef, useState, type FormEvent } from 'react'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { api } from '../api/client'; +import { nextRoute, toScreen, type Screen } from '../api/screen'; +import type { SessionModel } from '../api/session'; +import { useAuth } from '../auth'; +import { basePath, baseUrl } from '../config'; +import { Field, FormErrors } from '../components/Form'; + +type Step = 'password' | 'code' | 'recovery'; + +const OIDC_STATE_KEY = 'baget.oidc-state'; + +/** Saves a random state, then leaves for the provider `id`; BaGet returns to `/sign-in?state=...#exchange_token=...`. */ +function startExternalSignIn(id: string) { + const bytes = crypto.getRandomValues(new Uint8Array(16)); + const state = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); + sessionStorage.setItem(OIDC_STATE_KEY, state); + const returnUrl = encodeURIComponent(`${window.location.origin}${basePath}/sign-in?state=${state}`); + window.location.href = `${baseUrl}/api/ui/session/external/${encodeURIComponent(id)}?returnUrl=${returnUrl}`; +} + +export function SignIn() { + const auth = useAuth(); + const navigate = useNavigate(); + const location = useLocation(); + const [step, setStep] = useState('password'); + const [ticket, setTicket] = useState(''); + const [result, setResult] = useState | null>(null); + const [notice, setNotice] = useState(null); + const [busy, setBusy] = useState(false); + // One button per external provider the server offers (the sign-in screen model lists them). + const [providers, setProviders] = useState<{ id: string; displayName: string }[]>([]); + const from = (location.state as { from?: string } | null)?.from ?? '/'; + + /** A session answer is either tokens (done) or a two-factor ticket (ask for the code). */ + function handle(s: Screen) { + setResult(s); + const m = s.model; + if (m?.twoFactorRequired && m.twoFactorTicket) { + setTicket(m.twoFactorTicket); + setStep('code'); + } else if (m?.accessToken) { + auth.adopt(m); + navigate(nextRoute(s) ?? from, { replace: true }); + } + } + + useEffect(() => { + // Anonymous endpoint; a failure (or an old server) just means no external buttons. + void api + .GET('/api/ui/session/providers', {}) + .then((r) => setProviders(toScreen(r).model?.providers ?? [])) + .catch(() => setProviders([])); + }, []); + + // External sign-in returns to /sign-in#exchange_token=...: take the token out of the address bar + // at once (history and Referer), then exchange it. #notice / #error carry messages instead. + const handled = useRef(false); + useEffect(() => { + if (handled.current || !location.hash) return; + const h = new URLSearchParams(location.hash.slice(1)); + const exchangeToken = h.get('exchange_token'); + if (!exchangeToken && !h.get('notice') && !h.get('error')) return; + handled.current = true; + // The callback must carry the random state saved before the redirect (it binds the answer to this browser). + const expected = sessionStorage.getItem(OIDC_STATE_KEY); + sessionStorage.removeItem(OIDC_STATE_KEY); + const stateOk = !!expected && new URLSearchParams(location.search).get('state') === expected; + history.replaceState(null, '', location.pathname); + if (!stateOk) { + setResult({ status: 'Invalid', http: 400, model: null, errors: { '': ['External sign-in refused: the state does not match. Start again.'] }, next: null }); + return; + } + setNotice(h.get('notice') ?? null); + if (h.get('error')) setResult({ status: 'Invalid', http: 400, model: null, errors: { '': [h.get('error')!] }, next: null }); + if (exchangeToken) { + setBusy(true); + void api + .POST('/api/ui/session/exchange', { body: { exchangeToken } }) + .then((r) => handle(toScreen(r))) + .finally(() => setBusy(false)); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [location.hash]); + + async function submit(e: FormEvent) { + e.preventDefault(); + const f = new FormData(e.currentTarget); + const text = (k: string) => String(f.get(k) ?? ''); + setBusy(true); + try { + if (step === 'password') { + handle(toScreen(await api.POST('/api/ui/session', { body: { userName: text('userName'), password: text('password') } }))); + } else if (step === 'code') { + handle(toScreen(await api.POST('/api/ui/session/two-factor', { body: { ticket, code: text('code') } }))); + } else { + handle(toScreen(await api.POST('/api/ui/session/recovery-code', { body: { ticket, recoveryCode: text('recoveryCode') } }))); + } + } finally { + setBusy(false); + } + } + + const errors = result?.errors ?? {}; + + return ( +
+

Sign in

+ {notice &&

{notice}

} +
+ {step === 'password' && ( + <> + + + + )} + {step === 'code' && } + {step === 'recovery' && } + + + {step === 'code' && ( + + )} + +

+ Create an account | Forgot your password? + {providers.map((p) => ( + + {' '} + |{' '} + + + ))} +

+
+ ); +} diff --git a/samples/BaGet.Frontend.React/src/routes.ts b/samples/BaGet.Frontend.React/src/routes.ts new file mode 100644 index 000000000..296a00309 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/routes.ts @@ -0,0 +1,20 @@ +/** Maps a ScreenResult `next.screen` ({controller, action}) to a route of this application. */ +const table: Record) => string> = { + 'home/index': () => '/', + 'package/index': (v) => `/packages/${encodeURIComponent(String(v.id ?? ''))}/${encodeURIComponent(String(v.version ?? ''))}`, + 'account/login': () => '/sign-in', + 'account/register': () => '/register', + 'account/forgotpassword': () => '/forgot-password', + 'account/resetpassword': () => '/reset-password', + 'account/confirmemail': () => '/confirm-email', + 'adminusers/index': () => '/admin/users', +}; + +/** Unknown screens fall back to the home page: an SPA covers only the screens it implements. */ +export function routeFor( + screen: { controller?: string | null; action?: string | null }, + routeValues: Record = {}, +): string { + const key = `${screen.controller ?? ''}/${screen.action ?? ''}`.toLowerCase(); + return (table[key] ?? (() => '/'))(routeValues); +} diff --git a/samples/BaGet.Frontend.React/src/styles.css b/samples/BaGet.Frontend.React/src/styles.css new file mode 100644 index 000000000..78283c43e --- /dev/null +++ b/samples/BaGet.Frontend.React/src/styles.css @@ -0,0 +1,25 @@ +:root { font-family: system-ui, sans-serif; color: #1c2430; background: #f6f7f9; } +body { margin: 0; } +header { display: flex; gap: 1rem; align-items: center; padding: .6rem 1.2rem; background: #1f3a5f; color: #fff; } +header a { color: #fff; text-decoration: none; } +header nav { display: flex; gap: 1rem; } +.brand { font-weight: 700; font-size: 1.2rem; } +.spacer { flex: 1; } +main { max-width: 56rem; margin: 1.5rem auto; padding: 0 1rem; } +.card { display: grid; gap: .8rem; max-width: 24rem; padding: 1rem; background: #fff; border: 1px solid #d8dde4; border-radius: 6px; } +.field { display: grid; gap: .25rem; } +.field input, input { padding: .4rem; border: 1px solid #aab3bf; border-radius: 4px; } +.field input[aria-invalid='true'] { border-color: #b3261e; } +button { padding: .4rem .8rem; cursor: pointer; } +button.link { background: none; border: 0; color: #1f5fbf; text-decoration: underline; } +.errors, .error, .refusal { color: #b3261e; } +.errors { margin: 0; padding-left: 1.2rem; } +.refusal { padding: 1rem; background: #fdecea; border-radius: 6px; } +.notice { padding: .6rem; background: #e7f3ea; border-radius: 4px; } +.muted { color: #67707d; } +.list { list-style: none; padding: 0; } +.list li { padding: .6rem 0; border-bottom: 1px solid #e2e6eb; } +.pager { display: flex; gap: .5rem; margin-top: 1rem; } +table { border-collapse: collapse; width: 100%; background: #fff; } +th, td { text-align: left; padding: .4rem .6rem; border-bottom: 1px solid #e2e6eb; } +pre { padding: .6rem; background: #eef1f5; overflow: auto; } diff --git a/samples/BaGet.Frontend.React/src/vite-env.d.ts b/samples/BaGet.Frontend.React/src/vite-env.d.ts new file mode 100644 index 000000000..3e76b0a23 --- /dev/null +++ b/samples/BaGet.Frontend.React/src/vite-env.d.ts @@ -0,0 +1,5 @@ +/// +interface ImportMetaEnv { + /** BaGet base URL; empty = same origin (the build served by BaGet, or the dev proxy). */ + readonly VITE_BAGET_URL?: string; +} diff --git a/samples/BaGet.Frontend.React/tsconfig.json b/samples/BaGet.Frontend.React/tsconfig.json new file mode 100644 index 000000000..ae1f21a2a --- /dev/null +++ b/samples/BaGet.Frontend.React/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true, + "isolatedModules": true, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["src"] +} diff --git a/samples/BaGet.Frontend.React/vite.config.ts b/samples/BaGet.Frontend.React/vite.config.ts new file mode 100644 index 000000000..774253675 --- /dev/null +++ b/samples/BaGet.Frontend.React/vite.config.ts @@ -0,0 +1,15 @@ +import react from '@vitejs/plugin-react'; +import { defineConfig } from 'vite'; + +// Built for BaGet's Frontend:SpaBasePath=/app. Change `base` (and the router basename in +// src/main.tsx follows it) if you host under another path. +export default defineConfig({ + base: '/app/', + plugins: [react()], + server: { + port: 5173, + // Dev convenience for "same origin" mode (VITE_BAGET_URL empty): /api goes to a local BaGet. + // The browser's Origin stays http://localhost:5173, so list it in Cors:AllowedOrigins. + proxy: { '/api': { target: process.env.BAGET_DEV_PROXY ?? 'http://localhost:6060', changeOrigin: true } }, + }, +}); diff --git a/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj b/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj index 51c3b7967..38c8c921b 100644 --- a/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj +++ b/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj @@ -1,21 +1,19 @@ - netcoreapp3.1 + net10.0 false - IDE0007 + + Exe + IDE0007;CS8600;CS8601;CS8602;CS8603;CS8604;CS8605;CS8607;CS8608;CS8609;CS8610;CS8611;CS8612;CS8613;CS8614;CS8615;CS8616;CS8617;CS8618;CS8619;CS8620;CS8621;CS8622;CS8624;CS8625;CS8629;CS8631;CS8633;CS8634;CS8643;CS8644;CS8645;CS8653;CS8654;CS8655;CS8667;CS8670;CS8714;CS8762;CS8764;CS8765;CS8766;CS8767;CS8768;CS8769;CS8770;CS8774;CS8775;CS8776;CS8777;CS9264 + latest + annotations - - - - - all - runtime; build; native; contentfiles; analyzers - - + + diff --git a/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs b/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs index e3488f9af..faa6304eb 100644 --- a/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs +++ b/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs @@ -4,38 +4,39 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Samples.Tests +namespace BaGet.Protocol.Samples.Tests; + +public class Sample01_Download { - public class Sample01_Download + [Fact] + public async Task DownloadPackage() { - [Fact] - public async Task DownloadPackage() - { - // Downloads a package file (.nupkg) - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + var cancellationToken = TestContext.Current.CancellationToken; + // Downloads a package file (.nupkg) + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - string packageId = "Newtonsoft.Json"; - NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + string packageId = "Newtonsoft.Json"; + NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - using (Stream packageStream = await client.DownloadPackageAsync(packageId, packageVersion)) - { - Console.WriteLine($"Downloaded package {packageId} {packageVersion}"); - } + using (Stream packageStream = await client.DownloadPackageAsync(packageId, packageVersion, cancellationToken)) + { + Console.WriteLine($"Downloaded package {packageId} {packageVersion}"); } + } - [Fact] - public async Task DownloadPackageManifest() - { - // Downloads a package manifest (.nuspec) - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + [Fact] + public async Task DownloadPackageManifest() + { + var cancellationToken = TestContext.Current.CancellationToken; + // Downloads a package manifest (.nuspec) + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - string packageId = "Newtonsoft.Json"; - NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + string packageId = "Newtonsoft.Json"; + NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - using (Stream manifestStream = await client.DownloadPackageManifestAsync(packageId, packageVersion)) - { - Console.WriteLine($"Downloaded package {packageId} {packageVersion}'s nuspec"); - } + using (Stream manifestStream = await client.DownloadPackageManifestAsync(packageId, packageVersion, cancellationToken)) + { + Console.WriteLine($"Downloaded package {packageId} {packageVersion}'s nuspec"); } } -} +} \ No newline at end of file diff --git a/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs b/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs index 2d3cc8acb..8525ec8e4 100644 --- a/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs +++ b/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs @@ -5,60 +5,62 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Samples.Tests +namespace BaGet.Protocol.Samples.Tests; + +public class Sample02_Search { - public class Sample02_Search + [Fact] + public async Task Exists() { - [Fact] - public async Task Exists() - { - // Check if a package exists. - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + var cancellationToken = TestContext.Current.CancellationToken; + // Check if a package exists. + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - if (!await client.ExistsAsync("newtonsoft.json")) - { - Console.WriteLine("Package 'newtonsoft.json' does not exist!"); - } - - var packageVersion = NuGetVersion.Parse("12.0.1"); - if (!await client.ExistsAsync("newtonsoft.json", packageVersion)) - { - Console.WriteLine("Package 'newtonsoft.json' version '12.0.1' does not exist!"); - } + if (!await client.ExistsAsync("newtonsoft.json", cancellationToken)) + { + Console.WriteLine("Package 'newtonsoft.json' does not exist!"); } - [Fact] - public async Task Search() + var packageVersion = NuGetVersion.Parse("12.0.1"); + if (!await client.ExistsAsync("newtonsoft.json", packageVersion, cancellationToken)) { - // Search for packages that are relevant to "json". - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - IReadOnlyList results = await client.SearchAsync("json"); + Console.WriteLine("Package 'newtonsoft.json' version '12.0.1' does not exist!"); + } + } - var index = 1; - foreach (SearchResult result in results) - { - Console.WriteLine($"Result #{index}"); - Console.WriteLine($"Package id: {result.PackageId}"); - Console.WriteLine($"Package version: {result.Version}"); - Console.WriteLine($"Package downloads: {result.TotalDownloads}"); - Console.WriteLine($"Package versions: {result.Versions.Count}"); - Console.WriteLine(); + [Fact] + public async Task Search() + { + var cancellationToken = TestContext.Current.CancellationToken; + // Search for packages that are relevant to "json". + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + IReadOnlyList results = await client.SearchAsync("json", cancellationToken); - index++; - } + var index = 1; + foreach (SearchResult result in results) + { + Console.WriteLine($"Result #{index}"); + Console.WriteLine($"Package id: {result.PackageId}"); + Console.WriteLine($"Package version: {result.Version}"); + Console.WriteLine($"Package downloads: {result.TotalDownloads}"); + Console.WriteLine($"Package versions: {result.Versions.Count}"); + Console.WriteLine(); + + index++; } + } - [Fact] - public async Task Autocomplete() - { - // Search for packages whose names' start with "Newt". - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - IReadOnlyList packageIds = await client.AutocompleteAsync("Newt"); + [Fact] + public async Task Autocomplete() + { + var cancellationToken = TestContext.Current.CancellationToken; + // Search for packages whose names' start with "Newt". + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + IReadOnlyList packageIds = await client.AutocompleteAsync("Newt", cancellationToken); - foreach (string packageId in packageIds) - { - Console.WriteLine($"Found package ID '{packageId}'"); - } + foreach (string packageId in packageIds) + { + Console.WriteLine($"Found package ID '{packageId}'"); } } -} +} \ No newline at end of file diff --git a/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs b/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs index da959f4e9..7b829fa6c 100644 --- a/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs +++ b/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs @@ -6,63 +6,65 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Samples.Tests +namespace BaGet.Protocol.Samples.Tests; + +public class Sample03_Metadata { - public class Sample03_Metadata + [Fact] + public async Task GetAllPackageMetadata() { - [Fact] - public async Task GetAllPackageMetadata() - { - // Find the metadata for all versions of a package. - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - - IReadOnlyList items = await client.GetPackageMetadataAsync("Newtonsoft.Json"); - if (!items.Any()) - { - Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); - return; - } + var cancellationToken = TestContext.Current.CancellationToken; + // Find the metadata for all versions of a package. + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - // There is an item for each version of the package. - foreach (var metadata in items) - { - Console.WriteLine($"Version: {metadata.Version}"); - Console.WriteLine($"Listed: {metadata.Listed}"); - Console.WriteLine($"Tags: {metadata.Tags}"); - Console.WriteLine($"Description: {metadata.Description}"); - } + IReadOnlyList items = await client.GetPackageMetadataAsync("Newtonsoft.Json", cancellationToken); + if (!items.Any()) + { + Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); + return; } - [Fact] - public async Task GetPackageMetadata() + // There is an item for each version of the package. + foreach (var metadata in items) { - // Find the metadata for a single version of a package. - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - - string packageId = "Newtonsoft.Json"; - NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - - PackageMetadata metadata = await client.GetPackageMetadataAsync(packageId, packageVersion); - + Console.WriteLine($"Version: {metadata.Version}"); Console.WriteLine($"Listed: {metadata.Listed}"); Console.WriteLine($"Tags: {metadata.Tags}"); Console.WriteLine($"Description: {metadata.Description}"); } + } - [Fact] - public async Task ListVersions() - { - // Find all versions of a package (including unlisted versions). - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + [Fact] + public async Task GetPackageMetadata() + { + var cancellationToken = TestContext.Current.CancellationToken; + // Find the metadata for a single version of a package. + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + + string packageId = "Newtonsoft.Json"; + NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + + PackageMetadata metadata = await client.GetPackageMetadataAsync(packageId, packageVersion, cancellationToken); + + Console.WriteLine($"Listed: {metadata.Listed}"); + Console.WriteLine($"Tags: {metadata.Tags}"); + Console.WriteLine($"Description: {metadata.Description}"); + } - IReadOnlyList packageVersions = await client.ListPackageVersionsAsync("Newtonsoft.Json", includeUnlisted: true); - if (!packageVersions.Any()) - { - Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); - return; - } + [Fact] + public async Task ListVersions() + { + var cancellationToken = TestContext.Current.CancellationToken; + // Find all versions of a package (including unlisted versions). + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - Console.WriteLine($"Found {packageVersions.Count} versions"); + IReadOnlyList packageVersions = await client.ListPackageVersionsAsync("Newtonsoft.Json", includeUnlisted: true, cancellationToken); + if (!packageVersions.Any()) + { + Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); + return; } + + Console.WriteLine($"Found {packageVersions.Count} versions"); } -} +} \ No newline at end of file diff --git a/samples/BaGetWebApplication/BaGetWebApplication.csproj b/samples/BaGetWebApplication/BaGetWebApplication.csproj index 3123a668b..b4b89439a 100644 --- a/samples/BaGetWebApplication/BaGetWebApplication.csproj +++ b/samples/BaGetWebApplication/BaGetWebApplication.csproj @@ -1,12 +1,16 @@ - + - netcoreapp3.1 + net10.0 + latest + enable + - + + diff --git a/samples/BaGetWebApplication/Program.cs b/samples/BaGetWebApplication/Program.cs index a91fee8b8..e53f54fd4 100644 --- a/samples/BaGetWebApplication/Program.cs +++ b/samples/BaGetWebApplication/Program.cs @@ -1,25 +1,66 @@ +using System.IO; using System.Threading.Tasks; -using BaGet.Web; -using Microsoft.AspNetCore.Hosting; +using BaGet; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; +using BaGet.Web.V3.Extensions; -namespace BaGetWebApplication +namespace BaGetWebApplication; + +public class Program { - public class Program + public static async Task Main(string[] args) { - public static async Task Main(string[] args) + var builder = WebApplication.CreateBuilder(args); + + builder.Services.AddBaGetWebApplication(app => { - var host = CreateHostBuilder(args).Build(); + // Use SQLite as BaGet's database and store packages on the local file system. + app.AddSqliteDatabase(); + app.AddFileStorage(); + }); + + // The web UI (screens and views); leave it out for a host that serves only the APIs. + builder.Services.AddBaGetFrontEnd(); + + var app = builder.Build(); + + if (app.Environment.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } - await host.RunMigrationsAsync(); - await host.RunAsync(); + app.UseStaticFiles(); + + // The layout links the UI's static files at /_content/BaGet.Web/...; the BaGet host serves its wwwroot there. This sample + // serves the same folder from the repository (a real embedding host ships a copy of it: see the Extension.BaGet package). + var uiFiles = Path.GetFullPath(Path.Combine(app.Environment.ContentRootPath, "..", "..", "src", "BaGet", "wwwroot")); + if (Directory.Exists(uiFiles)) + { + app.UseStaticFiles(new StaticFileOptions + { + FileProvider = new PhysicalFileProvider(uiFiles), + RequestPath = "/_content/BaGet.Web", + }); } - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); + app.UseRouting(); + + // Required: selects the repository of /r/{repo}/ requests (404 for an unknown one). Without it those routes would be + // served from the default repository, so BaGet answers them 500. Keep it before authentication, if you add any. + app.UseRepositoryResolution(); + + // Writes answer 503 while the server is read-only (a database copy, for one), and a cancelled request is not an error. + app.UseOperationCancelledMiddleware(); + app.UseMaintenanceMiddleware(); + + // This sample adds no authentication, so every caller is anonymous: see BaGet.Web.V3's README to add accounts or an API key. + + // Add BaGet's endpoints. + new BaGetEndpointBuilder().MapEndpoints(app); + + await app.RunMigrationsAsync(); + await app.RunAsync(); } } diff --git a/samples/BaGetWebApplication/Startup.cs b/samples/BaGetWebApplication/Startup.cs deleted file mode 100644 index fe11415a0..000000000 --- a/samples/BaGetWebApplication/Startup.cs +++ /dev/null @@ -1,40 +0,0 @@ -using BaGet; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace BaGetWebApplication -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services.AddBaGetWebApplication(app => - { - // Use SQLite as BaGet's database and store packages on the local file system. - app.AddSqliteDatabase(); - app.AddFileStorage(); - }); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseStaticFiles(); - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - // Add BaGet's endpoints. - var baget = new BaGetEndpointBuilder(); - - baget.MapEndpoints(endpoints); - }); - } - } -} diff --git a/samples/readme.md b/samples/readme.md index 90f70a48c..703e51230 100644 --- a/samples/readme.md +++ b/samples/readme.md @@ -2,5 +2,5 @@ Here you can find samples that show you how to use BaGet in your own projects: -* `BaGetWebApplication` - Embed BaGet into your own ASP.NET Core project +* `BaGetWebApplication` - Embed BaGet into your own ASP.NET Core project. `AddBaGetWebApplication` brings the V3 API, web UI, catalog, the validation pipeline (off unless `Validation:Enabled`) and browser-upload staging; the sample adds SQLite and file storage. It calls `UseRepositoryResolution()` (required: `/r/{repo}/` is answered 500 without it) and serves the UI files of `src/BaGet/wwwroot` at `/_content/BaGet.Web`. Accounts are not wired: the full host, `src/BaGet/Program.cs`, adds them * `BaGet.Protocol.Samples.Tests` - Interact with a NuGet V3 API diff --git a/src/BaGet.Aliyun/AliyunApplicationExtensions.cs b/src/BaGet.Aliyun/AliyunApplicationExtensions.cs index eb8a6e745..cf296ed6c 100644 --- a/src/BaGet.Aliyun/AliyunApplicationExtensions.cs +++ b/src/BaGet.Aliyun/AliyunApplicationExtensions.cs @@ -6,41 +6,42 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class AliyunApplicationExtensions { - public static class AliyunApplicationExtensions + public static BaGetApplication AddAliyunOssStorage(this BaGetApplication app) { - public static BaGetApplication AddAliyunOssStorage(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; - return new OssClient(options.Endpoint, options.AccessKey, options.AccessKeySecret); - }); + return new OssClient(options.Endpoint, options.AccessKey, options.AccessKeySecret); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("AliyunOss")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasStorageType("AliyunOss")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAliyunOssStorage( - this BaGetApplication app, - Action configure) - { - app.AddAliyunOssStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAliyunOssStorage( + this BaGetApplication app, + Action configure) + { + app.AddAliyunOssStorage(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Aliyun/AliyunStorageOptions.cs b/src/BaGet.Aliyun/AliyunStorageOptions.cs index 2357bdd61..ca22887be 100644 --- a/src/BaGet.Aliyun/AliyunStorageOptions.cs +++ b/src/BaGet.Aliyun/AliyunStorageOptions.cs @@ -1,21 +1,25 @@ using System.ComponentModel.DataAnnotations; -namespace BaGet.Aliyun +using BaGet.Core; + +namespace BaGet.Aliyun; + +[RestartRequired] +public class AliyunStorageOptions { - public class AliyunStorageOptions - { - [Required] - public string AccessKey { get; set; } + [Required] + [SensitiveSetting] + public string? AccessKey { get; set; } - [Required] - public string AccessKeySecret { get; set; } + [Required] + [SensitiveSetting] + public string? AccessKeySecret { get; set; } - [Required] - public string Endpoint { get; set; } + [Required] + public string? Endpoint { get; set; } - [Required] - public string Bucket { get; set; } + [Required] + public string? Bucket { get; set; } - public string Prefix { get; set; } - } -} + public string? Prefix { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Aliyun/AliyunStorageService.Streaming.cs b/src/BaGet.Aliyun/AliyunStorageService.Streaming.cs new file mode 100644 index 000000000..2a69e09c4 --- /dev/null +++ b/src/BaGet.Aliyun/AliyunStorageService.Streaming.cs @@ -0,0 +1,406 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Aliyun.OSS; +using BaGet.Core; +using OssPart = global::Aliyun.OSS.Part; +using OssException = global::Aliyun.OSS.Common.OssException; + +namespace BaGet.Aliyun; + +/// +/// Streaming uploads on OSS multipart uploads (), laid out exactly like the S3 provider: +/// parts are assembled into a temporary object under .uploads/ and copied (in ranges) to the final key at commit; bytes +/// short of a part wait in a .tail object, so an upload's whole state is in OSS. Memory per request: one part +/// (). +/// +/// +/// Not verified against a live service: OSS has no emulator, so this provider is covered by code review and the shared +/// contract only. The commit is also not atomic against a concurrent commit of the same final key: the SDK sends no +/// x-oss-forbid-overwrite (see ), so the key is checked first. +/// +public partial class AliyunStorageService +{ + /// The size of a part: OSS wants at least 100 KB (except the last), allows 10 000 parts and 5 GB each. + internal const int PartSize = 16 * 1024 * 1024; + + private const string GenericContentType = "application/octet-stream"; + + // A copied range is one part of the final multipart copy. + private const long CopyRangeSize = 512L * 1024 * 1024; + + public async Task BeginUploadAsync(string contentType, CancellationToken cancellationToken = default) + { + var id = Guid.NewGuid().ToString("N"); + var result = await Run(() => _client.InitiateMultipartUpload( + new InitiateMultipartUploadRequest(_bucket, TempKey(id)) + { + ObjectMetadata = new ObjectMetadata { ContentType = string.IsNullOrEmpty(contentType) ? GenericContentType : contentType }, + }), cancellationToken).ConfigureAwait(false); + + return Convert.ToBase64String(Encoding.UTF8.GetBytes(id + "|" + result.UploadId)) + .Replace('+', '-').Replace('/', '_').TrimEnd('='); + } + + public async Task AppendAsync(string uploadId, long offset, Stream chunk, CancellationToken cancellationToken = default) + { + if (chunk == null) throw new ArgumentNullException(nameof(chunk)); + + var (id, ossId) = Decode(uploadId); + var state = await ReadStateAsync(id, ossId, uploadId, cancellationToken).ConfigureAwait(false); + if (state.Length != offset) throw new StorageUploadOffsetException(state.Length, offset); + + var tracked = UploadDigestTracker.Shared.Track(uploadId, offset, chunk); + try + { + var partNumber = state.LastPartNumber; + var stored = state.PartsLength; + + var tail = await StreamPartitioner.SplitAsync( + tracked, + state.Tail, + PartSize, + async (part, ct) => + { + partNumber++; + var number = partNumber; + var bytes = part; + await Run(() => + { + using var body = StreamingStreams.AsStream(bytes); + return _client.UploadPart(new UploadPartRequest(_bucket, TempKey(id), ossId) + { + PartNumber = number, + PartSize = bytes.Length, + InputStream = body, + }); + }, ct).ConfigureAwait(false); + stored += part.Length; + }, + cancellationToken).ConfigureAwait(false); + + if (tail.Length > 0) + { + await Run(() => + { + using var body = new MemoryStream(tail, writable: false); + return _client.PutObject(_bucket, TailKey(id), body); + }, cancellationToken).ConfigureAwait(false); + } + else if (state.Tail.Length > 0) + { + await Run(() => { _client.DeleteObject(_bucket, TailKey(id)); return 0; }, cancellationToken).ConfigureAwait(false); + } + + var length = stored + tail.Length; + tracked.Complete(length); + return length; + } + catch + { + tracked.Fail(); + throw; + } + } + + public async Task GetUploadLengthAsync(string uploadId, CancellationToken cancellationToken = default) + { + try + { + var (id, ossId) = Decode(uploadId); + return (await ReadStateAsync(id, ossId, uploadId, cancellationToken).ConfigureAwait(false)).Length; + } + catch (StorageUploadNotFoundException) + { + return null; + } + } + + public async Task CommitAsync(string uploadId, string path, string? expectedSha256, CancellationToken cancellationToken = default) + { + var (id, ossId) = Decode(uploadId); + var state = await ReadStateAsync(id, ossId, uploadId, cancellationToken).ConfigureAwait(false); + var finalKey = PrepareKey(path); + var tempKey = TempKey(id); + var sha = UploadDigestTracker.Shared.TryComplete(uploadId, state.Length); + + if (sha != null && expectedSha256 != null && !string.Equals(expectedSha256, sha, StringComparison.OrdinalIgnoreCase)) + { + await DiscardAsync(id, ossId, cancellationToken).ConfigureAwait(false); + throw new StorageDigestMismatchException(expectedSha256, sha); + } + + // Nothing but a tail: a single put, no multipart. + if (state.LastPartNumber == 0) + { + sha ??= StreamingStorage.Sha256Hex(state.Tail); + if (expectedSha256 != null && !string.Equals(expectedSha256, sha, StringComparison.OrdinalIgnoreCase)) + { + await DiscardAsync(id, ossId, cancellationToken).ConfigureAwait(false); + throw new StorageDigestMismatchException(expectedSha256, sha); + } + + StoragePutResult put; + if (await Run(() => _client.DoesObjectExist(_bucket, finalKey), cancellationToken).ConfigureAwait(false)) + { + put = await CompareAsync(finalKey, sha, cancellationToken).ConfigureAwait(false); + } + else + { + await Run(() => + { + using var body = new MemoryStream(state.Tail, writable: false); + return _client.PutObject(_bucket, finalKey, body, new ObjectMetadata { ContentType = GenericContentType }); + }, cancellationToken).ConfigureAwait(false); + put = StoragePutResult.Success; + } + + await DiscardAsync(id, ossId, cancellationToken).ConfigureAwait(false); + return new StorageCommitResult(put, state.Length, sha); + } + + if (state.Tail.Length > 0) + { + await Run(() => + { + using var body = new MemoryStream(state.Tail, writable: false); + return _client.UploadPart(new UploadPartRequest(_bucket, tempKey, ossId) + { + PartNumber = state.LastPartNumber + 1, + PartSize = state.Tail.Length, + InputStream = body, + }); + }, cancellationToken).ConfigureAwait(false); + } + + await Run(() => + { + var complete = new CompleteMultipartUploadRequest(_bucket, tempKey, ossId); + foreach (var part in ListParts(tempKey, ossId)) complete.PartETags.Add(new PartETag(part.PartNumber, part.ETag)); + return _client.CompleteMultipartUpload(complete); + }, cancellationToken).ConfigureAwait(false); + + try + { + sha ??= await ReadSha256Async(tempKey, cancellationToken).ConfigureAwait(false); + StreamingStorage.VerifyDigest(expectedSha256, sha); + + if (await Run(() => _client.DoesObjectExist(_bucket, finalKey), cancellationToken).ConfigureAwait(false)) + { + return new StorageCommitResult(await CompareAsync(finalKey, sha, cancellationToken).ConfigureAwait(false), state.Length, sha); + } + + await CopyAsync(tempKey, finalKey, state.Length, cancellationToken).ConfigureAwait(false); + return new StorageCommitResult(StoragePutResult.Success, state.Length, sha); + } + finally + { + UploadDigestTracker.Shared.Forget(uploadId); + await Run(() => { _client.DeleteObject(_bucket, tempKey); _client.DeleteObject(_bucket, TailKey(id)); return 0; }, CancellationToken.None).ConfigureAwait(false); + } + } + + public async Task AbortAsync(string uploadId, CancellationToken cancellationToken = default) + { + UploadDigestTracker.Shared.Forget(uploadId); + + string id, ossId; + try + { + (id, ossId) = Decode(uploadId); + } + catch (StorageUploadNotFoundException) + { + return; + } + + await DiscardAsync(id, ossId, cancellationToken).ConfigureAwait(false); + } + + public async Task GetInfoAsync(string path, CancellationToken cancellationToken = default) + { + var key = PrepareKey(path); + return await Run(() => + { + if (!_client.DoesObjectExist(_bucket, key)) return null; + + var meta = _client.GetObjectMetadata(_bucket, key); + return new StorageBlobInfo(meta.ContentLength, meta.ContentType); + }, cancellationToken).ConfigureAwait(false); + } + + public async Task GetRangeAsync(string path, long offset, long? length, CancellationToken cancellationToken = default) + { + var info = await GetInfoAsync(path, cancellationToken).ConfigureAwait(false); + if (info == null) return null; + + var count = StreamingStorage.ResolveRange(info.Length, offset, length); + if (count == 0) return Stream.Null; + + // Bounded range requests, each re-requested from the exact byte if its connection drops: one GET of many GB must not be the unit of failure. + return new WindowedReadStream( + async (from, size, ct) => + { + var request = new GetObjectRequest(_bucket, PrepareKey(path)); + request.SetRange(from, from + size - 1); + var result = await Run(() => _client.GetObject(request), ct).ConfigureAwait(false); + return new OwnedReadStream(result.Content, result); + }, + offset, + count); + } + + private string TempKey(string id) => PrepareKey(StreamingStorage.UploadsFolder + Separator + id); + + private string TailKey(string id) => PrepareKey(StreamingStorage.UploadsFolder + Separator + id + ".tail"); + + private static Task Run(Func work, CancellationToken cancellationToken) + => Task.Run(work, cancellationToken); + + private static (string Id, string OssId) Decode(string uploadId) + { + try + { + var padded = uploadId.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + (4 - padded.Length % 4) % 4, '='); + var text = Encoding.UTF8.GetString(Convert.FromBase64String(padded)); + var bar = text.IndexOf('|'); + if (bar == 32 && Guid.TryParseExact(text.Substring(0, bar), "N", out _) && bar < text.Length - 1) + { + return (text.Substring(0, bar), text.Substring(bar + 1)); + } + } + catch (FormatException) + { + } + + throw new StorageUploadNotFoundException(uploadId); + } + + private sealed record UploadState(int LastPartNumber, long PartsLength, byte[] Tail) + { + public long Length => PartsLength + Tail.Length; + } + + private List ListParts(string key, string ossId) + { + var parts = new List(); + int? marker = null; + while (true) + { + var request = new ListPartsRequest(_bucket, key, ossId); + if (marker != null) request.PartNumberMarker = marker; + var page = _client.ListParts(request); + parts.AddRange(page.Parts); + + if (!page.IsTruncated) break; + marker = page.NextPartNumberMarker; + } + + return parts.OrderBy(p => p.PartNumber).ToList(); + } + + private async Task ReadStateAsync(string id, string ossId, string uploadId, CancellationToken cancellationToken) + { + List parts; + try + { + parts = await Run(() => ListParts(TempKey(id), ossId), cancellationToken).ConfigureAwait(false); + } + catch (OssException e) when (e.ErrorCode == "NoSuchUpload") + { + throw new StorageUploadNotFoundException(uploadId); + } + + var tailKey = TailKey(id); + var tail = await Run(() => + { + if (!_client.DoesObjectExist(_bucket, tailKey)) return Array.Empty(); + + using var result = _client.GetObject(_bucket, tailKey); + using var buffer = new MemoryStream(); + result.Content.CopyTo(buffer); + return buffer.ToArray(); + }, cancellationToken).ConfigureAwait(false); + + return new UploadState(parts.Count == 0 ? 0 : parts.Max(p => p.PartNumber), parts.Sum(p => p.Size), tail); + } + + private async Task ReadSha256Async(string key, CancellationToken cancellationToken) + { + using var result = await Run(() => _client.GetObject(_bucket, key), cancellationToken).ConfigureAwait(false); + return await StreamingStorage.Sha256HexAsync(result.Content, cancellationToken).ConfigureAwait(false); + } + + private async Task CompareAsync(string key, string sha, CancellationToken cancellationToken) + { + var existing = await ReadSha256Async(key, cancellationToken).ConfigureAwait(false); + return string.Equals(existing, sha, StringComparison.Ordinal) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict; + } + + private Task CopyAsync(string sourceKey, string key, long size, CancellationToken cancellationToken) + => Run(() => + { + var start = _client.InitiateMultipartUpload(new InitiateMultipartUploadRequest(_bucket, key)); + try + { + var complete = new CompleteMultipartUploadRequest(_bucket, key, start.UploadId); + var number = 0; + for (long first = 0; first < size; first += CopyRangeSize) + { + number++; + var copied = _client.UploadPartCopy(new UploadPartCopyRequest(_bucket, sourceKey, _bucket, key, start.UploadId) + { + PartNumber = number, + BeginIndex = first, + PartSize = Math.Min(CopyRangeSize, size - first), + }); + complete.PartETags.Add(copied.PartETag); + } + + if (number == 0) + { + _client.AbortMultipartUpload(new AbortMultipartUploadRequest(_bucket, key, start.UploadId)); + using var empty = new MemoryStream(); + _client.PutObject(_bucket, key, empty); + return 0; + } + + _client.CompleteMultipartUpload(complete); + return 0; + } + catch + { + try + { + _client.AbortMultipartUpload(new AbortMultipartUploadRequest(_bucket, key, start.UploadId)); + } + catch (OssException) + { + } + + throw; + } + }, cancellationToken); + + private async Task DiscardAsync(string id, string ossId, CancellationToken cancellationToken) + { + await Run(() => + { + try + { + _client.AbortMultipartUpload(new AbortMultipartUploadRequest(_bucket, TempKey(id), ossId)); + } + catch (OssException e) when (e.ErrorCode == "NoSuchUpload") + { + } + + _client.DeleteObject(_bucket, TailKey(id)); + return 0; + }, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Aliyun/AliyunStorageService.cs b/src/BaGet.Aliyun/AliyunStorageService.cs index 9ea3e6353..5ba993111 100644 --- a/src/BaGet.Aliyun/AliyunStorageService.cs +++ b/src/BaGet.Aliyun/AliyunStorageService.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -6,88 +7,153 @@ using BaGet.Core; using Microsoft.Extensions.Options; -namespace BaGet.Aliyun +namespace BaGet.Aliyun; + +public partial class AliyunStorageService : IStreamingStorageService, IListableStorageService { - public class AliyunStorageService : IStorageService + private const string Separator = "/"; + + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; + + private readonly string? _bucket; + private readonly string? _prefix; + private readonly OssClient _client; + + public AliyunStorageService(IOptionsSnapshot options, OssClient client) { - private const string Separator = "/"; - private readonly string _bucket; - private readonly string _prefix; - private readonly OssClient _client; + if (options == null) + throw new ArgumentNullException(nameof(options)); - public AliyunStorageService(IOptionsSnapshot options, OssClient client) - { - if (options == null) - throw new ArgumentNullException(nameof(options)); + _bucket = options.Value.Bucket; + _prefix = options.Value.Prefix; + _client = client ?? throw new ArgumentNullException(nameof(client)); - _bucket = options.Value.Bucket; - _prefix = options.Value.Prefix; - _client = client ?? throw new ArgumentNullException(nameof(client)); + if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) + _prefix += Separator; + } - if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) - _prefix += Separator; - } + private string PrepareKey(string path) + { + return _prefix + path.Replace("\\", Separator); + } - private string PrepareKey(string path) + public async Task GetAsync(string path, CancellationToken cancellationToken = default) + { + try { - return _prefix + path.Replace("\\", Separator); - } + var ossObject = await Task.Factory.FromAsync(_client.BeginGetObject, _client.EndGetObject, _bucket, PrepareKey(path), null); - public async Task GetAsync(string path, CancellationToken cancellationToken = default) + return ossObject.ResponseStream; + } + catch (global::Aliyun.OSS.Common.OssException e) when (e.ErrorCode == "NoSuchKey") { - try - { - var ossObject = await Task.Factory.FromAsync(_client.BeginGetObject, _client.EndGetObject, _bucket, PrepareKey(path), null); - - return ossObject.ResponseStream; - } - catch (Exception) - { - // TODO - throw; - } + // The one "missing content" exception of IStorageService.GetAsync, as FileStorageService throws. + throw new FileNotFoundException("The object '" + path + "' does not exist.", path, e); } + } - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) - { - var uri = _client.GeneratePresignedUri(_bucket, PrepareKey(path)); + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + var uri = _client.GeneratePresignedUri(_bucket, PrepareKey(path)); - return Task.FromResult(uri); - } + return Task.FromResult(uri); + } + + public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + { + if (content == null) throw new ArgumentNullException(nameof(content)); - public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + var key = PrepareKey(path); + + // A temporary file, not a MemoryStream: a large package is never held in managed memory. + using (var seekableContent = await StreamingStreams.SpoolAsync(content, cancellationToken).ConfigureAwait(false)) { - // TODO: Uploads should be idempotent. This should fail if and only if the blob - // already exists but has different content. + // Storing the same content twice is not a failure, storing different content + // at a taken key is. OSS does signal the latter itself, through the + // "x-oss-forbid-overwrite" request header and a 409 "FileAlreadyExists" + // response, but this SDK exposes neither: ObjectMetadata has no such header + // and OssException carries only ErrorCode, with no HTTP status code to match + // on. So the check is made here instead, which leaves the window between the + // check and the put open to a concurrent upload - unlike FileStorageService, + // BlobStorageService and GoogleCloudStorageService, which all decide this + // atomically in the store. + // TODO: make this atomic once the SDK sends "x-oss-forbid-overwrite" and + // surfaces the 409, or once it is confirmed against a live OSS account that + // ObjectMetadata.AddHeader reaches the request unprefixed. + if (_client.DoesObjectExist(_bucket, key)) + { + using (var targetStream = await GetAsync(path, cancellationToken)) + { + seekableContent.Seek(0, SeekOrigin.Begin); + + return seekableContent.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; + } + } + + seekableContent.Seek(0, SeekOrigin.Begin); var metadata = new ObjectMetadata { ContentType = contentType, }; - var putResult = await Task.Factory.FromAsync(_client.BeginPutObject, _client.EndPutObject, _bucket, PrepareKey(path), content, metadata); + // PutObjectResult.HttpStatusCode is not inspected. The branches that used to + // read it ("check sdk documents") mapped 409 to Conflict and 302 to + // AlreadyExists, and neither is reachable: OSS reports a refused put by + // throwing OssException, and PutObjectResult is not documented to carry any + // status that means conflict. + await Task.Factory.FromAsync( + _client.BeginPutObject, _client.EndPutObject, _bucket, key, seekableContent, metadata); - switch (putResult.HttpStatusCode) - { - case System.Net.HttpStatusCode.OK: - return StoragePutResult.Success; + return StoragePutResult.Success; + } + } - // TODO: check sdk documents - //case System.Net.HttpStatusCode.Conflict: - // return StoragePutResult.Conflict; + /// + /// Every object under a prefix, paged until OSS says there is no more. The sweep of + /// abandoned staged uploads is the only caller, and without this a bucket would keep + /// them forever. + /// + public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // "staging-archive/...". + var prefix = PrepareKey(pathPrefix.TrimEnd('/') + Separator); + var paths = new List(); + string? marker = null; - //case System.Net.HttpStatusCode.Found: - // return StoragePutResult.AlreadyExists; + do + { + cancellationToken.ThrowIfCancellationRequested(); + + // Listed synchronously, as DoesObjectExist above is: this SDK's asynchronous + // surface is the Begin/End pairs, which it does not offer for listing. + var listing = _client.ListObjects(new ListObjectsRequest(_bucket) + { + Prefix = prefix, + Marker = marker, + }); - default: - return StoragePutResult.Success; + foreach (var item in listing.ObjectSummaries) + { + // Reported as the paths IStorageService takes, so the configured bucket + // prefix is removed again. + paths.Add(string.IsNullOrEmpty(_prefix) ? item.Key : item.Key.Substring(_prefix.Length)); } - } - public Task DeleteAsync(string path, CancellationToken cancellationToken = default) - { - _client.DeleteObject(_bucket, PrepareKey(path)); - return Task.CompletedTask; + marker = listing.IsTruncated ? listing.NextMarker : null; } + while (!string.IsNullOrEmpty(marker)); + + return Task.FromResult>(paths); + } + + public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + _client.DeleteObject(_bucket, PrepareKey(path)); + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Aliyun/BaGet.Aliyun.csproj b/src/BaGet.Aliyun/BaGet.Aliyun.csproj index ad7896fcc..5059953d3 100644 --- a/src/BaGet.Aliyun/BaGet.Aliyun.csproj +++ b/src/BaGet.Aliyun/BaGet.Aliyun.csproj @@ -1,12 +1,20 @@ - + NuGet;Alibaba;Cloud - The libraries to host BaGet on Alibaba Cloud (Aliyun). - netstandard2.0 + The libraries to host BaGet Extension on Alibaba Cloud (Aliyun). + net10.0 + latest + enable - + + + + + + + diff --git a/src/BaGet.Aliyun/README.md b/src/BaGet.Aliyun/README.md new file mode 100644 index 000000000..446afb770 --- /dev/null +++ b/src/BaGet.Aliyun/README.md @@ -0,0 +1,26 @@ +# Extension.BaGet.Aliyun + +Alibaba Cloud (Aliyun) OSS package storage for [BaGet Extension](https://pieroviano.github.io/BaGet/). + +```powershell +dotnet add package Extension.BaGet.Aliyun +``` + +## Usage + +```csharp +services.AddBaGetWebApplication(app => app.AddAliyunOssStorage()); +``` + +Active when `Storage:Type` is `AliyunOss`. + +| Setting | Value | +|---|---| +| `Storage:Endpoint` | OSS endpoint, e.g. `oss-cn-hangzhou.aliyuncs.com` | +| `Storage:Bucket` | Bucket name | +| `Storage:Prefix` | Optional key prefix | +| `Storage:AccessKey`, `Storage:AccessKeySecret` | Credentials | + +## Links + +[Hosting on Alibaba Cloud](https://pieroviano.github.io/BaGet/installation/aliyun/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Api.Base/BaGet.Api.Base.csproj b/src/BaGet.Api.Base/BaGet.Api.Base.csproj new file mode 100644 index 000000000..b8f990baf --- /dev/null +++ b/src/BaGet.Api.Base/BaGet.Api.Base.csproj @@ -0,0 +1,35 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's shared base of the web APIs: the /api/ui twin controllers' bases, the screen-naming attributes and the API-key principal resolver. + + BaGet.Frontend + enable + Extension.$(MSBuildProjectName) + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Api.Base/Controllers/Base/AccessApiControllerBase.cs b/src/BaGet.Api.Base/Controllers/Base/AccessApiControllerBase.cs new file mode 100644 index 000000000..4a3db1095 --- /dev/null +++ b/src/BaGet.Api.Base/Controllers/Base/AccessApiControllerBase.cs @@ -0,0 +1,45 @@ +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.UseCases.Access; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the access-control screens' JSON twins (groups, permissions, projects, audit; retention and replication build on it), like +/// AccessControllerBase: administrators, or whoever admits (a project's administrators); an +/// administrator is pointed at /admin/access-unavailable where there is no access model; every write is refused with 503 while +/// the server is read-only. +/// +public abstract class AccessApiControllerBase : AdminApiControllerBase +{ + /// Admits a caller who is not a server administrator. The default admits nobody else. + protected virtual Task AuthorizeAsync(CancellationToken cancellationToken) => Task.FromResult(false); + + /// + /// Who is using the screen, for a use case: the signed-in account (an API key's owner) and whether the caller is a server administrator rather than + /// only a project administrator (decided by the same that admitted the request). + /// + [NonAction] + protected async Task CallerAsync(CancellationToken cancellationToken) + => new(User, await Gate.IsAdministratorAsync(User, KeyCaller, cancellationToken)); + + /// The screen the running action serves (), so a base can widen one screen of a controller. + [NonAction] + protected ScreenRef? CurrentScreen() + => ControllerContext.ActionDescriptor.EndpointMetadata.OfType().FirstOrDefault()?.Screen; + + /// + protected override GateRequest Requirements(ActionExecutingContext context) + => base.Requirements(context) with + { + Role = GateRole.AccessAdministrator, + IsWrite = !(HttpMethods.IsGet(Request.Method) || HttpMethods.IsHead(Request.Method)), + AlsoAllow = AuthorizeAsync, + }; +} diff --git a/src/BaGet.Api.Base/Controllers/Base/AccountApiControllerBase.cs b/src/BaGet.Api.Base/Controllers/Base/AccountApiControllerBase.cs new file mode 100644 index 000000000..2b69e77d0 --- /dev/null +++ b/src/BaGet.Api.Base/Controllers/Base/AccountApiControllerBase.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the account screens' JSON twins: accounts enabled (else 404), mail configured when , signed in when +/// (else 401), through the same as AccountControllerBase. Account self-service +/// (password, two-factor, external logins, API keys, sign-in and out, deletion) and package ownership screens are interactive only (): +/// over HTTP they are open to a person's interactive session (a session token, or the cookie with an antiforgery header) and answer 403 "use the web screen" to +/// everybody else, API keys included; the web screen reaches them in process. +/// +public abstract class AccountApiControllerBase : ApiControllerBase, IAsyncActionFilter +{ + /// Whether the screen needs a signed-in user. + protected virtual bool RequiresSignIn => false; + + /// Whether the screen needs mail to be configured. + protected virtual bool RequiresEmail => false; + + /// Whether the twin is for interactive sessions only over HTTP (account self-service, package ownership): 403 for an API key and an anonymous caller. The administration bases lift it. + protected virtual bool CookieOnly => true; + + /// What the screen requires of the caller; a derived base widens it (role, writes). + protected virtual GateRequest Requirements(ActionExecutingContext context) + { + // The per-action forms of the two requirements, like AccountControllerBase reads them. + var metadata = context.ActionDescriptor.EndpointMetadata ?? (IList)Array.Empty(); + + return new GateRequest( + RequiresSignIn: RequiresSignIn || metadata.OfType().Any(), + RequiresEmail: RequiresEmail || metadata.OfType().Any(), + KeyCaller: KeyCaller, + + // An endpoint that gives a session out (or prepares for one) is open to a caller without credentials; an API key is still refused. + CookieOnly: CookieOnly && !(KeyCaller == null && metadata.OfType().Any())) + { + // This filter runs only when the twin is called over HTTP (the in-process call of a view controller skips it). + OverHttp = true, + InteractiveSession = InteractiveCaller != null, + }; + } + + /// Asks the gate; a refusal is the answer. + [NonAction] + public virtual async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var gate = await Gate.CheckAsync(User, Requirements(context), HttpContext.RequestAborted); + if (!gate.IsAllowed) + { + context.Result = new UiApiResult(Refusal(gate)); + return; + } + + await next(); + } +} diff --git a/src/BaGet.Api.Base/Controllers/Base/AdminApiControllerBase.cs b/src/BaGet.Api.Base/Controllers/Base/AdminApiControllerBase.cs new file mode 100644 index 000000000..c85cb89ec --- /dev/null +++ b/src/BaGet.Api.Base/Controllers/Base/AdminApiControllerBase.cs @@ -0,0 +1,21 @@ +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the administrator screens' JSON twins: the caller is an administrator's API key with the admin:api scope and no repository limit +/// (see ): 401 with no key, 403 for any other key, the global ApiKey included. +/// +public abstract class AdminApiControllerBase : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + /// + protected override bool CookieOnly => false; + + /// + protected override GateRequest Requirements(ActionExecutingContext context) + => base.Requirements(context) with { Role = GateRole.Administrator }; +} diff --git a/src/BaGet.Api.Base/Controllers/Base/ApiControllerBase.cs b/src/BaGet.Api.Base/Controllers/Base/ApiControllerBase.cs new file mode 100644 index 000000000..fd44b2ad4 --- /dev/null +++ b/src/BaGet.Api.Base/Controllers/Base/ApiControllerBase.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of every controller of the JSON UI API (/api/ui/...): the twin of a view controller that does the work of a screen and +/// returns its model, so a single-page application (or any client) can be written against it alone, and the view controller only renders +/// what UiApiInvoker got from it. +/// +/// Authentication (): API keys (Authorization: Bearer or X-NuGet-ApiKey), like /api/v1, or a person's +/// interactive session (a session token from /api/ui/session, or the cookie with an antiforgery header); the bare cookie and HTTP Basic are never accepted +/// over HTTP (see ). +/// Answers are through : status, model, errors, next. +/// No [ApiController]: its automatic 400 on an invalid model would differ between an HTTP call and the +/// in-process call of a view controller. An action validates explicitly and answers . +/// Filters do not run in process: the view controller's base runs the same before it calls the +/// twin, and its own antiforgery validation and cookie session. +/// +/// A twin is marked (never a view controller), routed under api/ui/ (a repository +/// screen also at api/ui/r/{repo}/... through ), and takes the request body as JSON +/// ([FromBody]) or multipart ([FromForm], file uploads). +/// +[TypeFilter(typeof(UiApiSecurityFilter))] +[Produces("application/json")] +// Not [ApiController], so ApiExplorer would skip the twins: they all belong in the OpenAPI document "ui". +[ApiExplorerSettings(IgnoreApi = false)] +public abstract class ApiControllerBase : ControllerBase +{ + /// The API key behind the request, or null for an anonymous caller or an interactive session. + protected BaGetPrincipal? KeyCaller => UiApiCaller.Key(HttpContext); + + /// The interactive session behind the request (a session token, or the cookie with a valid antiforgery header), or null. + protected BaGetPrincipal? InteractiveCaller => UiApiCaller.Interactive(HttpContext); + + /// The screen gate (the same one the view controllers ask). + protected ScreenGate Gate + => HttpContext.RequestServices.GetService() + ?? ActivatorUtilities.CreateInstance(HttpContext.RequestServices); + + /// + /// A use case, resolved when the action runs (not injected into the constructor): the account use cases are registered only while accounts are + /// enabled, and the gate must be able to answer 404 first. + /// + [NonAction] + protected T UseCase() where T : notnull => HttpContext.RequestServices.GetRequiredService(); + + /// + /// What the request binding already refused (a value that is not a number, a malformed body), by field, for a use case that must not act while + /// there is any. A use case validates its form itself; this only carries what it cannot see. + /// + [NonAction] + protected IReadOnlyDictionary BindingErrors() + => ModelState + .Where(entry => entry.Value is { Errors.Count: > 0 }) + .ToDictionary( + entry => entry.Key, + entry => entry.Value!.Errors.Select(e => string.IsNullOrEmpty(e.ErrorMessage) ? "The value is not valid." : e.ErrorMessage).ToArray()); + + /// The answer of an action: with the HTTP status of its decision. + [NonAction] + protected ActionResult> Respond(ScreenResult result) + => new(new UiApiResult(result ?? throw new ArgumentNullException(nameof(result)))); + + /// The answer for a gate's refusal: the screen has no model, so the result is of the action's own model type with only the decision set. + [NonAction] + protected static IScreenResult Refusal(GateResult gate) + => gate.Message != null + ? gate.Outcome switch + { + GateOutcome.SignIn => ScreenResult.SignIn(gate.Message), + GateOutcome.Forbidden => ScreenResult.Forbidden(gate.Message), + _ => Refusal(gate.Outcome), + } + : Refusal(gate.Outcome); + + /// The answer for a gate's refusal, without a message. + [NonAction] + protected static IScreenResult Refusal(GateOutcome outcome) + => outcome switch + { + GateOutcome.SignIn => ScreenResult.SignIn(), + GateOutcome.Forbidden => ScreenResult.Forbidden(), + GateOutcome.AccessUnavailable => ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AdminAccessUnavailable)), + _ => ScreenResult.NotFound(), + }; +} diff --git a/src/BaGet.Api.Base/Mvc/Attributes/AnonymousSessionEndpointAttribute.cs b/src/BaGet.Api.Base/Mvc/Attributes/AnonymousSessionEndpointAttribute.cs new file mode 100644 index 000000000..142143b97 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/AnonymousSessionEndpointAttribute.cs @@ -0,0 +1,20 @@ +using System; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// Marks an action of /api/ui that a client without a session calls to get one or to prepare for it (sign-in, refresh, exchange, antiforgery, registration, +/// forgot / reset password, confirm email): treats an invalid or expired session token on it as no credential at all (a client that +/// attaches its header to every request can still refresh), refuses a browser request from another origin (the Origin header must be this server's, or, unless +/// , listed in Cors:AllowedOrigins: with no list a separate-origin page cannot script these endpoints, whatever the CORS policy), and, for an +/// account twin, lets an anonymous HTTP caller through where the twin is otherwise for interactive sessions. +/// +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] +public sealed class AnonymousSessionEndpointAttribute : Attribute +{ + /// Only this server's own origin may call it (the cookie endpoints: a cookie is never set for another origin). + public bool SameOriginOnly { get; set; } + + /// A valid antiforgery request token (X-XSRF-TOKEN, from GET /api/ui/antiforgery while signed out) must accompany the request: no login CSRF. + public bool RequireAntiforgery { get; set; } +} diff --git a/src/BaGet.Api.Base/Mvc/Attributes/FallbackHandlerAttribute.cs b/src/BaGet.Api.Base/Mvc/Attributes/FallbackHandlerAttribute.cs new file mode 100644 index 000000000..c2674ef07 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/FallbackHandlerAttribute.cs @@ -0,0 +1,13 @@ +using System; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// Marks the action of a screen that only answers a request no handler of the screen claims (a stray POST without a known +/// ?handler=, answered 404 after the antiforgery check). It is not one of the screen's handlers, so it is no part of the screen's +/// routes or of the UI API parity; see and ScreenEndpoints. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class FallbackHandlerAttribute : Attribute +{ +} diff --git a/src/BaGet.Api.Base/Mvc/Attributes/NamedPageHandler.cs b/src/BaGet.Api.Base/Mvc/Attributes/NamedPageHandler.cs new file mode 100644 index 000000000..a34193fb6 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/NamedPageHandler.cs @@ -0,0 +1,6 @@ +using System.Collections.Generic; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// A named handler (OnPostApprove-style action) of a controller: its name, the HTTP methods it answers and its screen (see ). +internal sealed record NamedPageHandler(string Name, IReadOnlyList Verbs, string Screen); diff --git a/src/BaGet.Api.Base/Mvc/Attributes/PageHandlerAttribute.cs b/src/BaGet.Api.Base/Mvc/Attributes/PageHandlerAttribute.cs new file mode 100644 index 000000000..a6e801801 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/PageHandlerAttribute.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ActionConstraints; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.Routing; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// Selects a controller action by the handler value of the request, the way a Razor Page selects OnPostApprove +/// for ?handler=Approve, so every existing form, bookmark and script keeps posting to the same URL. The value is read +/// from the route values first, then from the query string (names are compared ignoring case), exactly as Razor Pages does. +/// +/// [PageHandler("Approve")] next to [HttpPost]: the action runs for a POST whose handler is +/// Approve. +/// [PageHandler] without a name: the default handler, OnGet / OnPost of the +/// page. It runs when the request names no handler or a handler that no action of the same screen (same +/// controller and route template, see ; the whole controller when the action has none) and HTTP method has (Razor Pages: an +/// unknown handler is the default handler). A repeated handler key counts by its first value, as in Razor Pages. The default handler of a screen that also has named handlers +/// must carry the attribute, else a request naming a handler would match both and be ambiguous. +/// +/// A HEAD request is answered by the GET handlers, so declare [HttpGet, HttpHead] on them. The attribute +/// is an action constraint, so routing does the selection; two actions with the same template, HTTP method and handler name +/// are ambiguous, as two OnPostApprove methods would be. +/// +/// +/// Usage: [HttpGet, PageHandler("CopyStatus")] CopyStatus() answers ?handler=CopyStatus, and [HttpPost, PageHandler] Post() (or just [HttpPost] when no sibling has a name). Forms keep +/// asp-route-handler="Approve" with asp-controller/asp-action (or Url.Action(..., new { handler = "Approve" })), which renders ?handler=Approve. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class PageHandlerAttribute : ActionMethodSelectorAttribute +{ + /// The route value and query string key that names the handler. + public const string HandlerKey = "handler"; + + private static readonly ConcurrentDictionary> Siblings = new(); + private static readonly ConcurrentDictionary Screens = new(); + + /// The handler name (?handler=name), or null for the default handler. + public PageHandlerAttribute(string? name = null) + { + Name = string.IsNullOrWhiteSpace(name) ? null : name; + } + + /// The handler name, or null for the default handler. + public string? Name { get; } + + /// + /// The handler a request asks for: the handler route value, else the handler query string value, else null. + /// + public static string? RequestedHandler(HttpContext httpContext, RouteData? routeData = null) + { + if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); + + if (routeData?.Values.TryGetValue(HandlerKey, out var value) == true && Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture) is { Length: > 0 } fromRoute) + { + return fromRoute; + } + + // Razor Pages takes the first value of a repeated key (StringValues.ToString would join them with commas). + var fromQuery = httpContext.Request.Query[HandlerKey].FirstOrDefault(); + + return string.IsNullOrEmpty(fromQuery) ? null : fromQuery; + } + + /// + public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action) + { + if (routeContext == null) throw new ArgumentNullException(nameof(routeContext)); + if (action == null) throw new ArgumentNullException(nameof(action)); + + var requested = RequestedHandler(routeContext.HttpContext, routeContext.RouteData); + + if (Name != null) + { + return string.Equals(Name, requested, StringComparison.OrdinalIgnoreCase); + } + + // The default handler: valid unless a sibling of the same screen that answers this HTTP method is named like the request. + // Only the same screen counts: a controller serving several screens must not let one screen's handler names knock out + // another screen's default handler (Razor Pages looked at one page's handlers). + if (requested == null || action is not ControllerActionDescriptor controllerAction) + { + return true; + } + + var verb = routeContext.HttpContext.Request.Method; + if (HttpMethods.IsHead(verb)) verb = HttpMethods.Get; + + // A descriptor built by hand may have no method: it then belongs to the whole controller. + var screen = controllerAction.MethodInfo is { } method ? ScreenOf(method) : string.Empty; + + return !Siblings.GetOrAdd(controllerAction.ControllerTypeInfo.AsType(), NamedHandlersOf) + .Any(h => (screen.Length == 0 || h.Screen.Length == 0 || h.Screen == screen) + && string.Equals(h.Name, requested, StringComparison.OrdinalIgnoreCase) + && (h.Verbs.Count == 0 || h.Verbs.Contains(verb, StringComparer.OrdinalIgnoreCase))); + } + + private static IReadOnlyList NamedHandlersOf(Type controller) + { + var result = new List(); + foreach (var method in controller.GetMethods(BindingFlags.Public | BindingFlags.Instance)) + { + var handler = method.GetCustomAttribute(); + if (handler?.Name == null) continue; + + var verbs = method.GetCustomAttributes(inherit: true).SelectMany(a => a.HttpMethods).ToList(); + result.Add(new NamedPageHandler(handler.Name, verbs, ScreenOf(method))); + } + + return result; + } + + /// + /// The screen an action belongs to: the route templates of its own attributes ([Route], [HttpGet("x")]), sorted and joined, which every + /// action of one screen shares (a screen's handlers post to its URL); the empty key when it names none (the controller's own route is its + /// only route, so the whole controller is one screen). An action with the empty key (a fallback such as PackageManageController.NoHandler) + /// is compared with every named handler of its controller, and a named handler with the empty key counts for every screen. + /// + internal static string ScreenOf(MethodInfo method) => Screens.GetOrAdd(method, m => string.Join( + "|", + m.GetCustomAttributes(inherit: true) + .OfType() + .Select(p => p.Template) + .Where(template => template != null) + .OrderBy(template => template, StringComparer.Ordinal))); +} diff --git a/src/BaGet.Api.Base/Mvc/Attributes/RepositoryPageAttribute.cs b/src/BaGet.Api.Base/Mvc/Attributes/RepositoryPageAttribute.cs new file mode 100644 index 000000000..d97c80e2b --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/RepositoryPageAttribute.cs @@ -0,0 +1,61 @@ +using System; +using BaGet.Core; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// Marks a controller action (or a whole controller) as a repository page: a page that acts on the request's +/// repository and is therefore served at its own route and at /r/{repo}/…, and that passes the single repository check +/// before the action runs. The marker is data on the action itself: +/// +/// RepositoryActionRouteConvention adds the r/{repo}/ twin of every route of the action +/// (Order -1, so a link that carries a repository resolves to it and one that does not resolves to the plain route). +/// RepositoryActionFilter requires Read on the repository (Deploy for an page), +/// on the package named by the id, group/artifact or image route values, answers 404 to a signed-in +/// caller who may not (a visitor who is not signed in is challenged, when the host has accounts), and applies the rules below. +/// Links inside the page keep the repository: RepositoryUrlHelper adds the request's repo to a +/// link to such an action. +/// +/// +/// +/// The check runs after the controller base's own OnActionExecutionAsync (the controller overrides run first, like a page +/// model's did), so a model check that must precede it keeps doing so. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RepositoryPageAttribute : Attribute +{ + /// The route value that carries the repository name on the /r/{repo}/ variant of a route. + public const string RouteKey = "repo"; + + /// + /// The format whose repositories the page belongs to (NuGet unless set). The page answers 404 in a repository of another + /// format; the NuGet front page () instead sends the visitor to the format's own browse page. + /// Ignored when is true. + /// + public RepositoryFormat Format { get; set; } = RepositoryFormat.NuGet; + + /// The page serves a repository of every format (it names an artifact generically): Scan now. + public bool AnyFormat { get; set; } + + /// + /// A virtual repository holds nothing of its own, so the page answers 404 there (statistics, abuse reports, the owner and + /// management tools, scanning). + /// + public bool NotOnVirtual { get; set; } + + /// A remote repository refuses every action of the page (publish, tags, owners), so the page answers 404 there. + public bool NotOnRemote { get; set; } + + /// + /// An upload page: the caller needs the right to publish (IRepositoryAccess.CanWriteAsync), not Read, so a + /// Deploy-only drop box is usable. In a virtual repository the request continues in its deploy repository + /// (RepositoryPageGate.RequestedVirtualItemKey remembers the virtual one for the view); without one it is 404. + /// + public bool Upload { get; set; } + + /// + /// The NuGet front page of a repository (/Index): in a repository of another format it redirects to that format's + /// browse link instead of answering 404. + /// + public bool FrontPage { get; set; } +} diff --git a/src/BaGet.Api.Base/Mvc/Attributes/RequiresEmailAttribute.cs b/src/BaGet.Api.Base/Mvc/Attributes/RequiresEmailAttribute.cs new file mode 100644 index 000000000..16bf33297 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/RequiresEmailAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// The action answers 404 while no mail is configured (the per-action form of AccountControllerBase.RequiresEmail, for a +/// controller whose screens do not all need it). +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RequiresEmailAttribute : Attribute +{ +} diff --git a/src/BaGet.Api.Base/Mvc/Attributes/RequiresSignInAttribute.cs b/src/BaGet.Api.Base/Mvc/Attributes/RequiresSignInAttribute.cs new file mode 100644 index 000000000..5793280b2 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/RequiresSignInAttribute.cs @@ -0,0 +1,13 @@ +using System; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// The action needs a signed-in user; a visitor is challenged (the per-action form of +/// AccountControllerBase.RequiresSignIn). Not [Authorize]: while accounts are disabled there is no scheme to +/// challenge with and the screen must answer 404 instead. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class RequiresSignInAttribute : Attribute +{ +} diff --git a/src/BaGet.Api.Base/Mvc/Attributes/UploadSizeLimitAttribute.cs b/src/BaGet.Api.Base/Mvc/Attributes/UploadSizeLimitAttribute.cs new file mode 100644 index 000000000..dc1f502fc --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Attributes/UploadSizeLimitAttribute.cs @@ -0,0 +1,20 @@ +using System; +using Microsoft.AspNetCore.Mvc; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// Raises the multipart limit for an action that receives a package or artifact file. The host keeps the limit of every other form +/// small (ConfigureBaGetOptions.DefaultFormLimit), because antiforgery validation buffers the whole form of any POST. +/// It is an authorization-stage filter (), so it applies before the antiforgery check +/// reads the form. +/// +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] +public sealed class UploadSizeLimitAttribute : RequestFormLimitsAttribute +{ + /// Allows files up to the request size the server accepts. + public UploadSizeLimitAttribute() + { + MultipartBodyLengthLimit = long.MaxValue; + } +} diff --git a/src/BaGet.Api.Base/Mvc/Screens/AccountSupport.cs b/src/BaGet.Api.Base/Mvc/Screens/AccountSupport.cs new file mode 100644 index 000000000..71b5aad5f --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Screens/AccountSupport.cs @@ -0,0 +1,76 @@ +using System; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Email; +using BaGet.Identity.Application.Links; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Security; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace BaGet.Frontend.Mvc.Screens; + +/// +/// The rules of the account screens used by the account controller base (AccountControllerBase), the use cases' link builder and the re-authentication state. +/// +internal static class AccountSupport +{ + /// How long a sign-in with the external provider counts as proof of presence for a sensitive action. + public static readonly TimeSpan ReauthenticationWindow = AccountConfirmation.ReauthenticationWindow; + + /// The sign-in cookie property that holds the time (ticks, UTC) of the last re-authentication. + public const string ReauthenticatedItem = AccountConfirmation.ReauthenticatedItem; + + /// + /// The check behind every sensitive action. An account with a password types it again; one without (external sign-in + /// only) must have signed in again with its provider a moment ago. The rule lives in . + /// + public static Task IsConfirmedAsync(UserManager users, HttpContext httpContext, BaGetUser? user, string? password) + => AccountConfirmation.IsConfirmedAsync(users, httpContext, user, password); + + /// Whether the session re-authenticated with the external provider within . + public static Task HasReauthenticatedRecentlyAsync(HttpContext httpContext) + => AccountConfirmation.HasReauthenticatedRecentlyAsync(httpContext); + + /// The URL to go to after a sign-in: when it is local, else the site root. + public static string LocalTarget(IUrlHelper url, string? returnUrl) + => !string.IsNullOrEmpty(returnUrl) && url.IsLocalUrl(returnUrl) ? returnUrl : url.Content("~/") ?? "/"; + + /// + /// An absolute link to an account screen, for an email. Built only from Site:PublicUrl, never from the request's host + /// or scheme: see . + /// + public static string AbsoluteLink(HttpContext httpContext, IUrlHelper url, ScreenRef screen, object values) + { + var site = httpContext.RequestServices.GetRequiredService>(); + var publicUrl = site.Value.PublicUrl; + + // Without the server-rendered screens (Frontend:Mvc=false, or Frontend:SpaLinks) the link targets the single-page application's route. + var spa = AccountLinks.ForScreen(site, screen, values); + if (spa != null) return spa; + + if (EmailLinkPolicy.TryParsePublicUrl(publicUrl, out var root)) + { + // The path includes the request's path base, which the public URL replaces. + var path = url.Action(screen.Action, screen.Controller, values) ?? string.Empty; + var pathBase = httpContext.Request.PathBase; + if (pathBase.HasValue && path.StartsWith(pathBase.Value, StringComparison.OrdinalIgnoreCase)) + { + path = path.Substring(pathBase.Value.Length); + } + + return root?.GetLeftPart(UriPartial.Path).TrimEnd('/') + path; + } + + throw new InvalidOperationException(EmailLinkPolicy.UnavailableWarning); + } + + /// Decodes a token written by PasswordResetLinkSender.EncodeToken, or null. + public static string? DecodeToken(string? code) => AccountConfirmation.DecodeToken(code); + + /// The messages of an identity failure as one sentence. + public static string Describe(IdentityResult result) => AccountConfirmation.Describe(result); +} diff --git a/src/BaGet.Api.Base/Mvc/Screens/ScreenLinks.cs b/src/BaGet.Api.Base/Mvc/Screens/ScreenLinks.cs new file mode 100644 index 000000000..9b2fec004 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/Screens/ScreenLinks.cs @@ -0,0 +1,34 @@ +using System; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.Routing; + +namespace BaGet.Frontend.Mvc.Screens; + +/// +/// for the MVC screens: resolves a screen (controller and action) with the request's +/// URL helper, and builds the absolute address from Site:PublicUrl only (). +/// +internal sealed class ScreenLinks : IScreenLinks +{ + private readonly IHttpContextAccessor _http; + private readonly IUrlHelperFactory _factory; + + public ScreenLinks(IHttpContextAccessor http, IUrlHelperFactory factory) + { + _http = http ?? throw new ArgumentNullException(nameof(http)); + _factory = factory ?? throw new ArgumentNullException(nameof(factory)); + } + + /// + public string AbsoluteLink(ScreenRef screen, object values) + { + var context = _http.HttpContext ?? throw new InvalidOperationException("A link to a screen is built while a request is being served."); + var url = _factory.GetUrlHelper(new ActionContext(context, context.GetRouteData(), new ActionDescriptor())); + + return AccountSupport.AbsoluteLink(context, url, screen, values); + } +} diff --git a/src/BaGet.Api.Base/Mvc/UI/IScreenController.cs b/src/BaGet.Api.Base/Mvc/UI/IScreenController.cs new file mode 100644 index 000000000..766b306e2 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/IScreenController.cs @@ -0,0 +1,10 @@ +namespace BaGet.Frontend.Mvc.UI; + +/// +/// Marks a controller as a view controller of the web UI (a screen). The API assemblies cannot see the front-end base class, so +/// tells a screen action from every other endpoint by this marker, which the front-end base +/// (UiControllerBase) implements; the JSON twins under /api/ui never do. +/// +public interface IScreenController +{ +} diff --git a/src/BaGet.Api.Base/Mvc/UI/ScreenEndpoints.cs b/src/BaGet.Api.Base/Mvc/UI/ScreenEndpoints.cs new file mode 100644 index 000000000..78949df5b --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/ScreenEndpoints.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Reflection; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Routing; + +namespace BaGet.Frontend.Mvc.UI; + +/// +/// Tells the endpoints of BaGet's own web UI from every other endpoint and names the screen an action belongs to. A screen is an action of +/// a controller implementing (the view controllers, derived from UiControllerBase; the JSON twins under /api/ui derive from +/// ApiControllerBase, never from it) other than a fallback. The screen is identified by +/// the controller and the action that answers a plain GET for it (); the actions of one screen are those of the +/// controller that share its route templates (: handlers post to the screen's own URL). +/// +public static class ScreenEndpoints +{ + private const string ControllerSuffix = "Controller"; + + private static readonly ConcurrentDictionary Screens = new(); + + /// Whether belongs to a screen of the web UI. + public static bool IsScreen(ActionDescriptor? action) + => action is ControllerActionDescriptor controller + && typeof(IScreenController).IsAssignableFrom(controller.ControllerTypeInfo.AsType()) + && controller.MethodInfo.GetCustomAttribute(inherit: true) == null; + + /// Whether is an action of a screen of the web UI. + public static bool IsScreen(Endpoint? endpoint) + => endpoint?.Metadata.OfType().Any(a => IsScreen(a)) == true; + + /// + /// The screen belongs to (the screen itself for its GET, a handler of it for a named handler), or null when it is + /// no screen action (see ) or its screen has no GET action answering without a handler. + /// + public static ScreenRef? ScreenOf(ActionDescriptor? action) + => IsScreen(action) ? ScreenOf(((ControllerActionDescriptor)action!).MethodInfo, ((ControllerActionDescriptor)action).ControllerTypeInfo.AsType()) : null; + + /// The screen of the current endpoint, or null when the endpoint is no screen action. + public static ScreenRef? ScreenOf(Endpoint? endpoint) + => endpoint?.Metadata.OfType().Select(a => ScreenOf(a)).FirstOrDefault(s => s != null); + + private static ScreenRef? ScreenOf(MethodInfo method, Type controller) => Screens.GetOrAdd(method, m => + { + var key = PageHandlerAttribute.ScreenOf(m); + var page = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance) + .Where(c => c.GetCustomAttribute(inherit: true) == null + && (key.Length == 0 || PageHandlerAttribute.ScreenOf(c) == key) + && IsDefaultGet(c)) + .OrderBy(c => c.Name, StringComparer.Ordinal) + .FirstOrDefault(); + if (page == null) return null; + + var name = controller.Name; + if (name.EndsWith(ControllerSuffix, StringComparison.Ordinal)) name = name.Substring(0, name.Length - ControllerSuffix.Length); + + return new ScreenRef(name, page.GetCustomAttribute()?.Name ?? page.Name); + }); + + // The action that answers a plain GET: GET (or HEAD) with no named handler. + private static bool IsDefaultGet(MethodInfo method) + { + var verbs = method.GetCustomAttributes(inherit: true).SelectMany(a => a.HttpMethods).ToList(); + + return verbs.Contains("GET", StringComparer.OrdinalIgnoreCase) + && method.GetCustomAttribute(inherit: true)?.Name == null; + } +} diff --git a/src/BaGet.Api.Base/Mvc/UI/UiApiAttribute.cs b/src/BaGet.Api.Base/Mvc/UI/UiApiAttribute.cs new file mode 100644 index 000000000..02c185cf2 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/UiApiAttribute.cs @@ -0,0 +1,38 @@ +using System; +using BaGet.Identity.Application.Screens; + +namespace BaGet.Frontend.Mvc.UI; + +/// +/// Marks a controller action of /api/ui as the JSON twin of a screen: [UiApi("AdminUsers", "Index")] names the screen by the +/// view controller (without the Controller suffix) and the default GET action that serve it (), and the +/// ?handler= it mirrors (null = the screen itself). The view controllers live in the front-end assemblies the API cannot reference, so the +/// screen is a name that ScreenCatalogTests resolves against them. The attribute is data for the parity and coverage tests and for the OpenAPI +/// document; a twin is never a view controller, so the route snapshot of the screens (ui-routes.txt) does not see the API. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class UiApiAttribute : Attribute +{ + /// The view controller of the screen this action serves, without the suffix ("AdminUsers"). + /// The action of that controller that shows the screen ("Index"). + public UiApiAttribute(string controller, string action) + { + if (string.IsNullOrWhiteSpace(controller)) throw new ArgumentException("A screen names its controller.", nameof(controller)); + if (string.IsNullOrWhiteSpace(action)) throw new ArgumentException("A screen names its action.", nameof(action)); + + Controller = controller; + Action = action; + } + + /// The view controller of the screen this action serves, without the Controller suffix. + public string Controller { get; } + + /// The action of the view controller that shows the screen. + public string Action { get; } + + /// The screen this action serves, as asp-controller/asp-action name it. + public ScreenRef Screen => new(Controller, Action); + + /// The page handler this action mirrors (Approve for ?handler=Approve), or null for the screen itself (GET) or its default POST. + public string? Handler { get; set; } +} diff --git a/src/BaGet.Api.Base/Mvc/UI/UiApiCaller.cs b/src/BaGet.Api.Base/Mvc/UI/UiApiCaller.cs new file mode 100644 index 000000000..e4bb97ff1 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/UiApiCaller.cs @@ -0,0 +1,110 @@ +using System; +using System.Security.Claims; +using BaGet.Core; +using BaGet.Frontend.Security; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Sessions; +using Microsoft.AspNetCore.Http; + +namespace BaGet.Frontend.Mvc.UI; + +/// +/// Who calls /api/ui over HTTP: an API key sent as Authorization: Bearer or X-NuGet-ApiKey (headers a web page cannot make a browser +/// send), a person's interactive session (a session token as Authorization: Bearer bgs.xxx, or the browser cookie accompanied by a valid antiforgery +/// header), or nobody. The cookie alone is never a credential here and neither is HTTP Basic (browsers cache Basic credentials and re-send them on +/// cross-site requests). decides and records it here; User is then the key's owner (or anonymous), so the gate +/// and the services see one kind of caller. The in-process call of a view controller does not pass through the filter: it has its own cookie session. +/// +public static class UiApiCaller +{ + private const string KeyItem = "BaGet.UiApi.Key"; + + /// The header that carries the antiforgery request token when the cookie session is used on /api/ui (GET /api/ui/antiforgery hands it out). + public const string AntiforgeryHeader = "X-XSRF-TOKEN"; + + private const string CookieUserItem = "BaGet.UiApi.CookieUser"; + + /// + /// The interactive session that authenticated the request (a session token, or the cookie session with a valid antiforgery header), or null. + /// An API key is never one: it is . + /// + public static BaGetPrincipal? Interactive(HttpContext context) + => context.Items.TryGetValue(RequestPrincipalResolver.InteractiveItem, out var session) ? session as BaGetPrincipal : null; + + /// The cookie session's user the request arrived with, before the filter decided the caller (so the antiforgery token can be issued for it), or null. + internal static System.Security.Claims.ClaimsPrincipal? CookieUser(HttpContext context) + => context.Items.TryGetValue(CookieUserItem, out var user) ? user as ClaimsPrincipal : null; + + internal static void RememberCookieUser(HttpContext context) + { + if (context.User.Identity?.IsAuthenticated == true) context.Items[CookieUserItem] = context.User; + } + + /// + /// A person's session authenticated the request. A session token ( set) replaces the cookie entirely; the cookie + /// (already validated with its antiforgery header) keeps User and stays readable for the re-authentication proof. + /// + internal static void SetInteractive(HttpContext context, ClaimsPrincipal user, BaGetPrincipal principal, DateTime? authenticatedAt) + { + RequestPrincipalResolver.Forget(context); + context.Items[RequestPrincipalResolver.InteractiveItem] = principal; + context.User = user; + + if (authenticatedAt != null) + { + context.Items[AccountConfirmation.IgnoreSessionItem] = true; + context.Items[AccountConfirmation.SessionAuthenticatedItem] = authenticatedAt.Value; + } + } + + /// The API key that authenticated the request, or null for an anonymous caller. + public static BaGetPrincipal? Key(HttpContext context) + => context.Items.TryGetValue(KeyItem, out var key) ? key as BaGetPrincipal : null; + + internal static void SetKey(HttpContext context, BaGetPrincipal key) + { + RememberCookieUser(context); + context.Items[KeyItem] = key; + MarkSessionIgnored(context); + + // The owner acts: User carries the key owner's id and name, as a session's does. The global key has no owner. + var identity = new ClaimsIdentity("BaGetApiKey", ClaimTypes.Name, ClaimTypes.Role); + if (key.UserId != null) identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, key.UserId)); + if (key.UserName != null) identity.AddClaim(new Claim(ClaimTypes.Name, key.UserName)); + context.User = new ClaimsPrincipal(identity); + } + + /// + /// An anonymous caller: whatever the cookie authentication put in User is dropped, the request's resolved principal is forgotten and the + /// request is marked so that nothing re-reads the session cookie (). + /// + internal static void SetAnonymous(HttpContext context) + { + RememberCookieUser(context); + MarkSessionIgnored(context); + context.User = new ClaimsPrincipal(new ClaimsIdentity()); + } + + private static void MarkSessionIgnored(HttpContext context) + { + context.Items[AccountConfirmation.IgnoreSessionItem] = true; + RequestPrincipalResolver.Forget(context); + } + + /// Whether the request carries an HTTP Basic Authorization header (not accepted on /api/ui). + public static bool HasBasicCredentials(HttpRequest request) + => request.Headers.Authorization.ToString().StartsWith("Basic", System.StringComparison.OrdinalIgnoreCase); + + /// Whether the request carries an API key or a session token in an accepted header (Bearer or X-NuGet-ApiKey). + public static bool HasKeyCredentials(HttpRequest request) + => BasicCredentials.ReadBearer(request) != null + || !string.IsNullOrEmpty(request.Headers[RequestPrincipalResolver.ApiKeyHeader].ToString()); + + /// The session token of the request's Authorization: Bearer header, or null (an API key, or none). + public static string? SessionTokenOf(HttpRequest request) + { + var bearer = BasicCredentials.ReadBearer(request); + + return SessionTokenService.IsSessionToken(bearer) ? bearer : null; + } +} diff --git a/src/BaGet.Api.Base/Mvc/UI/UiApiEntry.cs b/src/BaGet.Api.Base/Mvc/UI/UiApiEntry.cs new file mode 100644 index 000000000..855048e40 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/UiApiEntry.cs @@ -0,0 +1,40 @@ +using System; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Mvc.UI; + +/// +/// The in-process call of a twin's entry check: a screen whose first step (ownership, a Delete permission, a valid name) must run +/// before the global repository filter, as it did on the page, asks it from OnActionExecutionAsync of its view controller. The twin +/// exposes the step as a [NonAction] method returning the refusal, or null to go on; the use case remembers the answer for the +/// request, so the operation that follows does not repeat the work. Same rules as UiApiInvoker: the twin shares the +/// view action's , its own filters do not run. +/// +public static class UiApiEntry +{ + /// Calls on a new that shares the caller's context; null means "go on". + /// The twin controller. + /// The screen's model. + /// The view controller. + /// The twin's entry check. + /// The refusal as a response the view controller renders, or null when the check passed. + public static async Task?> InvokeAsync( + ControllerBase caller, + Func?>> enter) + where TApi : ApiControllerBase + { + if (caller == null) throw new ArgumentNullException(nameof(caller)); + if (enter == null) throw new ArgumentNullException(nameof(enter)); + + var api = ActivatorUtilities.CreateInstance(caller.HttpContext.RequestServices); + api.ControllerContext = caller.ControllerContext; + + var refusal = await enter(api).ConfigureAwait(false); + + return refusal == null ? null : new UiApiResponse(refusal, null); + } +} diff --git a/src/BaGet.Api.Base/Mvc/UI/UiApiResponse.cs b/src/BaGet.Api.Base/Mvc/UI/UiApiResponse.cs new file mode 100644 index 000000000..f1a392480 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/UiApiResponse.cs @@ -0,0 +1,24 @@ +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; + +namespace BaGet.Frontend.Mvc.UI; + +/// What the in-process call of a JSON twin produced: its , or the plain action result it answered with. +/// The screen's model. +public sealed class UiApiResponse +{ + internal UiApiResponse(ScreenResult screen, IActionResult? raw) + { + Screen = screen; + Raw = raw; + } + + /// The decision (for a plain action result, the one it stands for: 404 is not found, 401 sign in, 403 forbidden). + public ScreenResult Screen { get; } + + /// + /// The action result the twin returned when it was not a (NotFound(), Forbid(), Challenge(), + /// a status code): a view controller returns it unchanged, so the answer is the one the twin gave. + /// + public IActionResult? Raw { get; } +} diff --git a/src/BaGet.Api.Base/Mvc/UI/UiApiResult.cs b/src/BaGet.Api.Base/Mvc/UI/UiApiResult.cs new file mode 100644 index 000000000..8887780ab --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/UiApiResult.cs @@ -0,0 +1,62 @@ +using System; +using System.Threading.Tasks; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Formatters; +using Microsoft.Net.Http.Headers; + +namespace BaGet.Frontend.Mvc.UI; + +/// +/// The HTTP answer of a on /api/ui: always application/json written with +/// (camelCase, enums by name), with the status the decision maps to (or the screen's own when it sets one, e.g. 409 for a refused scan): Ok and Next 200, Invalid 400 (the body +/// still carries the model and the errors), NotFound 404, Forbidden 403, SignIn 401 with a Bearer challenge (not Basic, which +/// would make a browser prompt for a password on a fetch). A shown screen that carries its own status () is answered with it. A maintenance refusal is not a result: it propagates and the middleware answers 503. +/// +/// The in-process call of a view controller never executes it: UiApiInvoker reads . +/// +/// +public sealed class UiApiResult : ObjectResult +{ + private readonly IScreenResult _screen; + + /// Creates the answer for . + public UiApiResult(IScreenResult screen) + : base(screen) + { + _screen = screen ?? throw new ArgumentNullException(nameof(screen)); + StatusCode = StatusOf(screen); + ContentTypes.Add("application/json"); + Formatters.Add(new SystemTextJsonOutputFormatter(UiApiJson.Options)); + DeclaredType = screen.GetType(); + } + + /// + /// The HTTP status of a result: the status its screen renders with when the result sets one for a shown screen (, + /// : an upload refused with 403, a package page that explains a missing package with 404), else the one of its decision. + /// + public static int StatusOf(IScreenResult screen) + => screen.StatusCode is { } code && screen.Status is ScreenStatus.Ok or ScreenStatus.Invalid ? code : StatusOf(screen.Status); + + /// The HTTP status of a decision. + public static int StatusOf(ScreenStatus status) => status switch + { + ScreenStatus.Invalid => StatusCodes.Status400BadRequest, + ScreenStatus.NotFound => StatusCodes.Status404NotFound, + ScreenStatus.Forbidden => StatusCodes.Status403Forbidden, + ScreenStatus.SignIn => StatusCodes.Status401Unauthorized, + _ => StatusCodes.Status200OK, + }; + + /// + public override Task ExecuteResultAsync(ActionContext context) + { + if (StatusCode == StatusCodes.Status401Unauthorized) + { + context.HttpContext.Response.Headers[HeaderNames.WWWAuthenticate] = "Bearer realm=\"BaGet\""; + } + + return base.ExecuteResultAsync(context); + } +} diff --git a/src/BaGet.Api.Base/Mvc/UI/UiApiSecurityFilter.cs b/src/BaGet.Api.Base/Mvc/UI/UiApiSecurityFilter.cs new file mode 100644 index 000000000..aeba3f4f8 --- /dev/null +++ b/src/BaGet.Api.Base/Mvc/UI/UiApiSecurityFilter.cs @@ -0,0 +1,172 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using BaGet.Frontend.Mvc.Attributes; +using Microsoft.Extensions.Options; +using BaGet.Core; +using BaGet.Frontend.Security; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Sessions; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Mvc.UI; + +/// +/// Authenticates a request to /api/ui over HTTP before any action runs. The credentials, in order: +/// +/// A session token (Authorization: Bearer bgs.xxx, issued by POST /api/ui/session): the signed-in user, with the rights of their +/// cookie session ( re-checks the account and its security stamp). Only this API accepts it. An invalid or expired one is 401. +/// An API key (Authorization: Bearer or X-NuGet-ApiKey, resolved by ): the key's owner +/// acts within the key's scopes and repository limits. A key that does not authenticate is 401 (not read as "anonymous"). +/// HTTP Basic is refused with 401: browsers cache Basic credentials after a Basic challenge and re-send them on cross-site requests. +/// The browser session cookie, only for a same-origin client that also sends a valid antiforgery request token in the +/// header (GET /api/ui/antiforgery), for every method. A cross-site page can neither read the token nor set the header. +/// Without a valid token the cookie is ignored. +/// No credentials: anonymous. User is reset to an anonymous principal and the request is marked so that no later code re-reads the cookie. +/// An open server (accounts off, no ApiKey) accepts anonymous uploads, so a cross-site form can post one, as it can to the protocol routes. +/// +/// In-process calls of a view controller do not pass through here: the view action has its own antiforgery validation and its own cookie session. +/// +public sealed class UiApiSecurityFilter : IAsyncAuthorizationFilter +{ + /// + public async Task OnAuthorizationAsync(AuthorizationFilterContext context) + { + var http = context.HttpContext; + http.Items[AccountConfirmation.OverHttpItem] = true; + + var endpoint = context.ActionDescriptor.EndpointMetadata.OfType().LastOrDefault(); + if (endpoint != null && !OriginAllowed(http, endpoint)) + { + context.Result = new UiApiResult(ScreenResult.Forbidden( + "A request from another origin cannot use this endpoint: serve the application from this server's origin, or list its origin in Cors:AllowedOrigins.")); + return; + } + + if (UiApiCaller.HasBasicCredentials(http.Request)) + { + context.Result = new UiApiResult(ScreenResult.SignIn( + "HTTP Basic is not accepted on /api/ui: send the API key as 'Authorization: Bearer ' or in the 'X-NuGet-ApiKey' header, or a session token.")); + return; + } + + var sessionToken = UiApiCaller.SessionTokenOf(http.Request); + if (sessionToken != null) + { + var authenticator = http.RequestServices.GetService(); + var session = authenticator == null ? null : await authenticator.AuthenticateAsync(SessionTokenKind.Access, sessionToken); + if (session == null && endpoint != null) + { + // The endpoints that give a session out: an expired header must not stop a refresh or a sign-in. + await AnonymousAsync(context, endpoint); + return; + } + + if (session == null) + { + context.Result = new UiApiResult(ScreenResult.SignIn("The session token has expired or is not valid: refresh it or sign in again.")); + return; + } + + UiApiCaller.RememberCookieUser(http); + UiApiCaller.SetInteractive(http, session.User, session.Principal, session.AuthenticatedAt); + return; + } + + if (!UiApiCaller.HasKeyCredentials(http.Request)) + { + if (await TryCookieSessionAsync(http)) return; + + await AnonymousAsync(context, endpoint); + return; + } + + var resolver = http.RequestServices.GetService(); + var key = resolver == null ? null : await resolver.ResolveForWriteAsync(http, http.RequestAborted); + if (key == null) + { + context.Result = new UiApiResult(ScreenResult.SignIn("The API key is not valid.")); + return; + } + + UiApiCaller.SetKey(http, key); + } + + // No credential: anonymous. An endpoint that signs a visitor in with the cookie also needs the antiforgery token of an anonymous visitor (no login CSRF). + private static async Task AnonymousAsync(AuthorizationFilterContext context, AnonymousSessionEndpointAttribute? endpoint) + { + var http = context.HttpContext; + UiApiCaller.SetAnonymous(http); + + if (endpoint is { RequireAntiforgery: true } && !await IsAntiforgeryValidAsync(http)) + { + context.Result = new UiApiResult(ScreenResult.Forbidden("A valid antiforgery token is required: send the token of GET /api/ui/antiforgery in the X-XSRF-TOKEN header.")); + } + } + + private static async Task IsAntiforgeryValidAsync(Microsoft.AspNetCore.Http.HttpContext http) + { + var antiforgery = http.RequestServices.GetService(); + if (antiforgery == null || string.IsNullOrEmpty(http.Request.Headers[UiApiCaller.AntiforgeryHeader].ToString())) return false; + + try + { + await antiforgery.ValidateRequestAsync(http); + + return true; + } + catch (AntiforgeryValidationException) + { + return false; + } + } + + // A browser sends Origin on a cross-origin request and on every POST; a request without it (a script, a navigation) is not a cross-origin browser call. + private static bool OriginAllowed(Microsoft.AspNetCore.Http.HttpContext http, AnonymousSessionEndpointAttribute endpoint) + { + var origin = http.Request.Headers.Origin.ToString(); + if (string.IsNullOrEmpty(origin)) return true; + + var own = http.Request.Scheme + "://" + http.Request.Host; + if (string.Equals(origin.TrimEnd('/'), own, StringComparison.OrdinalIgnoreCase)) return true; + + // Behind a TLS proxy whose X-Forwarded-Proto is not trusted the request looks like http: the public URL of the site is this server's origin too. + if (Uri.TryCreate(http.RequestServices.GetService>()?.Value.PublicUrl, UriKind.Absolute, out var publicUrl) + && string.Equals(origin.TrimEnd('/'), publicUrl.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase)) return true; + if (endpoint.SameOriginOnly) return false; + + var listed = SessionReturnUrls.Origins(http.RequestServices.GetService>()?.Value.AllowedOrigins); + + return listed.Any(allowed => string.Equals(allowed, origin.TrimEnd('/'), StringComparison.OrdinalIgnoreCase)); + } + + // The cookie session, accepted only together with a valid antiforgery token in the header (for every method). + private static async Task TryCookieSessionAsync(Microsoft.AspNetCore.Http.HttpContext http) + { + if (http.User.Identity?.IsAuthenticated != true || string.IsNullOrEmpty(http.Request.Headers[UiApiCaller.AntiforgeryHeader].ToString())) return false; + + // ValidateRequestAsync, not IsRequestValidAsync: that one answers "valid" for GET, HEAD and OPTIONS, and the cookie needs the token for every method. + var antiforgery = http.RequestServices.GetService(); + if (antiforgery == null) return false; + + try + { + await antiforgery.ValidateRequestAsync(http); + } + catch (AntiforgeryValidationException) + { + return false; + } + + var sessions = http.RequestServices.GetService(); + var principal = sessions == null ? null : await sessions.CreateAsync(http.User); + if (principal == null) return false; + + UiApiCaller.SetInteractive(http, http.User, principal, authenticatedAt: null); + + return true; + } +} diff --git a/src/BaGet.Api.Base/README.md b/src/BaGet.Api.Base/README.md new file mode 100644 index 000000000..18bd37d37 --- /dev/null +++ b/src/BaGet.Api.Base/README.md @@ -0,0 +1,28 @@ +# Extension.BaGet.Api.Base + +The base of the web APIs of [BaGet Extension](https://pieroviano.github.io/BaGet/): the `/api/ui` JSON twin bases and what both the APIs and the +screens need. No view controller, no view. `Extension.BaGet.Identity.Api` and `Extension.BaGet.Web.V3` reference it; so does `Extension.BaGet.Frontend.Base`. + +```powershell +dotnet add package Extension.BaGet.Api.Base +``` + +## Contents + +| Folder / type | Role | +|---|---| +| `Controllers/Base/ApiControllerBase` and `AccountApiControllerBase`, `AdminApiControllerBase`, `AccessApiControllerBase` | Bases of the JSON twins (`/api/ui`, see [UI API](https://pieroviano.github.io/BaGet/ui-api/)); visible in the OpenAPI `ui` document | +| `Mvc/Attributes` | `PageHandlerAttribute` (`?handler=` selector), `FallbackHandlerAttribute`, `RepositoryPageAttribute` (`/r/{repo}/` twin routes and the repository check), `RequiresSignInAttribute`, `RequiresEmailAttribute` | +| `Mvc/UI/UiApiAttribute` | `[UiApi("AdminUsers", "Index", Handler = ...)]` names the screen (controller without the suffix, default GET action) a twin mirrors; `ScreenCatalogTests` resolves the names against the front-end assemblies | +| `Mvc/UI/IScreenController`, `ScreenEndpoints` | The marker `UiControllerBase` implements, and whether an action is a screen and which one (`ScreenRef`) | +| `Mvc/UI` (`UiApiSecurityFilter`, `UiApiCaller`, `UiApiEntry`, `UiApiResult`, `UiApiResponse`) | `/api/ui` over HTTP: API keys only (Bearer or `X-NuGet-ApiKey`); no cookie, no Basic, no antiforgery | +| `Mvc/Screens` (`ScreenLinks`, `AccountSupport`) | Absolute screen links for emails, account re-authentication rules | +| `Security` | `RequestPrincipalResolver`, `BasicCredentials`, `HttpReauthenticationState` | + +## Layout + +One type per file, no nested types, namespace = `BaGet.Frontend` + folder (`CodeLayoutTests`; the namespace the types had in `Extension.BaGet.Frontend.Base`). + +## Links + +[UI API](https://pieroviano.github.io/BaGet/ui-api/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Api.Base/Security/BasicCredentials.cs b/src/BaGet.Api.Base/Security/BasicCredentials.cs new file mode 100644 index 000000000..d30e8d14b --- /dev/null +++ b/src/BaGet.Api.Base/Security/BasicCredentials.cs @@ -0,0 +1,57 @@ +using System; +using System.Text; +using Microsoft.AspNetCore.Http; + +namespace BaGet.Frontend.Security; + +/// +/// Credentials sent with Authorization: Basic, which is what NuGet clients (dotnet, nuget.exe, Visual Studio, +/// PowerShellGet) send to a feed that answered 401 with WWW-Authenticate: Basic. +/// +public static class BasicCredentials +{ + /// The challenge a protected feed answers anonymous callers with. + public const string Challenge = "Basic realm=\"BaGet\", charset=\"UTF-8\""; + + /// The challenge an npm route adds: npm clients send Authorization: Bearer {_authToken}. + public const string BearerChallenge = "Bearer realm=\"BaGet\""; + + /// + /// The token of an Authorization: Bearer header (what npm sends for _authToken), or null. The token is an + /// API key, like the password of Basic credentials. + /// + public static string? ReadBearer(HttpRequest request) + { + var header = request.Headers.Authorization.ToString(); + const string scheme = "Bearer "; + if (!header.StartsWith(scheme, StringComparison.OrdinalIgnoreCase)) return null; + + var token = header.Substring(scheme.Length).Trim(); + + return token.Length == 0 ? null : token; + } + + /// + /// The user name and password of the request's Basic credentials, or null when it carries none (or malformed ones). + /// The password is an API key; the user name is the key owner's, or anything for the global key. + /// + public static (string UserName, string Password)? Read(HttpRequest request) + { + var header = request.Headers.Authorization.ToString(); + const string scheme = "Basic "; + if (!header.StartsWith(scheme, StringComparison.OrdinalIgnoreCase)) return null; + + try + { + var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(header.Substring(scheme.Length).Trim())); + var colon = decoded.IndexOf(':'); + if (colon < 0) return null; + + return (decoded.Substring(0, colon), decoded.Substring(colon + 1)); + } + catch (FormatException) + { + return null; + } + } +} diff --git a/src/BaGet.Api.Base/Security/HttpReauthenticationState.cs b/src/BaGet.Api.Base/Security/HttpReauthenticationState.cs new file mode 100644 index 000000000..a861e20e9 --- /dev/null +++ b/src/BaGet.Api.Base/Security/HttpReauthenticationState.cs @@ -0,0 +1,27 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Identity.Application.UseCases.Account; +using Microsoft.AspNetCore.Http; + +namespace BaGet.Frontend.Security; + +/// +/// over the request's sign-in cookie: whether the session re-authenticated with the external +/// provider within . Without a request (or a cookie) the answer is false. +/// +internal sealed class HttpReauthenticationState : IReauthenticationState +{ + private readonly IHttpContextAccessor _accessor; + + public HttpReauthenticationState(IHttpContextAccessor accessor) + { + _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor)); + } + + public Task HasReauthenticatedRecentlyAsync(CancellationToken cancellationToken) + => _accessor.HttpContext == null + ? Task.FromResult(false) + : AccountSupport.HasReauthenticatedRecentlyAsync(_accessor.HttpContext); +} diff --git a/src/BaGet.Api.Base/Security/RequestPrincipalResolver.cs b/src/BaGet.Api.Base/Security/RequestPrincipalResolver.cs new file mode 100644 index 000000000..db30a68fa --- /dev/null +++ b/src/BaGet.Api.Base/Security/RequestPrincipalResolver.cs @@ -0,0 +1,127 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Sessions; +using Microsoft.AspNetCore.Http; +using IAuthenticationService = BaGet.Core.IAuthenticationService; + +namespace BaGet.Frontend.Security; + +/// +/// Who is calling: the principal behind the request's credentials, for the read checks. Credentials are, in order, the +/// password of Authorization: Basic (an API key; the user name must be the key owner's when the key belongs to a +/// user), the token of Authorization: Bearer (an API key too: what npm sends), the X-NuGet-ApiKey header, +/// then the browser session. A write () never uses the session: a cookie is sent by a +/// browser on its own, so accepting it would let any web page make the user's browser publish or delete. Credentials that do not authenticate are the same +/// as none: a repository that is open to everyone stays readable, one that is not answers 401. +/// +public class RequestPrincipalResolver +{ + /// The header NuGet clients send an API key in. + internal const string ApiKeyHeader = "X-NuGet-ApiKey"; + + /// + /// The key under which /api/ui records the interactive session that authenticated the request (a session token, + /// or the cookie with a valid antiforgery header). Only the UI API filter sets it, so no other route ever sees a session token as a credential: there + /// a token () is an invalid key. + /// + internal const string InteractiveItem = AccountConfirmation.InteractiveSessionItem; + + private const string ItemKey = "BaGet.RequestPrincipal"; + private const string WriteItemKey = "BaGet.RequestWritePrincipal"; + + private readonly IAuthenticationService _authentication; + private readonly ISessionPrincipalFactory? _sessions; + + public RequestPrincipalResolver(IAuthenticationService authentication, ISessionPrincipalFactory? sessions = null) + { + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _sessions = sessions; + } + + /// Drops what was resolved for the request so far (used when the request's credentials are decided afterwards, as on /api/ui). + internal static void Forget(HttpContext context) + { + context.Items.Remove(ItemKey); + context.Items.Remove(WriteItemKey); + } + + /// The caller, or null when anonymous. Resolved once per request. + public async Task ResolveAsync(HttpContext context, CancellationToken cancellationToken) + { + if (context.Items.TryGetValue(InteractiveItem, out var interactive) && interactive is BaGetPrincipal session) return session; + if (context.Items.TryGetValue(ItemKey, out var cached)) return cached as BaGetPrincipal; + + var principal = await ResolveCoreAsync(context, cancellationToken).ConfigureAwait(false); + context.Items[ItemKey] = principal; + return principal; + } + + /// + /// The caller of a write (npm publish, tag, deprecate, unpublish), or null when its credentials do not authenticate: + /// the API key sent as Basic password, Bearer token or X-NuGet-ApiKey, as for NuGet's write routes, and never the + /// browser session. An open server (no global key, accounts off) authenticates a request with no credentials as the + /// superuser, as it always did. Resolved once per request. + /// + public async Task ResolveForWriteAsync(HttpContext context, CancellationToken cancellationToken) + { + if (context.Items.TryGetValue(InteractiveItem, out var interactive) && interactive is BaGetPrincipal session) return session; + if (context.Items.TryGetValue(WriteItemKey, out var cached)) return cached as BaGetPrincipal; + + var basic = BasicCredentials.Read(context.Request); + var key = KeyOf(context, basic); + + // A session token is not an API key: outside /api/ui (which resolved it before) it is simply not a credential. + if (SessionTokenService.IsSessionToken(key)) + { + context.Items[WriteItemKey] = null; + + return null; + } + + var principal = await _authentication.AuthenticatePrincipalAsync(key, cancellationToken).ConfigureAwait(false); + if (principal != null && UserMismatch(principal, basic)) principal = null; + + context.Items[WriteItemKey] = principal; + return principal; + } + + private static string? KeyOf(HttpContext context, (string UserName, string Password)? basic) + { + var key = basic?.Password; + if (string.IsNullOrEmpty(key)) key = BasicCredentials.ReadBearer(context.Request); + if (string.IsNullOrEmpty(key)) key = context.Request.Headers[ApiKeyHeader]; + + return key; + } + + private static bool UserMismatch(BaGetPrincipal principal, (string UserName, string Password)? basic) + { + var userName = basic?.UserName; + + return !string.IsNullOrEmpty(userName) + && principal.UserName != null + && !string.Equals(userName, principal.UserName, StringComparison.OrdinalIgnoreCase); + } + + private async Task ResolveCoreAsync(HttpContext context, CancellationToken cancellationToken) + { + var basic = BasicCredentials.Read(context.Request); + var key = KeyOf(context, basic); + + if (!string.IsNullOrEmpty(key) && !SessionTokenService.IsSessionToken(key)) + { + var principal = await _authentication.AuthenticatePrincipalAsync(key, cancellationToken).ConfigureAwait(false); + if (principal != null && !UserMismatch(principal, basic)) return principal; + } + + if (_sessions != null && context.User.Identity?.IsAuthenticated == true) + { + return await _sessions.CreateAsync(context.User).ConfigureAwait(false); + } + + return null; + } +} diff --git a/src/BaGet.Aws/AwsApplicationExtensions.cs b/src/BaGet.Aws/AwsApplicationExtensions.cs index 6b07f8682..13fecdec8 100644 --- a/src/BaGet.Aws/AwsApplicationExtensions.cs +++ b/src/BaGet.Aws/AwsApplicationExtensions.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; using Amazon; using Amazon.Runtime; +using Amazon.Runtime.Credentials; using Amazon.S3; using BaGet.Aws; using BaGet.Core; @@ -9,88 +10,92 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class AwsApplicationExtensions { - public static class AwsApplicationExtensions + public static BaGetApplication AddAwsS3Storage(this BaGetApplication app) { - public static BaGetApplication AddAwsS3Storage(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("AwsS3")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasStorageType("AwsS3")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - app.Services.AddSingleton(provider => + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; + + var config = new AmazonS3Config { - var options = provider.GetRequiredService>().Value; - - var config = new AmazonS3Config - { - RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region) - }; - - if (options.UseInstanceProfile) - { - var credentials = FallbackCredentialsFactory.GetCredentials(); - return new AmazonS3Client(credentials, config); - } - - if (!string.IsNullOrEmpty(options.AssumeRoleArn)) - { - var credentials = FallbackCredentialsFactory.GetCredentials(); - var assumedCredentials = AssumeRoleAsync( - credentials, - options.AssumeRoleArn, - $"BaGet-Session-{Guid.NewGuid()}") - .GetAwaiter() - .GetResult(); - - return new AmazonS3Client(assumedCredentials, config); - } - - if (!string.IsNullOrEmpty(options.AccessKey)) - { - return new AmazonS3Client( - new BasicAWSCredentials( - options.AccessKey, - options.SecretKey), - config); - } - - return new AmazonS3Client(config); - }); - - return app; - } + RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region) + }; - public static BaGetApplication AddAwsS3Storage(this BaGetApplication app, Action configure) - { - app.AddAwsS3Storage(); - app.Services.Configure(configure); - return app; - } + if (options.UseInstanceProfile) + { + var credentials = DefaultAWSCredentialsIdentityResolver.GetCredentials(config); + return new AmazonS3Client(credentials, config); + } - private static async Task AssumeRoleAsync( - AWSCredentials credentials, - string roleArn, - string roleSessionName) - { - var assumedCredentials = new AssumeRoleAWSCredentials(credentials, roleArn, roleSessionName); - var immutableCredentials = await credentials.GetCredentialsAsync(); + if (!string.IsNullOrEmpty(options.AssumeRoleArn)) + { + var credentials = DefaultAWSCredentialsIdentityResolver.GetCredentials(config); + var assumedCredentials = AssumeRoleAsync( + credentials, + options.AssumeRoleArn, + $"BaGet-Session-{Guid.NewGuid()}") + .GetAwaiter() + .GetResult(); + + return new AmazonS3Client(assumedCredentials, config); + } - if (string.IsNullOrWhiteSpace(immutableCredentials.Token)) + if (!string.IsNullOrEmpty(options.AccessKey)) { - throw new InvalidOperationException($"Unable to assume role {roleArn}"); + return new AmazonS3Client( + new BasicAWSCredentials( + options.AccessKey, + options.SecretKey), + config); } - return assumedCredentials; + return new AmazonS3Client(config); + }); + + return app; + } + + public static BaGetApplication AddAwsS3Storage(this BaGetApplication app, Action configure) + { + app.AddAwsS3Storage(); + app.Services.Configure(configure); + return app; + } + + private static async Task AssumeRoleAsync( + AWSCredentials credentials, + string roleArn, + string roleSessionName) + { + var assumedCredentials = new AssumeRoleAWSCredentials(credentials, roleArn, roleSessionName); + + // The check is on the assumed credentials (temporary ones always carry a session token), not on the base credentials: + // long-term IAM user keys, the usual base for assuming a role, have none. + var immutableCredentials = await assumedCredentials.GetCredentialsAsync(); + + if (string.IsNullOrWhiteSpace(immutableCredentials.Token)) + { + throw new InvalidOperationException($"Unable to assume role {roleArn}"); } + + return assumedCredentials; } } diff --git a/src/BaGet.Aws/BaGet.Aws.csproj b/src/BaGet.Aws/BaGet.Aws.csproj index 5094cd3d6..2c5bfdc6d 100644 --- a/src/BaGet.Aws/BaGet.Aws.csproj +++ b/src/BaGet.Aws/BaGet.Aws.csproj @@ -1,16 +1,23 @@  - netstandard2.0 - + net10.0 + latest NuGet;Amazon;Cloud - The libraries to host BaGet on AWS. + The libraries to host BaGet Extension on AWS. + enable - - - + + + + + + + + + diff --git a/src/BaGet.Aws/README.md b/src/BaGet.Aws/README.md new file mode 100644 index 000000000..0f69f9040 --- /dev/null +++ b/src/BaGet.Aws/README.md @@ -0,0 +1,28 @@ +# Extension.BaGet.Aws + +Amazon S3 package storage for [BaGet Extension](https://pieroviano.github.io/BaGet/). + +```powershell +dotnet add package Extension.BaGet.Aws +``` + +## Usage + +```csharp +services.AddBaGetWebApplication(app => app.AddAwsS3Storage()); +``` + +Active when `Storage:Type` is `AwsS3`. + +| Setting | Value | +|---|---| +| `Storage:Region` | AWS region system name, e.g. `eu-west-1` | +| `Storage:Bucket` | Bucket name | +| `Storage:Prefix` | Optional key prefix | +| `Storage:AccessKey`, `Storage:SecretKey` | Static credentials | +| `Storage:UseInstanceProfile` | `true` to use the EC2 instance profile instead of keys | +| `Storage:AssumeRoleArn` | Optional role to assume | + +## Links + +[Hosting on AWS](https://pieroviano.github.io/BaGet/installation/aws/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Aws/S3StorageOptions.cs b/src/BaGet.Aws/S3StorageOptions.cs index 025340d20..b05dd34dd 100644 --- a/src/BaGet.Aws/S3StorageOptions.cs +++ b/src/BaGet.Aws/S3StorageOptions.cs @@ -1,26 +1,28 @@ using System.ComponentModel.DataAnnotations; using BaGet.Core; -namespace BaGet.Aws +namespace BaGet.Aws; + +[RestartRequired] +public class S3StorageOptions { - public class S3StorageOptions - { - [RequiredIf(nameof(SecretKey), null, IsInverted = true)] - public string AccessKey { get; set; } + [RequiredIf(nameof(SecretKey), null, IsInverted = true)] + [SensitiveSetting] + public string? AccessKey { get; set; } - [RequiredIf(nameof(AccessKey), null, IsInverted = true)] - public string SecretKey { get; set; } + [RequiredIf(nameof(AccessKey), null, IsInverted = true)] + [SensitiveSetting] + public string? SecretKey { get; set; } - [Required] - public string Region { get; set; } + [Required] + public string? Region { get; set; } - [Required] - public string Bucket { get; set; } + [Required] + public string? Bucket { get; set; } - public string Prefix { get; set; } + public string? Prefix { get; set; } - public bool UseInstanceProfile { get; set; } + public bool UseInstanceProfile { get; set; } - public string AssumeRoleArn { get; set; } - } -} + public string? AssumeRoleArn { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Aws/S3StorageService.Streaming.cs b/src/BaGet.Aws/S3StorageService.Streaming.cs new file mode 100644 index 000000000..c99fb157c --- /dev/null +++ b/src/BaGet.Aws/S3StorageService.Streaming.cs @@ -0,0 +1,473 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Amazon.S3; +using Amazon.S3.Model; +using BaGet.Core; + +namespace BaGet.Aws; + +/// +/// Streaming uploads on S3 multipart uploads (). The final key is only known at commit, so +/// the parts are assembled into a temporary object under .uploads/ and then copied (server side, in ranges, so any size) +/// into the final key through a multipart copy completed with If-None-Match: *, which makes the commit atomic and safe +/// against a concurrent identical commit. +/// +/// +/// S3 wants every part but the last to be at least 5 MiB while a chunk may be any size, so bytes short of a part are kept in a +/// small .tail object (at most one part) that the next chunk is prepended with; the state of an upload is therefore all in +/// S3 (listed parts plus the tail) and any node can take the next chunk. Memory per request: one part (). +/// A blob that never reaches one part is stored with a single put and the generic content type. +/// +public partial class S3StorageService +{ + /// The size of a part: above S3's 5 MiB minimum, and 10 000 parts reach 160 GB. + internal const int PartSize = 16 * 1024 * 1024; + + private const string GenericContentType = "application/octet-stream"; + + // A copied range is one part of the final multipart copy (limit 5 GiB each). + private const long CopyRangeSize = 512L * 1024 * 1024; + + public async Task BeginUploadAsync(string contentType, CancellationToken cancellationToken = default) + { + var id = Guid.NewGuid().ToString("N"); + var response = await _client.InitiateMultipartUploadAsync( + new InitiateMultipartUploadRequest + { + BucketName = _bucket, + Key = TempKey(id), + ContentType = string.IsNullOrEmpty(contentType) ? GenericContentType : contentType, + }, + cancellationToken).ConfigureAwait(false); + + return Convert.ToBase64String(Encoding.UTF8.GetBytes(id + "|" + response.UploadId)) + .Replace('+', '-').Replace('/', '_').TrimEnd('='); + } + + public async Task AppendAsync(string uploadId, long offset, Stream chunk, CancellationToken cancellationToken = default) + { + if (chunk == null) throw new ArgumentNullException(nameof(chunk)); + + var (id, s3Id) = Decode(uploadId); + var state = await ReadStateAsync(id, s3Id, uploadId, cancellationToken).ConfigureAwait(false); + if (state.Length != offset) throw new StorageUploadOffsetException(state.Length, offset); + + var tracked = UploadDigestTracker.Shared.Track(uploadId, offset, chunk); + try + { + var partNumber = state.LastPartNumber; + var stored = state.PartsLength; + + var tail = await StreamPartitioner.SplitAsync( + tracked, + state.Tail, + PartSize, + async (part, ct) => + { + partNumber++; + using var body = StreamingStreams.AsStream(part); + await _client.UploadPartAsync( + new UploadPartRequest + { + BucketName = _bucket, + Key = TempKey(id), + UploadId = s3Id, + PartNumber = partNumber, + InputStream = body, + PartSize = part.Length, + }, + ct).ConfigureAwait(false); + stored += part.Length; + }, + cancellationToken).ConfigureAwait(false); + + if (tail.Length > 0) + { + using var body = new MemoryStream(tail, writable: false); + await _client.PutObjectAsync( + new PutObjectRequest { BucketName = _bucket, Key = TailKey(id), InputStream = body, AutoCloseStream = false }, + cancellationToken).ConfigureAwait(false); + } + else if (state.Tail.Length > 0) + { + await _client.DeleteObjectAsync(_bucket, TailKey(id), cancellationToken).ConfigureAwait(false); + } + + var length = stored + tail.Length; + tracked.Complete(length); + return length; + } + catch + { + tracked.Fail(); + throw; + } + } + + public async Task GetUploadLengthAsync(string uploadId, CancellationToken cancellationToken = default) + { + try + { + var (id, s3Id) = Decode(uploadId); + return (await ReadStateAsync(id, s3Id, uploadId, cancellationToken).ConfigureAwait(false)).Length; + } + catch (StorageUploadNotFoundException) + { + return null; + } + } + + public async Task CommitAsync(string uploadId, string path, string? expectedSha256, CancellationToken cancellationToken = default) + { + var (id, s3Id) = Decode(uploadId); + var state = await ReadStateAsync(id, s3Id, uploadId, cancellationToken).ConfigureAwait(false); + var finalKey = PrepareKey(path); + var tempKey = TempKey(id); + + var sha = UploadDigestTracker.Shared.TryComplete(uploadId, state.Length); + + // Nothing but a tail (a small blob, or an empty one): no multipart is needed, so it is put in one request. + if (state.LastPartNumber == 0) + { + sha ??= StreamingStorage.Sha256Hex(state.Tail); + if (expectedSha256 != null && !string.Equals(expectedSha256, sha, StringComparison.OrdinalIgnoreCase)) + { + await DiscardAsync(id, s3Id, cancellationToken).ConfigureAwait(false); + throw new StorageDigestMismatchException(expectedSha256, sha); + } + + var result = await PutIfAbsentAsync(finalKey, state.Tail, sha, cancellationToken).ConfigureAwait(false); + await DiscardAsync(id, s3Id, cancellationToken).ConfigureAwait(false); + return new StorageCommitResult(result, state.Length, sha); + } + + // Digest known: refuse a wrong blob before assembling it. + if (sha != null && expectedSha256 != null && !string.Equals(expectedSha256, sha, StringComparison.OrdinalIgnoreCase)) + { + await DiscardAsync(id, s3Id, cancellationToken).ConfigureAwait(false); + throw new StorageDigestMismatchException(expectedSha256, sha); + } + + var parts = await ListPartsAsync(tempKey, s3Id, cancellationToken).ConfigureAwait(false); + if (state.Tail.Length > 0) + { + using var body = new MemoryStream(state.Tail, writable: false); + var response = await _client.UploadPartAsync( + new UploadPartRequest + { + BucketName = _bucket, + Key = tempKey, + UploadId = s3Id, + PartNumber = state.LastPartNumber + 1, + InputStream = body, + PartSize = state.Tail.Length, + }, + cancellationToken).ConfigureAwait(false); + parts.Add(new PartETag(state.LastPartNumber + 1, response.ETag)); + } + + await _client.CompleteMultipartUploadAsync( + new CompleteMultipartUploadRequest { BucketName = _bucket, Key = tempKey, UploadId = s3Id, PartETags = parts }, + cancellationToken).ConfigureAwait(false); + + try + { + // The digest is unknown when this node did not see every chunk: read the assembled object once, streaming. + sha ??= await ReadSha256Async(tempKey, cancellationToken).ConfigureAwait(false); + + StreamingStorage.VerifyDigest(expectedSha256, sha); + + var meta = await _client.GetObjectMetadataAsync(_bucket, tempKey, cancellationToken).ConfigureAwait(false); + var put = await CopyIfAbsentAsync(tempKey, finalKey, state.Length, meta.Headers.ContentType, sha, cancellationToken).ConfigureAwait(false); + return new StorageCommitResult(put, state.Length, sha); + } + finally + { + await _client.DeleteObjectAsync(_bucket, tempKey, CancellationToken.None).ConfigureAwait(false); + await _client.DeleteObjectAsync(_bucket, TailKey(id), CancellationToken.None).ConfigureAwait(false); + UploadDigestTracker.Shared.Forget(uploadId); + } + } + + public async Task AbortAsync(string uploadId, CancellationToken cancellationToken = default) + { + UploadDigestTracker.Shared.Forget(uploadId); + + string id, s3Id; + try + { + (id, s3Id) = Decode(uploadId); + } + catch (StorageUploadNotFoundException) + { + return; + } + + await DiscardAsync(id, s3Id, cancellationToken).ConfigureAwait(false); + } + + public async Task GetInfoAsync(string path, CancellationToken cancellationToken = default) + { + try + { + var meta = await _client.GetObjectMetadataAsync(_bucket, PrepareKey(path), cancellationToken).ConfigureAwait(false); + return new StorageBlobInfo(meta.ContentLength, meta.Headers.ContentType); + } + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.NotFound) + { + return null; + } + } + + public async Task GetRangeAsync(string path, long offset, long? length, CancellationToken cancellationToken = default) + { + var info = await GetInfoAsync(path, cancellationToken).ConfigureAwait(false); + if (info == null) return null; + + var count = StreamingStorage.ResolveRange(info.Length, offset, length); + if (count == 0) return Stream.Null; + + // Bounded range requests, each re-requested from the exact byte if its connection drops: one GET of many GB must not be the unit of failure. + return new WindowedReadStream( + async (from, size, ct) => + { + var response = await _client.GetObjectAsync( + new GetObjectRequest { BucketName = _bucket, Key = PrepareKey(path), ByteRange = new ByteRange(from, from + size - 1) }, + ct).ConfigureAwait(false); + return new OwnedReadStream(response.ResponseStream, response); + }, + offset, + count); + } + + private string TempKey(string id) => PrepareKey(StreamingStorage.UploadsFolder + Separator + id); + + private string TailKey(string id) => PrepareKey(StreamingStorage.UploadsFolder + Separator + id + ".tail"); + + private static (string Id, string S3Id) Decode(string uploadId) + { + try + { + var padded = uploadId.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + (4 - padded.Length % 4) % 4, '='); + var text = Encoding.UTF8.GetString(Convert.FromBase64String(padded)); + var bar = text.IndexOf('|'); + if (bar == 32 && Guid.TryParseExact(text.Substring(0, bar), "N", out _) && bar < text.Length - 1) + { + return (text.Substring(0, bar), text.Substring(bar + 1)); + } + } + catch (FormatException) + { + } + + throw new StorageUploadNotFoundException(uploadId); + } + + private sealed record UploadState(int LastPartNumber, long PartsLength, byte[] Tail) + { + public long Length => PartsLength + Tail.Length; + } + + private async Task ReadStateAsync(string id, string s3Id, string uploadId, CancellationToken cancellationToken) + { + var last = 0; + long size = 0; + try + { + foreach (var part in await ListPartDetailsAsync(TempKey(id), s3Id, cancellationToken).ConfigureAwait(false)) + { + last = Math.Max(last, part.PartNumber.GetValueOrDefault()); + size += part.Size.GetValueOrDefault(); + } + } + catch (AmazonS3Exception e) when (e.ErrorCode == "NoSuchUpload" || e.StatusCode == HttpStatusCode.NotFound) + { + throw new StorageUploadNotFoundException(uploadId); + } + + var tail = Array.Empty(); + try + { + using var response = await _client.GetObjectAsync(_bucket, TailKey(id), cancellationToken).ConfigureAwait(false); + using var buffer = new MemoryStream(); + await response.ResponseStream.CopyToAsync(buffer, 81920, cancellationToken).ConfigureAwait(false); + tail = buffer.ToArray(); + } + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.NotFound) + { + } + + return new UploadState(last, size, tail); + } + + private async Task> ListPartDetailsAsync(string key, string s3Id, CancellationToken cancellationToken) + { + var result = new List(); + string? marker = null; + while (true) + { + var page = await _client.ListPartsAsync( + new ListPartsRequest { BucketName = _bucket, Key = key, UploadId = s3Id, PartNumberMarker = marker }, + cancellationToken).ConfigureAwait(false); + + if (page.Parts != null) result.AddRange(page.Parts); + + if (page.IsTruncated != true) break; + marker = page.NextPartNumberMarker?.ToString(); + } + + return result; + } + + private async Task> ListPartsAsync(string key, string s3Id, CancellationToken cancellationToken) + { + var parts = await ListPartDetailsAsync(key, s3Id, cancellationToken).ConfigureAwait(false); + return parts + .Select(p => new PartETag(p.PartNumber.GetValueOrDefault(), p.ETag)) + .OrderBy(p => p.PartNumber) + .ToList(); + } + + private async Task ReadSha256Async(string key, CancellationToken cancellationToken) + { + using var stored = await _client.GetObjectAsync(_bucket, key, cancellationToken).ConfigureAwait(false); + return await StreamingStorage.Sha256HexAsync(stored.ResponseStream, cancellationToken).ConfigureAwait(false); + } + + private async Task DiscardAsync(string id, string s3Id, CancellationToken cancellationToken) + { + try + { + await _client.AbortMultipartUploadAsync( + new AbortMultipartUploadRequest { BucketName = _bucket, Key = TempKey(id), UploadId = s3Id }, + cancellationToken).ConfigureAwait(false); + } + catch (AmazonS3Exception e) when (e.ErrorCode == "NoSuchUpload" || e.StatusCode == HttpStatusCode.NotFound) + { + } + + await _client.DeleteObjectAsync(_bucket, TailKey(id), cancellationToken).ConfigureAwait(false); + } + + private async Task PutIfAbsentAsync(string key, byte[] content, string sha, CancellationToken cancellationToken) + { + try + { + using var body = new MemoryStream(content, writable: false); + await _client.PutObjectAsync( + new PutObjectRequest + { + BucketName = _bucket, + Key = key, + InputStream = body, + ContentType = GenericContentType, + IfNoneMatch = IfKeyIsUnused, + AutoCloseStream = false, + }, + cancellationToken).ConfigureAwait(false); + return StoragePutResult.Success; + } + catch (AmazonS3Exception e) when (KeyIsTaken(e)) + { + return await CompareWithStoredAsync(key, sha, cancellationToken).ConfigureAwait(false); + } + } + + private async Task CopyIfAbsentAsync(string sourceKey, string key, long size, string? contentType, string sha, CancellationToken cancellationToken) + { + // The conditional complete below is what makes this atomic on S3; the plain check first spares the copy in the usual case of + // a blob that is already there, and covers S3-compatible stores that do not honour If-None-Match: * on a multipart complete. + if (await ExistsAsync(key, cancellationToken).ConfigureAwait(false)) + { + return await CompareWithStoredAsync(key, sha, cancellationToken).ConfigureAwait(false); + } + + var start = await _client.InitiateMultipartUploadAsync( + new InitiateMultipartUploadRequest { BucketName = _bucket, Key = key, ContentType = contentType }, + cancellationToken).ConfigureAwait(false); + + try + { + var etags = new List(); + var number = 0; + for (long first = 0; first < size; first += CopyRangeSize) + { + number++; + var copied = await _client.CopyPartAsync( + new CopyPartRequest + { + SourceBucket = _bucket, + SourceKey = sourceKey, + DestinationBucket = _bucket, + DestinationKey = key, + UploadId = start.UploadId, + PartNumber = number, + FirstByte = first, + LastByte = Math.Min(first + CopyRangeSize, size) - 1, + }, + cancellationToken).ConfigureAwait(false); + etags.Add(new PartETag(number, copied.ETag)); + } + + await _client.CompleteMultipartUploadAsync( + new CompleteMultipartUploadRequest { BucketName = _bucket, Key = key, UploadId = start.UploadId, PartETags = etags, IfNoneMatch = IfKeyIsUnused }, + cancellationToken).ConfigureAwait(false); + return StoragePutResult.Success; + } + catch (AmazonS3Exception e) when (KeyIsTaken(e)) + { + // Compared before the abort: the stored blob is what the answer is about. + var result = await CompareWithStoredAsync(key, sha, cancellationToken).ConfigureAwait(false); + await AbortQuietlyAsync(key, start.UploadId).ConfigureAwait(false); + return result; + } + catch + { + await AbortQuietlyAsync(key, start.UploadId).ConfigureAwait(false); + throw; + } + } + + // S3 answers a taken key with 412 Precondition Failed; some S3-compatible stores answer 304 Not Modified to the same header. + private static bool KeyIsTaken(AmazonS3Exception e) + => e.StatusCode == HttpStatusCode.PreconditionFailed || e.StatusCode == HttpStatusCode.NotModified; + + private async Task ExistsAsync(string key, CancellationToken cancellationToken) + { + try + { + await _client.GetObjectMetadataAsync(_bucket, key, cancellationToken).ConfigureAwait(false); + return true; + } + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.NotFound) + { + return false; + } + } + + private async Task AbortQuietlyAsync(string key, string uploadId) + { + try + { + await _client.AbortMultipartUploadAsync( + new AbortMultipartUploadRequest { BucketName = _bucket, Key = key, UploadId = uploadId }, + CancellationToken.None).ConfigureAwait(false); + } + catch (AmazonS3Exception) + { + } + } + + private async Task CompareWithStoredAsync(string key, string sha, CancellationToken cancellationToken) + { + var existing = await ReadSha256Async(key, cancellationToken).ConfigureAwait(false); + return string.Equals(existing, sha, StringComparison.Ordinal) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict; + } +} diff --git a/src/BaGet.Aws/S3StorageService.cs b/src/BaGet.Aws/S3StorageService.cs index bee08c5f0..215145ce3 100644 --- a/src/BaGet.Aws/S3StorageService.cs +++ b/src/BaGet.Aws/S3StorageService.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Net; using System.Threading; using System.Threading.Tasks; using Amazon.S3; @@ -7,96 +9,151 @@ using BaGet.Core; using Microsoft.Extensions.Options; -namespace BaGet.Aws +namespace BaGet.Aws; + +public partial class S3StorageService : IStreamingStorageService, IListableStorageService { - public class S3StorageService : IStorageService - { - private const string Separator = "/"; - private readonly string _bucket; - private readonly string _prefix; - private readonly AmazonS3Client _client; + private const string Separator = "/"; - public S3StorageService(IOptionsSnapshot options, AmazonS3Client client) - { - if (options == null) - throw new ArgumentNullException(nameof(options)); + /// + /// The value S3 expects in the If-None-Match header to mean "only if the key + /// is unused". See . + /// + private const string IfKeyIsUnused = "*"; - _bucket = options.Value.Bucket; - _prefix = options.Value.Prefix; - _client = client ?? throw new ArgumentNullException(nameof(client)); + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; - if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) - _prefix += Separator; - } - - private string PrepareKey(string path) - { - return _prefix + path.Replace("\\", Separator); - } + private readonly string? _bucket; + private readonly string? _prefix; + private readonly AmazonS3Client _client; - public async Task GetAsync(string path, CancellationToken cancellationToken = default) - { - var stream = new MemoryStream(); + public S3StorageService(IOptionsSnapshot options, AmazonS3Client client) + { + if (options == null) + throw new ArgumentNullException(nameof(options)); - try - { - using (var request = await _client.GetObjectAsync(_bucket, PrepareKey(path), cancellationToken)) - { - await request.ResponseStream.CopyToAsync(stream); - } + _bucket = options.Value.Bucket; + _prefix = options.Value.Prefix; + _client = client ?? throw new ArgumentNullException(nameof(client)); - stream.Seek(0, SeekOrigin.Begin); - } - catch (Exception) - { - stream.Dispose(); + if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) + _prefix += Separator; + } - // TODO - throw; - } + private string PrepareKey(string path) + { + return _prefix + path.Replace("\\", Separator); + } - return stream; + public async Task GetAsync(string path, CancellationToken cancellationToken = default) + { + // The response stream is handed out as it is (disposing it releases the connection): the object is never held in memory. + GetObjectResponse response; + try + { + response = await _client.GetObjectAsync(_bucket, PrepareKey(path), cancellationToken).ConfigureAwait(false); } - - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.NotFound) { - var url = _client.GetPreSignedURL(new GetPreSignedUrlRequest - { - BucketName = _bucket, - Key = PrepareKey(path) - }); - - return Task.FromResult(new Uri(url)); + // The one "missing content" exception of IStorageService.GetAsync, as FileStorageService throws. + throw new FileNotFoundException("The object '" + path + "' does not exist.", path, e); } - public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + return new OwnedReadStream(response.ResponseStream, response); + } + + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + var url = _client.GetPreSignedURL(new GetPreSignedUrlRequest { - // TODO: Uploads should be idempotent. This should fail if and only if the blob - // already exists but has different content. + BucketName = _bucket, + Key = PrepareKey(path) + }); - using (var seekableContent = new MemoryStream()) - { - await content.CopyToAsync(seekableContent, 4096, cancellationToken); + return Task.FromResult(new Uri(url)); + } - seekableContent.Seek(0, SeekOrigin.Begin); + public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + // A temporary file, not a MemoryStream: a large package is never held in managed memory. + using (var seekableContent = await StreamingStreams.SpoolAsync(content, cancellationToken).ConfigureAwait(false)) + { + try + { await _client.PutObjectAsync(new PutObjectRequest { BucketName = _bucket, Key = PrepareKey(path), InputStream = seekableContent, ContentType = contentType, + // Make the upload idempotent: store the content only while the key is + // unused. S3 answers a taken key with "412 Precondition Failed". + IfNoneMatch = IfKeyIsUnused, AutoResetStreamPosition = false, AutoCloseStream = false }, cancellationToken); + + return StoragePutResult.Success; } + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.PreconditionFailed) + { + // The key is taken. Storing the same content twice is not a failure, so + // this is only a conflict when the stored content differs. + using (var targetStream = await GetAsync(path, cancellationToken)) + { + seekableContent.Seek(0, SeekOrigin.Begin); - return StoragePutResult.Success; + return seekableContent.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; + } + } } + } - public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) + /// + /// Every key under a prefix, paged until S3 says there is no more. The sweep of + /// abandoned staged uploads is the only caller, and without this a bucket would keep + /// them forever. + /// + public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // "staging-archive/...". + var prefix = PrepareKey(pathPrefix.TrimEnd('/') + Separator); + var paths = new List(); + string? continuation = null; + + do { - await _client.DeleteObjectAsync(_bucket, PrepareKey(path), cancellationToken); + var response = await _client.ListObjectsV2Async( + new ListObjectsV2Request + { + BucketName = _bucket, + Prefix = prefix, + ContinuationToken = continuation, + }, + cancellationToken); + + foreach (var item in response.S3Objects) + { + // Reported as the paths IStorageService takes, so the configured bucket + // prefix is removed again. + paths.Add(string.IsNullOrEmpty(_prefix) ? item.Key : item.Key.Substring(_prefix.Length)); + } + + continuation = response.IsTruncated == true ? response.NextContinuationToken : null; } + while (continuation != null); + + return paths; + } + + public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + await _client.DeleteObjectAsync(_bucket, PrepareKey(path), cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/AzureApplicationExtensions.cs b/src/BaGet.Azure/AzureApplicationExtensions.cs index f8916840f..4fb623370 100644 --- a/src/BaGet.Azure/AzureApplicationExtensions.cs +++ b/src/BaGet.Azure/AzureApplicationExtensions.cs @@ -6,179 +6,190 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using Microsoft.WindowsAzure.Storage.Blob; +using Microsoft.Azure.Storage.Blob; -namespace BaGet -{ - using CloudStorageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount; - using StorageCredentials = Microsoft.WindowsAzure.Storage.Auth.StorageCredentials; +namespace BaGet; + +using CloudStorageAccount = Microsoft.Azure.Storage.CloudStorageAccount; +using StorageCredentials = Microsoft.Azure.Storage.Auth.StorageCredentials; - using TableStorageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount; +using TableStorageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount; - public static class AzureApplicationExtensions +public static class AzureApplicationExtensions +{ + public static BaGetApplication AddAzureTableDatabase(this BaGetApplication app) { - public static BaGetApplication AddAzureTableDatabase(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Database)); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Database)); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; - return TableStorageAccount.Parse(options.ConnectionString); - }); + return TableStorageAccount.Parse(options.ConnectionString); + }); - app.Services.AddTransient(provider => - { - var account = provider.GetRequiredService(); + app.Services.AddTransient(provider => + { + var account = provider.GetRequiredService(); - return account.CreateCloudTableClient(); - }); + return account.CreateCloudTableClient(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasDatabaseType("AzureTable")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasDatabaseType("AzureTable")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("Database")) return null; - if (!config.HasDatabaseType("AzureTable")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasSearchType("Database")) return null; + if (!config.HasDatabaseType("AzureTable")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("Database")) return null; - if (!config.HasDatabaseType("AzureTable")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasSearchType("Database")) return null; + if (!config.HasDatabaseType("AzureTable")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAzureTableDatabase( - this BaGetApplication app, - Action configure) - { - app.AddAzureTableDatabase(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAzureTableDatabase( + this BaGetApplication app, + Action configure) + { + app.AddAzureTableDatabase(); + app.Services.Configure(configure); + return app; + } - public static BaGetApplication AddAzureBlobStorage(this BaGetApplication app) + public static BaGetApplication AddAzureBlobStorage(this BaGetApplication app) + { + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + + app.Services.AddSingleton(provider => { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + var options = provider.GetRequiredService>().Value; - app.Services.AddSingleton(provider => + if (!string.IsNullOrEmpty(options.ConnectionString)) { - var options = provider.GetRequiredService>().Value; - - if (!string.IsNullOrEmpty(options.ConnectionString)) - { - return CloudStorageAccount.Parse(options.ConnectionString); - } + return CloudStorageAccount.Parse(options.ConnectionString); + } - return new CloudStorageAccount( - new StorageCredentials( - options.AccountName, - options.AccessKey), - useHttps: true); - }); + return new CloudStorageAccount( + new StorageCredentials( + options.AccountName, + options.AccessKey), + useHttps: true); + }); - app.Services.AddTransient(provider => - { - var options = provider.GetRequiredService>().Value; - var account = provider.GetRequiredService(); + app.Services.AddTransient(provider => + { + var options = provider.GetRequiredService>().Value; + var account = provider.GetRequiredService(); - var client = account.CreateCloudBlobClient(); + var client = account.CreateCloudBlobClient(); - return client.GetContainerReference(options.Container); - }); + return client.GetContainerReference(options.Container); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("AzureBlobStorage")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasStorageType("AzureBlobStorage")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAzureBlobStorage( - this BaGetApplication app, - Action configure) - { - app.AddAzureBlobStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAzureBlobStorage( + this BaGetApplication app, + Action configure) + { + app.AddAzureBlobStorage(); + app.Services.Configure(configure); + return app; + } - public static BaGetApplication AddAzureSearch(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Search)); + public static BaGetApplication AddAzureSearch(this BaGetApplication app) + { + app.Services.AddBaGetOptions(nameof(BaGetOptions.Search)); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; - var credentials = new SearchCredentials(options.ApiKey); + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; + var credentials = new SearchCredentials(options.ApiKey); - return new SearchServiceClient(options.AccountName, credentials); - }); + return new SearchServiceClient(options.AccountName, credentials); + }); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; - var credentials = new SearchCredentials(options.ApiKey); + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; + var credentials = new SearchCredentials(options.ApiKey); - return new SearchIndexClient(options.AccountName, PackageDocument.IndexName, credentials); - }); + return new SearchIndexClient(options.AccountName, PackageDocument.IndexName, credentials); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("AzureSearch")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasSearchType("AzureSearch")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("AzureSearch")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasSearchType("AzureSearch")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAzureSearch( - this BaGetApplication app, - Action configure) - { - app.AddAzureSearch(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAzureSearch( + this BaGetApplication app, + Action configure) + { + app.AddAzureSearch(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/BaGet.Azure.csproj b/src/BaGet.Azure/BaGet.Azure.csproj index 7b567f6aa..7c9b32895 100644 --- a/src/BaGet.Azure/BaGet.Azure.csproj +++ b/src/BaGet.Azure/BaGet.Azure.csproj @@ -1,21 +1,35 @@ - netstandard2.0 - + net10.0 + latest NuGet;Azure;Cloud - The libraries to host BaGet on Azure. + The libraries to host BaGet Extension on Azure. + + + + + true + enable - + - - - - + + + + + + + + + + + + diff --git a/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs b/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs index 89055c685..e96f3afa5 100644 --- a/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs +++ b/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs @@ -1,62 +1,85 @@ +using System; using System.Collections.Generic; +using BaGet.Core; using System.ComponentModel.DataAnnotations; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// BaGet's configurations to use Azure Blob Storage to store packages. +/// See: https://pieroviano.github.io/BaGet/quickstart/azure/#azure-blob-storage +/// +[RestartRequired] +public class AzureBlobStorageOptions : IValidatableObject { /// - /// BaGet's configurations to use Azure Blob Storage to store packages. - /// See: https://loic-sharma.github.io/BaGet/quickstart/azure/#azure-blob-storage + /// The Azure Blob Storage connection string. + /// If provided, ignores and . + /// + [SensitiveSetting] + public string? ConnectionString { get; set; } + + /// + /// The Azure Blob Storage account name. Ignored if is provided. + /// + public string? AccountName { get; set; } + + /// + /// The Azure Blob Storage access key. Ignored if is provided. + /// + [SensitiveSetting] + public string? AccessKey { get; set; } + + /// + /// The Azure Blob Storage container name. + /// + public string? Container { get; set; } + + /// + /// How long the shared access signatures handed out by + /// stay valid. + /// Must be greater than zero. /// - public class AzureBlobStorageOptions : IValidatableObject + public TimeSpan DownloadUriExpiry { get; set; } = DefaultDownloadUriExpiry; + + /// + /// The used when the configuration does not set one. + /// + public static readonly TimeSpan DefaultDownloadUriExpiry = TimeSpan.FromMinutes(10); + + public IEnumerable Validate(ValidationContext validationContext) { - /// - /// The Azure Blob Storage connection string. - /// If provided, ignores and . - /// - public string ConnectionString { get; set; } - - /// - /// The Azure Blob Storage account name. Ignored if is provided. - /// - public string AccountName { get; set; } - - /// - /// The Azure Blob Storage access key. Ignored if is provided. - /// - public string AccessKey { get; set; } - - /// - /// The Azure Blob Storage container name. - /// - public string Container { get; set; } - - public IEnumerable Validate(ValidationContext validationContext) + const string helpUrl = "https://pieroviano.github.io/BaGet/quickstart/azure/#azure-blob-storage"; + + if (DownloadUriExpiry <= TimeSpan.Zero) { - const string helpUrl = "https://loic-sharma.github.io/BaGet/quickstart/azure/#azure-blob-storage"; + yield return new ValidationResult( + $"The {nameof(DownloadUriExpiry)} configuration must be greater than zero. See {helpUrl}", + new[] { nameof(DownloadUriExpiry) }); + } - if (string.IsNullOrEmpty(ConnectionString)) + if (string.IsNullOrEmpty(ConnectionString)) + { + if (string.IsNullOrEmpty(AccountName)) { - if (string.IsNullOrEmpty(AccountName)) - { - yield return new ValidationResult( - $"The {nameof(AccountName)} configuration is required. See {helpUrl}", - new[] { nameof(AccountName) }); - } - - if (string.IsNullOrEmpty(AccessKey)) - { - yield return new ValidationResult( - $"The {nameof(AccessKey)} configuration is required. See {helpUrl}", - new[] { nameof(AccessKey) }); - } + yield return new ValidationResult( + $"The {nameof(AccountName)} configuration is required. See {helpUrl}", + new[] { nameof(AccountName) }); } - if (string.IsNullOrEmpty(Container)) + if (string.IsNullOrEmpty(AccessKey)) { yield return new ValidationResult( - $"The {nameof(Container)} configuration is required. See {helpUrl}", - new[] { nameof(Container) }); + $"The {nameof(AccessKey)} configuration is required. See {helpUrl}", + new[] { nameof(AccessKey) }); } } + + if (string.IsNullOrEmpty(Container)) + { + yield return new ValidationResult( + $"The {nameof(Container)} configuration is required. See {helpUrl}", + new[] { nameof(Container) }); + } } } diff --git a/src/BaGet.Azure/Configuration/AzureSearchOptions.cs b/src/BaGet.Azure/Configuration/AzureSearchOptions.cs index f92c06816..904e96bb3 100644 --- a/src/BaGet.Azure/Configuration/AzureSearchOptions.cs +++ b/src/BaGet.Azure/Configuration/AzureSearchOptions.cs @@ -1,13 +1,15 @@ using System.ComponentModel.DataAnnotations; +using BaGet.Core; -namespace BaGet.Azure +namespace BaGet.Azure; + +[RestartRequired] +public class AzureSearchOptions { - public class AzureSearchOptions - { - [Required] - public string AccountName { get; set; } + [Required] + public string? AccountName { get; set; } - [Required] - public string ApiKey { get; set; } - } -} + [Required] + [SensitiveSetting] + public string? ApiKey { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Configuration/AzureTableOptions.cs b/src/BaGet.Azure/Configuration/AzureTableOptions.cs index 373eb9b3e..9b5573453 100644 --- a/src/BaGet.Azure/Configuration/AzureTableOptions.cs +++ b/src/BaGet.Azure/Configuration/AzureTableOptions.cs @@ -1,10 +1,12 @@ using System.ComponentModel.DataAnnotations; +using BaGet.Core; -namespace BaGet.Azure +namespace BaGet.Azure; + +[RestartRequired] +public class AzureTableOptions { - public class AzureTableOptions - { - [Required] - public string ConnectionString { get; set; } - } -} + [Required] + [SensitiveSetting] + public string? ConnectionString { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs b/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs index a7f50c131..8de14bc82 100644 --- a/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs +++ b/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs @@ -1,30 +1,29 @@ using System.Net; -namespace BaGet.Azure -{ - using StorageException = Microsoft.WindowsAzure.Storage.StorageException; - using TableStorageException = Microsoft.Azure.Cosmos.Table.StorageException; +namespace BaGet.Azure; + +using StorageException = Microsoft.Azure.Storage.StorageException; +using TableStorageException = Microsoft.Azure.Cosmos.Table.StorageException; - internal static class StorageExceptionExtensions +internal static class StorageExceptionExtensions +{ + public static bool IsAlreadyExistsException(this StorageException? e) { - public static bool IsAlreadyExistsException(this StorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; - } + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; + } - public static bool IsNotFoundException(this TableStorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.NotFound; - } + public static bool IsNotFoundException(this TableStorageException? e) + { + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.NotFound; + } - public static bool IsAlreadyExistsException(this TableStorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; - } + public static bool IsAlreadyExistsException(this TableStorageException? e) + { + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; + } - public static bool IsPreconditionFailedException(this TableStorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.PreconditionFailed; - } + public static bool IsPreconditionFailedException(this TableStorageException? e) + { + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.PreconditionFailed; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/README.md b/src/BaGet.Azure/README.md new file mode 100644 index 000000000..62ece34be --- /dev/null +++ b/src/BaGet.Azure/README.md @@ -0,0 +1,30 @@ +# Extension.BaGet.Azure + +Azure providers for [BaGet Extension](https://pieroviano.github.io/BaGet/): Blob Storage, Table Storage and Azure Search. + +```powershell +dotnet add package Extension.BaGet.Azure +``` + +## Usage + +```csharp +services.AddBaGetWebApplication(app => +{ + app.AddAzureTableDatabase(); + app.AddAzureBlobStorage(); + app.AddAzureSearch(); +}); +``` + +| Provider | Active when | Settings | +|---|---|---| +| `AddAzureTableDatabase` | `Database:Type` = `AzureTable` | `Database:ConnectionString` | +| `AddAzureBlobStorage` | `Storage:Type` = `AzureBlobStorage` | `Storage:ConnectionString`, or `Storage:AccountName` + `Storage:AccessKey`; `Storage:Container`; `Storage:DownloadUriExpiry` | +| `AddAzureSearch` | `Search:Type` = `AzureSearch` | `Search:AccountName`, `Search:ApiKey` | + +With `Database:Type` = `AzureTable`, `Search:Type` = `Database` searches Table Storage. + +## Links + +[Hosting on Azure](https://pieroviano.github.io/BaGet/installation/azure/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs b/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs index 062d67d84..88e559779 100644 --- a/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs +++ b/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs @@ -9,80 +9,79 @@ using Microsoft.Extensions.Logging; using Microsoft.Rest.Azure; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class AzureSearchBatchIndexer { - public class AzureSearchBatchIndexer - { - /// - /// Azure Search accepts batches of up to 1000 documents. - /// - public const int MaxBatchSize = 1000; + /// + /// Azure Search accepts batches of up to 1000 documents. + /// + public const int MaxBatchSize = 1000; - private readonly ISearchIndexClient _indexClient; - private readonly ILogger _logger; + private readonly ISearchIndexClient _indexClient; + private readonly ILogger _logger; - public AzureSearchBatchIndexer( - SearchServiceClient searchClient, - ILogger logger) - { - if (searchClient == null) throw new ArgumentNullException(nameof(searchClient)); + public AzureSearchBatchIndexer( + SearchServiceClient searchClient, + ILogger logger) + { + if (searchClient == null) throw new ArgumentNullException(nameof(searchClient)); - _indexClient = searchClient.Indexes.GetClient(PackageDocument.IndexName); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + _indexClient = searchClient.Indexes.GetClient(PackageDocument.IndexName); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task IndexAsync( - IReadOnlyList> batch, - CancellationToken cancellationToken) + public async Task IndexAsync( + IReadOnlyList> batch, + CancellationToken cancellationToken) + { + if (batch.Count > MaxBatchSize) { - if (batch.Count > MaxBatchSize) - { - throw new ArgumentException( - $"Batch cannot have more than {MaxBatchSize} elements", - nameof(batch)); - } + throw new ArgumentException( + $"Batch cannot have more than {MaxBatchSize} elements", + nameof(batch)); + } - IList indexingResults = null; - Exception innerException = null; + IList? indexingResults = null; + Exception? innerException = null; - try - { - await _indexClient.Documents.IndexAsync( - IndexBatch.New(batch), - cancellationToken: cancellationToken); + try + { + await _indexClient.Documents.IndexAsync( + IndexBatch.New(batch), + cancellationToken: cancellationToken); - _logger.LogInformation("Pushed batch of {DocumentCount} documents", batch.Count); + _logger.LogInformation("Pushed batch of {DocumentCount} documents", batch.Count); - } - catch (IndexBatchException ex) - { - _logger.LogError(ex, "An exception was thrown when pushing batch of documents"); - indexingResults = ex.IndexingResults; - innerException = ex; - } - catch (CloudException ex) when (ex.Response.StatusCode == HttpStatusCode.RequestEntityTooLarge && batch.Count > 1) - { - var halfCount = batch.Count / 2; - var halfA = batch.Take(halfCount).ToList(); - var halfB = batch.Skip(halfCount).ToList(); + } + catch (IndexBatchException ex) + { + _logger.LogError(ex, "An exception was thrown when pushing batch of documents"); + indexingResults = ex.IndexingResults; + innerException = ex; + } + catch (CloudException ex) when (ex.Response.StatusCode == HttpStatusCode.RequestEntityTooLarge && batch.Count > 1) + { + var halfCount = batch.Count / 2; + var halfA = batch.Take(halfCount).ToList(); + var halfB = batch.Skip(halfCount).ToList(); - _logger.LogWarning( - 0, - ex, - "The request body for a batch of {BatchSize} was too large. Splitting into two batches of size " + - "{HalfA} and {HalfB}.", - batch.Count, - halfA.Count, - halfB.Count); + _logger.LogWarning( + 0, + ex, + "The request body for a batch of {BatchSize} was too large. Splitting into two batches of size " + + "{HalfA} and {HalfB}.", + batch.Count, + halfA.Count, + halfB.Count); - await IndexAsync(halfA, cancellationToken); - await IndexAsync(halfB, cancellationToken); - } + await IndexAsync(halfA, cancellationToken); + await IndexAsync(halfB, cancellationToken); + } - if (indexingResults != null && indexingResults.Any(result => !result.Succeeded)) - { - throw new InvalidOperationException("Failed to pushed batch of documents documents"); - } + if (indexingResults != null && indexingResults.Any(result => !result.Succeeded)) + { + throw new InvalidOperationException("Failed to pushed batch of documents documents"); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/AzureSearchIndexer.cs b/src/BaGet.Azure/Search/AzureSearchIndexer.cs index 46be8c95f..185f8782c 100644 --- a/src/BaGet.Azure/Search/AzureSearchIndexer.cs +++ b/src/BaGet.Azure/Search/AzureSearchIndexer.cs @@ -4,37 +4,36 @@ using BaGet.Core; using Microsoft.Extensions.Logging; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class AzureSearchIndexer : ISearchIndexer { - public class AzureSearchIndexer : ISearchIndexer - { - private readonly IPackageDatabase _packages; - private readonly IndexActionBuilder _actionBuilder; - private readonly AzureSearchBatchIndexer _batchIndexer; - private readonly ILogger _logger; + private readonly IPackageDatabase _packages; + private readonly IndexActionBuilder _actionBuilder; + private readonly AzureSearchBatchIndexer _batchIndexer; + private readonly ILogger _logger; - public AzureSearchIndexer( - IPackageDatabase packages, - IndexActionBuilder actionBuilder, - AzureSearchBatchIndexer batchIndexer, - ILogger logger) - { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _actionBuilder = actionBuilder ?? throw new ArgumentNullException(nameof(actionBuilder)); - _batchIndexer = batchIndexer ?? throw new ArgumentNullException(nameof(batchIndexer)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public AzureSearchIndexer( + IPackageDatabase packages, + IndexActionBuilder actionBuilder, + AzureSearchBatchIndexer batchIndexer, + ILogger logger) + { + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _actionBuilder = actionBuilder ?? throw new ArgumentNullException(nameof(actionBuilder)); + _batchIndexer = batchIndexer ?? throw new ArgumentNullException(nameof(batchIndexer)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task IndexAsync(Package package, CancellationToken cancellationToken) - { - var packages = await _packages.FindAsync(package.Id, includeUnlisted: false, cancellationToken); + public async Task IndexAsync(Package package, CancellationToken cancellationToken) + { + var packages = await _packages.FindAsync(package.Id, includeUnlisted: false, cancellationToken); - var actions = _actionBuilder.UpdatePackage( - new PackageRegistration( - package.Id, - packages)); + var actions = _actionBuilder.UpdatePackage( + new PackageRegistration( + package.Id, + packages)); - await _batchIndexer.IndexAsync(actions, cancellationToken); - } + await _batchIndexer.IndexAsync(actions, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/AzureSearchService.cs b/src/BaGet.Azure/Search/AzureSearchService.cs index 6ce1f63f5..a1a882a9f 100644 --- a/src/BaGet.Azure/Search/AzureSearchService.cs +++ b/src/BaGet.Azure/Search/AzureSearchService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -9,217 +9,428 @@ using Microsoft.Azure.Search; using NuGet.Versioning; -namespace BaGet.Azure +namespace BaGet.Azure; + +using QueryType = Microsoft.Azure.Search.Models.QueryType; +using SearchParameters = Microsoft.Azure.Search.Models.SearchParameters; + +/// +/// is ignored ( is the +/// default, relevance only). The index could order by "totalDownloads", but "published" is not +/// sortable, and adding it means changing the index definition, which an existing index would +/// need rebuilt. Offering one of the two sorts would also make the UI inconsistent. +/// +public class AzureSearchService : ISearchService { - using QueryType = Microsoft.Azure.Search.Models.QueryType; - using SearchParameters = Microsoft.Azure.Search.Models.SearchParameters; + private readonly SearchIndexClient _searchClient; + private readonly IUrlGenerator _url; + private readonly IFrameworkCompatibilityService _frameworks; - public class AzureSearchService : ISearchService + public AzureSearchService( + SearchIndexClient searchClient, + IUrlGenerator url, + IFrameworkCompatibilityService frameworks) { - private readonly SearchIndexClient _searchClient; - private readonly IUrlGenerator _url; - private readonly IFrameworkCompatibilityService _frameworks; - - public AzureSearchService( - SearchIndexClient searchClient, - IUrlGenerator url, - IFrameworkCompatibilityService frameworks) - { - _searchClient = searchClient ?? throw new ArgumentNullException(nameof(searchClient)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); - } + _searchClient = searchClient ?? throw new ArgumentNullException(nameof(searchClient)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); + } - public async Task SearchAsync( - SearchRequest request, - CancellationToken cancellationToken) + public async Task SearchAsync( + SearchRequest request, + CancellationToken cancellationToken) + { + var searchText = BuildSeachQuery(request.Query, request.PackageType, request.Framework); + var filter = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2); + var parameters = new SearchParameters { - var searchText = BuildSeachQuery(request.Query, request.PackageType, request.Framework); - var filter = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2); - var parameters = new SearchParameters - { - IncludeTotalResultCount = true, - QueryType = QueryType.Full, - Skip = request.Skip, - Top = request.Take, - Filter = filter - }; - - var response = await _searchClient.Documents.SearchAsync( - searchText, - parameters, - cancellationToken: cancellationToken); + IncludeTotalResultCount = true, + QueryType = QueryType.Full, + Skip = request.Skip, + Top = request.Take, + Filter = filter + }; - var results = new List(); + var response = await _searchClient.Documents.SearchAsync( + searchText, + parameters, + cancellationToken: cancellationToken); - foreach (var result in response.Results) - { - var document = result.Document; - var versions = new List(); - - if (document.Versions.Length != document.VersionDownloads.Length) - { - throw new InvalidOperationException($"Invalid document {document.Key} with mismatched versions"); - } + var results = new List(); - for (var i = 0; i < document.Versions.Length; i++) - { - var version = NuGetVersion.Parse(document.Versions[i]); + foreach (var result in response.Results) + { + var document = result.Document; + var versions = new List(); - versions.Add(new SearchResultVersion - { - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(document.Id, version), - Version = document.Versions[i], - Downloads = long.Parse(document.VersionDownloads[i]), - }); - } + #pragma warning disable CS8602 + if (document.Versions.Length != document.VersionDownloads.Length) + #pragma warning restore CS8602 + { + throw new InvalidOperationException($"Invalid document {document.Key} with mismatched versions"); + } - var iconUrl = document.HasEmbeddedIcon - ? _url.GetPackageIconDownloadUrl(document.Id, NuGetVersion.Parse(document.Version)) - : document.IconUrl; + for (var i = 0; i < document.Versions.Length; i++) + { + var version = NuGetVersion.Parse(document.Versions[i]); - results.Add(new SearchResult + versions.Add(new SearchResultVersion { - PackageId = document.Id, - Version = document.Version, - Description = document.Description, - Authors = document.Authors, - IconUrl = iconUrl, - LicenseUrl = document.LicenseUrl, - ProjectUrl = document.ProjectUrl, - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(document.Id), - Summary = document.Summary, - Tags = document.Tags, - Title = document.Title, - TotalDownloads = document.TotalDownloads, - Versions = versions + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(document.Id, version), + Version = document.Versions[i], + Downloads = long.Parse(document.VersionDownloads[i]), }); } - return new SearchResponse + #pragma warning disable CS8604 + var iconUrl = document.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(document.Id, NuGetVersion.Parse(document.Version)) + : document.IconUrl; + #pragma warning restore CS8604 + + results.Add(new SearchResult { - TotalHits = response.Count.Value, - Data = results, - Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()) - }; + PackageId = document.Id, + Version = document.Version, + Description = document.Description, + Authors = document.Authors, + IconUrl = iconUrl, + LicenseUrl = document.LicenseUrl, + ProjectUrl = document.ProjectUrl, + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(document.Id), + Summary = document.Summary, + Tags = document.Tags, + Title = document.Title, + TotalDownloads = document.TotalDownloads, + Versions = versions + }); } - public async Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) + #pragma warning disable CS8629 + return new SearchResponse { - // TODO: Do a prefix search on the package id field. - // TODO: Support prerelease, semver2, and package type filters. - // See: https://github.com/loic-sharma/BaGet/issues/291 - var parameters = new SearchParameters - { - IncludeTotalResultCount = true, - Skip = request.Skip, - Top = request.Take, - }; - - var response = await _searchClient.Documents.SearchAsync( - request.Query, - parameters, + TotalHits = response.Count.Value, + Data = results, + Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()) + }; + #pragma warning restore CS8629 + } + + public async Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + var parameters = new SearchParameters + { + IncludeTotalResultCount = true, + QueryType = QueryType.Full, + Skip = request.Skip, + Top = request.Take, + + // The index holds one document per package id per search filter, so without this + // the same id is returned up to four times and the total hit count is inflated. + Filter = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2), + }; + + var response = await _searchClient.Documents.SearchAsync( + BuildAutocompleteQuery(request.Query, request.PackageType), + parameters, + cancellationToken: cancellationToken); + + var results = response.Results + .Select(r => r.Document.Id) + .ToList() + .AsReadOnly(); + + #pragma warning disable CS8629 + return new AutocompleteResponse + { + TotalHits = response.Count.Value, + Data = results, + Context = AutocompleteContext.Default + }; + #pragma warning restore CS8629 + } + + public async Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + var filters = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2); + + // The exact lookup, for documents that have "normalizedId". + var response = await _searchClient.Documents.SearchAsync( + "*", + new SearchParameters { Top = 1, Filter = BuildVersionsFilter(request.PackageId, filters) }, + cancellationToken: cancellationToken); + + var document = response.Results.Select(r => r.Document).FirstOrDefault(); + + // A document indexed before "normalizedId" existed: a phrase query on "id" finds + // it among the IDs containing the same words, and the exact match is picked here. + if (document == null) + { + response = await _searchClient.Documents.SearchAsync( + $"id:{EscapeQueryPhrase(request.PackageId)}", + new SearchParameters { QueryType = QueryType.Full, Top = 50, Filter = filters }, cancellationToken: cancellationToken); - var results = response.Results - .Select(r => r.Document.Id) - .ToList() - .AsReadOnly(); + document = response.Results + .Select(r => r.Document) + .FirstOrDefault(d => string.Equals(d.Id, request.PackageId, StringComparison.OrdinalIgnoreCase)); + } - return new AutocompleteResponse - { - TotalHits = response.Count.Value, - Data = results, - Context = AutocompleteContext.Default - }; + var versions = document?.Versions ?? Array.Empty(); + + return new AutocompleteResponse + { + TotalHits = versions.Length, + Data = versions, + Context = AutocompleteContext.Default, + }; + } + + /// + /// The OData filter for one package ID's document under these search filters. + /// + internal static string BuildVersionsFilter(string? packageId, string searchFilter) + { + if (packageId == null) throw new ArgumentNullException(nameof(packageId)); + + // An OData string literal escapes a quote by doubling it. + var literal = packageId.ToLowerInvariant().Replace("'", "''"); + + return $"normalizedId eq '{literal}' and {searchFilter}"; + } + + /// + /// The full Lucene query for autocomplete: a prefix match on the whole ID, or, for a + /// document indexed before "normalizedId" existed, the analyzed match autocomplete + /// always made; plus the package type, if one was asked for. + /// + internal static string BuildAutocompleteQuery(string? query, string? packageType) + { + var builder = new StringBuilder(); + + var term = EscapeQueryTerm((query ?? string.Empty).Trim().TrimEnd('*').ToLowerInvariant()); + if (term.Length > 0) + { + builder.Append("+(normalizedId:"); + builder.Append(term); + builder.Append("* OR "); + builder.Append(term); + builder.Append(')'); } - public Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) + if (!string.IsNullOrEmpty(packageType)) { - // TODO: Support versions autocomplete. - // See: https://github.com/loic-sharma/BaGet/issues/291 - throw new NotImplementedException(); + builder.Append(" +packageTypes:"); + builder.Append(EscapeQueryPhrase(packageType)); } - public async Task FindDependentsAsync( - string packageId, - CancellationToken cancellationToken) + var result = builder.ToString().Trim(); + + return result.Length == 0 ? "*" : result; + } + + public async Task FindDependentsAsync( + string? packageId, + CancellationToken cancellationToken) + { + var query = BuildDependentsQuery(packageId); + var parameters = new SearchParameters { - // TODO: Escape packageId. - var query = $"dependencies:{packageId.ToLowerInvariant()}"; - var parameters = new SearchParameters - { - IncludeTotalResultCount = true, - QueryType = QueryType.Full, - Skip = 0, - Top = 20, - }; - - var response = await _searchClient.Documents.SearchAsync(query, parameters, cancellationToken: cancellationToken); - var results = response.Results - .Select(r => new PackageDependent - { - Id = r.Document.Id, - Description = r.Document.Description, - TotalDownloads = r.Document.TotalDownloads - }) - .ToList() - .AsReadOnly(); - - return new DependentsResponse + IncludeTotalResultCount = true, + QueryType = QueryType.Full, + Skip = 0, + Top = 20, + }; + + var response = await _searchClient.Documents.SearchAsync(query, parameters, cancellationToken: cancellationToken); + var results = response.Results + .Select(r => new PackageDependent { - TotalHits = response.Count.Value, - Data = results - }; + Id = r.Document.Id, + Description = r.Document.Description, + TotalDownloads = r.Document.TotalDownloads + }) + .ToList() + .AsReadOnly(); + + #pragma warning disable CS8629 + return new DependentsResponse + { + TotalHits = response.Count.Value, + Data = results + }; + #pragma warning restore CS8629 + } + + /// + /// Builds the query that finds the packages which depend on . + /// It runs with , the full Lucene query syntax. + /// + internal static string BuildDependentsQuery(string? packageId) + { + if (packageId == null) + { + throw new ArgumentNullException(nameof(packageId)); } - private string BuildSeachQuery(string query, string packageType, string framework) + // "dependencies" is indexed with ExactMatchCustomAnalyzer (a keyword tokenizer plus a + // lowercase filter) and holds lowercased ids, so the whole id must reach the analyzer + // as a single entity. + return $"dependencies:{EscapeQueryPhrase(packageId.ToLowerInvariant())}"; + } + + /// + /// Turns into a quoted phrase, which the full Lucene query parser + /// evaluates as a single literal entity, so that the value cannot change the meaning of the + /// query it is embedded in. + /// + /// + /// In an unquoted term the full Lucene syntax treats + /// + - & | ! ( ) { } [ ] ^ " ~ * ? : \ / as operators, and whitespace splits one + /// term into several - whitespace is not in that list and cannot be escaped, yet it is what + /// lets AND, OR and NOT become operators. Quoting solves both at once: + /// placement decides whether a symbol is an operator, and inside quotation marks every + /// character is content (wildcard, fuzzy, proximity and regex constructs are documented as + /// applying to a term, not to a phrase). That leaves exactly two significant characters, + /// each escaped here with a single backslash, the documented escape: + /// + /// ", which would end the phrase early; + /// \, the escape character itself, which would otherwise swallow + /// the character after it - a trailing one would escape the closing quotation mark. + /// + /// Neither is legal in a NuGet package id, so an ordinary id is emitted verbatim between + /// quotation marks and no backslash ever reaches the parser for a real id. + /// See https://learn.microsoft.com/azure/search/query-lucene-syntax. + /// + /// + /// Escapes the characters that are syntax in the full Lucene query the search runs + /// with, leaving the value usable as a term. Unlike + /// this does not quote, so a caller may still append a trailing "*" to make the term + /// a prefix query. + /// + /// + /// See the escaping rules for the full Lucene syntax: + /// https://learn.microsoft.com/en-us/azure/search/query-lucene-syntax + /// + internal static string EscapeQueryTerm(string? value) + { + if (value == null) { - var queryBuilder = new StringBuilder(); + throw new ArgumentNullException(nameof(value)); + } + + const string special = @"+-&|!(){}[]^""~*?:\/"; + var builder = new StringBuilder(value.Length); - if (!string.IsNullOrEmpty(query)) + foreach (var character in value) + { + if (special.IndexOf(character) >= 0) { - queryBuilder.Append(query.TrimEnd().TrimEnd('*')); - queryBuilder.Append('*'); + builder.Append('\\'); } - if (!string.IsNullOrEmpty(packageType)) + builder.Append(character); + } + + return builder.ToString(); + } + + internal static string EscapeQueryPhrase(string? value) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + var builder = new StringBuilder(value.Length + 2); + + builder.Append('"'); + + foreach (var character in value) + { + if (character == '"' || character == '\\') { - queryBuilder.Append(" +packageTypes:"); - queryBuilder.Append(packageType); + builder.Append('\\'); } - if (!string.IsNullOrEmpty(framework)) - { - var frameworks = _frameworks.FindAllCompatibleFrameworks(framework); + builder.Append(character); + } - queryBuilder.Append(" +frameworks:("); - queryBuilder.Append(string.Join(" ", frameworks)); - queryBuilder.Append(')'); - } + builder.Append('"'); + + return builder.ToString(); + } - return queryBuilder.ToString(); + private string BuildSeachQuery(string? query, string? packageType, string? framework) + { + var frameworks = string.IsNullOrEmpty(framework) + ? null + : _frameworks.FindAllCompatibleFrameworks(framework); + + return BuildSearchQuery(query, packageType, frameworks); + } + + /// + /// Builds the full Lucene query. Every caller supplied value is escaped: the search + /// runs with , so an unescaped value would change the + /// meaning of the query rather than being matched against. + /// + internal static string BuildSearchQuery( + string? query, + string? packageType, + IReadOnlyList? frameworks) + { + var queryBuilder = new StringBuilder(); + + if (!string.IsNullOrEmpty(query)) + { + // Escaped as a term, not quoted as a phrase, so the "*" below still makes + // this a prefix query. + queryBuilder.Append(EscapeQueryTerm(query.TrimEnd().TrimEnd('*'))); + queryBuilder.Append('*'); } - private string BuildSearchFilter(bool includePrerelease, bool includeSemVer2) + if (!string.IsNullOrEmpty(packageType)) { - var searchFilters = SearchFilters.Default; + queryBuilder.Append(" +packageTypes:"); + queryBuilder.Append(EscapeQueryPhrase(packageType)); + } - if (includePrerelease) - { - searchFilters |= SearchFilters.IncludePrerelease; - } + if (frameworks != null && frameworks.Count > 0) + { + // An unrecognised moniker is returned as given by FindAllCompatibleFrameworks, + // so these values are caller controlled too. + queryBuilder.Append(" +frameworks:("); + queryBuilder.Append(string.Join(" ", frameworks.Select(EscapeQueryPhrase))); + queryBuilder.Append(')'); + } - if (includeSemVer2) - { - searchFilters |= SearchFilters.IncludeSemVer2; - } + return queryBuilder.ToString(); + } - return $"searchFilters eq '{searchFilters}'"; + /// + /// Builds the OData filter that selects the single document matching these search filters. + /// writes one document per + /// value, using the same enum name as its "searchFilters" field. + /// + internal static string BuildSearchFilter(bool includePrerelease, bool includeSemVer2) + { + var searchFilters = SearchFilters.Default; + + if (includePrerelease) + { + searchFilters |= SearchFilters.IncludePrerelease; + } + + if (includeSemVer2) + { + searchFilters |= SearchFilters.IncludeSemVer2; } + + return $"searchFilters eq '{searchFilters}'"; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs b/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs index 962ef04c2..118ff0e41 100644 --- a/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs +++ b/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs @@ -1,21 +1,20 @@ using System.Collections.Generic; using Microsoft.Azure.Search.Models; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// A custom analyzer for case insensitive exact match. +/// +public static class ExactMatchCustomAnalyzer { - /// - /// A custom analyzer for case insensitive exact match. - /// - public static class ExactMatchCustomAnalyzer - { - public const string Name = "baget-exact-match-analyzer"; + public const string Name = "baget-exact-match-analyzer"; - public static CustomAnalyzer Instance = new CustomAnalyzer( - Name, - TokenizerName.Keyword, - new List - { - TokenFilterName.Lowercase - }); - } -} + public static CustomAnalyzer Instance = new( + Name, + TokenizerName.Keyword, + new List + { + TokenFilterName.Lowercase + }); +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/IndexActionBuilder.cs b/src/BaGet.Azure/Search/IndexActionBuilder.cs index 4888e0349..c34e92ae1 100644 --- a/src/BaGet.Azure/Search/IndexActionBuilder.cs +++ b/src/BaGet.Azure/Search/IndexActionBuilder.cs @@ -5,114 +5,121 @@ using BaGet.Core; using Microsoft.Azure.Search.Models; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class IndexActionBuilder { - public class IndexActionBuilder + public virtual IReadOnlyList> AddPackage( + PackageRegistration registration) { - public virtual IReadOnlyList> AddPackage( - PackageRegistration registration) - { - return AddOrUpdatePackage(registration, isUpdate: false); - } + return AddOrUpdatePackage(registration, isUpdate: false); + } - public virtual IReadOnlyList> UpdatePackage( - PackageRegistration registration) - { - return AddOrUpdatePackage(registration, isUpdate: true); - } + public virtual IReadOnlyList> UpdatePackage( + PackageRegistration registration) + { + return AddOrUpdatePackage(registration, isUpdate: true); + } + + private IReadOnlyList> AddOrUpdatePackage( + PackageRegistration registration, + bool isUpdate) + { + var encodedId = EncodePackageId(registration.PackageId.ToLowerInvariant()); + var result = new List>(); - private IReadOnlyList> AddOrUpdatePackage( - PackageRegistration registration, - bool isUpdate) + for (var i = 0; i < 4; i++) { - var encodedId = EncodePackageId(registration.PackageId.ToLowerInvariant()); - var result = new List>(); + var includePrerelease = (i & 1) != 0; + var includeSemVer2 = (i & 2) != 0; + var searchFilters = (SearchFilters)i; - for (var i = 0; i < 4; i++) - { - var includePrerelease = (i & 1) != 0; - var includeSemVer2 = (i & 2) != 0; - var searchFilters = (SearchFilters)i; + var documentKey = $"{encodedId}-{searchFilters}"; + var filtered = registration.Packages.Where(p => p.Listed); - var documentKey = $"{encodedId}-{searchFilters}"; - var filtered = registration.Packages.Where(p => p.Listed); + if (!includePrerelease) + { + filtered = filtered.Where(p => !p.IsPrerelease); + } - if (!includePrerelease) - { - filtered = filtered.Where(p => !p.IsPrerelease); - } + if (!includeSemVer2) + { + filtered = filtered.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); + } - if (!includeSemVer2) + var versions = filtered.OrderBy(p => p.Version).ToList(); + if (versions.Count == 0) + { + if (isUpdate) { - filtered = filtered.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); - } + var action = IndexAction.Delete( + new KeyedDocument + { + Key = documentKey + }); - var versions = filtered.OrderBy(p => p.Version).ToList(); - if (versions.Count == 0) - { - if (isUpdate) - { - var action = IndexAction.Delete( - new KeyedDocument - { - Key = documentKey - }); - - result.Add(action); - } - - continue; + result.Add(action); } - var latest = versions.Last(); - var dependencies = latest - .Dependencies - .Select(d => d.Id?.ToLowerInvariant()) - .Where(d => d != null) - .Distinct() - .ToArray(); - - var document = new PackageDocument(); - - document.Key = $"{encodedId}-{searchFilters}"; - document.Id = latest.Id; - document.Version = latest.Version.ToFullString(); - document.Description = latest.Description; - document.Authors = latest.Authors; - document.HasEmbeddedIcon = latest.HasEmbeddedIcon; - document.IconUrl = latest.IconUrlString; - document.LicenseUrl = latest.LicenseUrlString; - document.ProjectUrl = latest.ProjectUrlString; - document.Published = latest.Published; - document.Summary = latest.Summary; - document.Tags = latest.Tags; - document.Title = latest.Title; - document.TotalDownloads = versions.Sum(p => p.Downloads); - document.DownloadsMagnitude = document.TotalDownloads.ToString().Length; - document.Versions = versions.Select(p => p.Version.ToFullString()).ToArray(); - document.VersionDownloads = versions.Select(p => p.Downloads.ToString()).ToArray(); - document.Dependencies = dependencies; - document.PackageTypes = latest.PackageTypes.Select(t => t.Name).ToArray(); - document.Frameworks = latest.TargetFrameworks.Select(f => f.Moniker.ToLowerInvariant()).ToArray(); - document.SearchFilters = searchFilters.ToString(); - - result.Add( - isUpdate - ? IndexAction.MergeOrUpload(document) - : IndexAction.Upload(document)); + continue; } - return result; + var latest = versions.Last(); + #pragma warning disable CS8604 + var dependencies = latest + .Dependencies + .Select(d => d.Id?.ToLowerInvariant()) + .Where(d => d != null) + .Distinct() + .ToArray(); + #pragma warning restore CS8604 + + var document = new PackageDocument(); + + document.Key = $"{encodedId}-{searchFilters}"; + document.Id = latest.Id; + #pragma warning disable CS8602 + document.NormalizedId = latest.Id.ToLowerInvariant(); + #pragma warning restore CS8602 + document.Version = latest.Version.ToFullString(); + document.Description = latest.Description; + document.Authors = latest.Authors; + document.HasEmbeddedIcon = latest.HasEmbeddedIcon; + document.IconUrl = latest.IconUrlString; + document.LicenseUrl = latest.LicenseUrlString; + document.ProjectUrl = latest.ProjectUrlString; + document.Published = latest.Published; + document.Summary = latest.Summary; + document.Tags = latest.Tags; + document.Title = latest.Title; + document.TotalDownloads = versions.Sum(p => p.Downloads); + document.DownloadsMagnitude = document.TotalDownloads.ToString().Length; + document.Versions = versions.Select(p => p.Version.ToFullString()).ToArray(); + document.VersionDownloads = versions.Select(p => p.Downloads.ToString()).ToArray(); + document.Dependencies = dependencies; + #pragma warning disable CS8604 + document.PackageTypes = latest.PackageTypes.Select(t => t.Name).ToArray(); + #pragma warning disable CS8602 + document.Frameworks = latest.TargetFrameworks.Select(f => f.Moniker.ToLowerInvariant()).ToArray(); + #pragma warning restore CS8602, CS8604 + document.SearchFilters = searchFilters.ToString(); + + result.Add( + isUpdate + ? IndexAction.MergeOrUpload(document) + : IndexAction.Upload(document)); } - private string EncodePackageId(string key) - { - // Keys can only contain letters, digits, underscore(_), dash(-), or equal sign(=). - // TODO: Align with NuGet.org's algorithm. - var bytes = Encoding.UTF8.GetBytes(key); - var base64 = Convert.ToBase64String(bytes); + return result; + } - return base64.Replace('+', '-').Replace('/', '_'); - } + private string EncodePackageId(string key) + { + // Keys can only contain letters, digits, underscore(_), dash(-), or equal sign(=). + // TODO: Align with NuGet.org's algorithm. + var bytes = Encoding.UTF8.GetBytes(key); + var base64 = Convert.ToBase64String(bytes); + + return base64.Replace('+', '-').Replace('/', '_'); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/PackageDocument.cs b/src/BaGet.Azure/Search/PackageDocument.cs index 65c1c3b68..5feb7206a 100644 --- a/src/BaGet.Azure/Search/PackageDocument.cs +++ b/src/BaGet.Azure/Search/PackageDocument.cs @@ -3,78 +3,87 @@ using Microsoft.Azure.Search; using Microsoft.Azure.Search.Models; -namespace BaGet.Azure +namespace BaGet.Azure; + +// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages +[SerializePropertyNamesAsCamelCase] +public class PackageDocument : KeyedDocument +{ + public const string IndexName = "packages"; + + [IsSearchable, IsFilterable, IsSortable] + public string? Id { get; set; } + + /// + /// The lowercased ID as a single token, for exact lookups and prefix matches; "id" + /// is split on "." and "-" by the default analyzer. An index created before this + /// field existed needs it added, and a document only has it once its package is + /// pushed again, so every query that uses it falls back for documents without it. + /// + [IsSearchable, IsFilterable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string? NormalizedId { get; set; } + + /// + /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. + /// + [IsSearchable, IsFilterable, IsSortable] + public string? Version { get; set; } + + [IsSearchable] + public string? Description { get; set; } + public string[]? Authors { get; set; } + public bool HasEmbeddedIcon { get; set; } + public string? IconUrl { get; set; } + public string? LicenseUrl { get; set; } + public string? ProjectUrl { get; set; } + public DateTimeOffset Published { get; set; } + + [IsSearchable] + public string? Summary { get; set; } + + [IsSearchable, IsFilterable, IsFacetable] + public string[]? Tags { get; set; } + + [IsSearchable] + public string? Title { get; set; } + + [IsFilterable, IsSortable] + public long TotalDownloads { get; set; } + + [IsFilterable, IsSortable] + public int DownloadsMagnitude { get; set; } + + /// + /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. + /// + public string[]? Versions { get; set; } + public string[]? VersionDownloads { get; set; } + + [IsSearchable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string?[]? Dependencies { get; set; } + + [IsSearchable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string?[]? PackageTypes { get; set; } + + [IsSearchable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string[]? Frameworks { get; set; } + + [IsFilterable] + public string? SearchFilters { get; set; } +} + +[SerializePropertyNamesAsCamelCase] +public class KeyedDocument : IKeyedDocument { - // See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages - [SerializePropertyNamesAsCamelCase] - public class PackageDocument : KeyedDocument - { - public const string IndexName = "packages"; - - [IsSearchable, IsFilterable, IsSortable] - public string Id { get; set; } - - /// - /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. - /// - [IsSearchable, IsFilterable, IsSortable] - public string Version { get; set; } - - [IsSearchable] - public string Description { get; set; } - public string[] Authors { get; set; } - public bool HasEmbeddedIcon { get; set; } - public string IconUrl { get; set; } - public string LicenseUrl { get; set; } - public string ProjectUrl { get; set; } - public DateTimeOffset Published { get; set; } - - [IsSearchable] - public string Summary { get; set; } - - [IsSearchable, IsFilterable, IsFacetable] - public string[] Tags { get; set; } - - [IsSearchable] - public string Title { get; set; } - - [IsFilterable, IsSortable] - public long TotalDownloads { get; set; } - - [IsFilterable, IsSortable] - public int DownloadsMagnitude { get; set; } - - /// - /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. - /// - public string[] Versions { get; set; } - public string[] VersionDownloads { get; set; } - - [IsSearchable] - [Analyzer(ExactMatchCustomAnalyzer.Name)] - public string[] Dependencies { get; set; } - - [IsSearchable] - [Analyzer(ExactMatchCustomAnalyzer.Name)] - public string[] PackageTypes { get; set; } - - [IsSearchable] - [Analyzer(ExactMatchCustomAnalyzer.Name)] - public string[] Frameworks { get; set; } - - [IsFilterable] - public string SearchFilters { get; set; } - } - - [SerializePropertyNamesAsCamelCase] - public class KeyedDocument : IKeyedDocument - { - [Key] - public string Key { get; set; } - } - - public interface IKeyedDocument - { - string Key { get; set; } - } + [Key] + public string? Key { get; set; } } + +public interface IKeyedDocument +{ + string? Key { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/SearchFilters.cs b/src/BaGet.Azure/Search/SearchFilters.cs index 9e3e90b52..1a4a2d003 100644 --- a/src/BaGet.Azure/Search/SearchFilters.cs +++ b/src/BaGet.Azure/Search/SearchFilters.cs @@ -1,31 +1,30 @@ using System; -namespace BaGet.Azure +namespace BaGet.Azure; + +// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/d3e6b7a3aa8ec9cb8b32bf860f2d4f0d6766ed92/src/NuGet.Services.AzureSearch/VersionList/SearchFilters.cs#L9 +[Flags] +public enum SearchFilters { - // Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/d3e6b7a3aa8ec9cb8b32bf860f2d4f0d6766ed92/src/NuGet.Services.AzureSearch/VersionList/SearchFilters.cs#L9 - [Flags] - public enum SearchFilters - { - /// - /// Exclude SemVer 2.0.0 and prerelease packages. - /// - Default = 0, + /// + /// Exclude SemVer 2.0.0 and prerelease packages. + /// + Default = 0, - /// - /// Include packages that have prerelease versions. Note that a package's dependency version ranges do not - /// affect the prerelease status of the package. This is in contrast of . - /// - IncludePrerelease = 1 << 0, + /// + /// Include packages that have prerelease versions. Note that a package's dependency version ranges do not + /// affect the prerelease status of the package. This is in contrast of . + /// + IncludePrerelease = 1 << 0, - /// - /// Include SemVer 2.0.0 packages. Note that SemVer 2.0.0 dependency version ranges make a package into a SemVer - /// 2.0.0 even if the package's own version string is SemVer 1.0.0. - /// - IncludeSemVer2 = 1 << 1, + /// + /// Include SemVer 2.0.0 packages. Note that SemVer 2.0.0 dependency version ranges make a package into a SemVer + /// 2.0.0 even if the package's own version string is SemVer 1.0.0. + /// + IncludeSemVer2 = 1 << 1, - /// - /// Include package that have prerelease versions and include SemVer 2.0.0 packages. - /// - IncludePrereleaseAndSemVer2 = IncludePrerelease | IncludeSemVer2, - } -} + /// + /// Include package that have prerelease versions and include SemVer 2.0.0 packages. + /// + IncludePrereleaseAndSemVer2 = IncludePrerelease | IncludeSemVer2, +} \ No newline at end of file diff --git a/src/BaGet.Azure/Storage/BlobStorageService.Streaming.cs b/src/BaGet.Azure/Storage/BlobStorageService.Streaming.cs new file mode 100644 index 000000000..0d7ac2b60 --- /dev/null +++ b/src/BaGet.Azure/Storage/BlobStorageService.Streaming.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Azure.Storage; +using Microsoft.Azure.Storage.Blob; + +namespace BaGet.Azure; + +/// +/// Streaming uploads on block blobs (). Chunks are staged as uncommitted blocks of a +/// temporary blob under .uploads/ (a block is not limited below, so no tail is kept); at commit the block list is +/// committed there and the blob is copied server side to its final path with an if-not-exists condition. The upload's content +/// type lives in a small .meta blob, whose existence is also what makes an upload with no block yet exist. +/// Memory per request: one block (). A blob holds at most 50 000 blocks, so the largest upload is +/// 50 000 chunks of up to (400 GB when chunks are large, less when they are small). +/// +public partial class BlobStorageService +{ + /// The size a chunk is cut into when staged. + internal const int BlockSize = 8 * 1024 * 1024; + + private const string GenericContentType = "application/octet-stream"; + + public async Task BeginUploadAsync(string contentType, CancellationToken cancellationToken = default) + { + var id = Guid.NewGuid().ToString("N"); + var meta = MetaBlob(id); + meta.Properties.ContentType = "text/plain"; + await meta.UploadTextAsync(string.IsNullOrEmpty(contentType) ? GenericContentType : contentType, cancellationToken).ConfigureAwait(false); + return id; + } + + public async Task AppendAsync(string uploadId, long offset, Stream chunk, CancellationToken cancellationToken = default) + { + if (chunk == null) throw new ArgumentNullException(nameof(chunk)); + + await EnsureExistsAsync(uploadId, cancellationToken).ConfigureAwait(false); + var blocks = await ListBlocksAsync(uploadId, cancellationToken).ConfigureAwait(false); + var length = blocks.Sum(b => b.Length); + if (length != offset) throw new StorageUploadOffsetException(length, offset); + + var temp = TempBlob(uploadId); + var index = blocks.Count; + var tracked = UploadDigestTracker.Shared.Track(uploadId, offset, chunk); + try + { + var stored = length; + + async Task StageAsync(ReadOnlyMemory block, CancellationToken ct) + { + using var body = StreamingStreams.AsStream(block); + await temp.PutBlockAsync(BlockId(index++), body, null, ct).ConfigureAwait(false); + stored += block.Length; + } + + var rest = await StreamPartitioner.SplitAsync(tracked, ReadOnlyMemory.Empty, BlockSize, StageAsync, cancellationToken).ConfigureAwait(false); + if (rest.Length > 0) await StageAsync(rest, cancellationToken).ConfigureAwait(false); + + tracked.Complete(stored); + return stored; + } + catch + { + tracked.Fail(); + throw; + } + } + + public async Task GetUploadLengthAsync(string uploadId, CancellationToken cancellationToken = default) + { + if (!IsUploadId(uploadId) || !await MetaBlob(uploadId).ExistsAsync(cancellationToken).ConfigureAwait(false)) return null; + + return (await ListBlocksAsync(uploadId, cancellationToken).ConfigureAwait(false)).Sum(b => b.Length); + } + + public async Task CommitAsync(string uploadId, string path, string? expectedSha256, CancellationToken cancellationToken = default) + { + await EnsureExistsAsync(uploadId, cancellationToken).ConfigureAwait(false); + + var blocks = await ListBlocksAsync(uploadId, cancellationToken).ConfigureAwait(false); + var length = blocks.Sum(b => b.Length); + var temp = TempBlob(uploadId); + var sha = UploadDigestTracker.Shared.TryComplete(uploadId, length); + + try + { + if (sha != null && expectedSha256 != null && !string.Equals(expectedSha256, sha, StringComparison.OrdinalIgnoreCase)) + { + throw new StorageDigestMismatchException(expectedSha256, sha); + } + + temp.Properties.ContentType = (await MetaBlob(uploadId).DownloadTextAsync(cancellationToken).ConfigureAwait(false)).Trim(); + await temp.PutBlockListAsync(blocks.Select(b => b.Name).ToList(), cancellationToken).ConfigureAwait(false); + + // Unknown when this node did not see every chunk: read the assembled blob once, streaming. + if (sha == null) + { + using var read = await temp.OpenReadAsync(cancellationToken).ConfigureAwait(false); + sha = await StreamingStorage.Sha256HexAsync(read, cancellationToken).ConfigureAwait(false); + } + + StreamingStorage.VerifyDigest(expectedSha256, sha); + + var target = _container.GetBlockBlobReference(path); + try + { + await target.StartCopyAsync( + temp.Uri, + sourceAccessCondition: null, + destAccessCondition: AccessCondition.GenerateIfNotExistsCondition(), + options: null, + operationContext: null, + cancellationToken: cancellationToken).ConfigureAwait(false); + await WaitForCopyAsync(target, cancellationToken).ConfigureAwait(false); + return new StorageCommitResult(StoragePutResult.Success, length, sha); + } + catch (StorageException e) when (e.IsAlreadyExistsException()) + { + string existing; + using (var stored = await target.OpenReadAsync(cancellationToken).ConfigureAwait(false)) + { + existing = await StreamingStorage.Sha256HexAsync(stored, cancellationToken).ConfigureAwait(false); + } + + return new StorageCommitResult( + string.Equals(existing, sha, StringComparison.Ordinal) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict, + length, + sha); + } + } + finally + { + await DeleteUploadAsync(uploadId).ConfigureAwait(false); + } + } + + public Task AbortAsync(string uploadId, CancellationToken cancellationToken = default) + => DeleteUploadAsync(uploadId); + + public async Task GetInfoAsync(string path, CancellationToken cancellationToken = default) + { + var blob = _container.GetBlockBlobReference(path); + try + { + await blob.FetchAttributesAsync(cancellationToken).ConfigureAwait(false); + return new StorageBlobInfo(blob.Properties.Length, blob.Properties.ContentType); + } + catch (StorageException e) when (e.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.NotFound) + { + return null; + } + } + + public async Task GetRangeAsync(string path, long offset, long? length, CancellationToken cancellationToken = default) + { + var blob = _container.GetBlockBlobReference(path); + Stream stream; + try + { + stream = await blob.OpenReadAsync(cancellationToken).ConfigureAwait(false); + } + catch (StorageException e) when (e.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.NotFound) + { + return null; + } + + try + { + var count = StreamingStorage.ResolveRange(stream.Length, offset, length); + stream.Seek(offset, SeekOrigin.Begin); + return new RangeReadStream(stream, count); + } + catch + { + stream.Dispose(); + throw; + } + } + + private static bool IsUploadId(string uploadId) => Guid.TryParseExact(uploadId, "N", out _); + + private CloudBlockBlob TempBlob(string uploadId) => _container.GetBlockBlobReference(StreamingStorage.UploadsFolder + "/" + uploadId); + + private CloudBlockBlob MetaBlob(string uploadId) => _container.GetBlockBlobReference(StreamingStorage.UploadsFolder + "/" + uploadId + ".meta"); + + // Fixed-length ids are required: every block of a blob has an id of the same length. + internal static string BlockId(int index) => Convert.ToBase64String(Encoding.ASCII.GetBytes(index.ToString("D8"))); + + // Base64 text does not sort like what it encodes (digits come after letters in its alphabet), so blocks are ordered by the + // index inside the id, never by the id text: that put a 5 GB blob (more than ~320 blocks) together out of order. + internal static int BlockIndex(string blockId) => int.Parse(Encoding.ASCII.GetString(Convert.FromBase64String(blockId)), System.Globalization.CultureInfo.InvariantCulture); + + internal static IEnumerable InUploadOrder(IEnumerable blockIds) => blockIds.OrderBy(BlockIndex); + + private async Task EnsureExistsAsync(string uploadId, CancellationToken cancellationToken) + { + if (!IsUploadId(uploadId) || !await MetaBlob(uploadId).ExistsAsync(cancellationToken).ConfigureAwait(false)) + { + throw new StorageUploadNotFoundException(uploadId); + } + } + + private async Task> ListBlocksAsync(string uploadId, CancellationToken cancellationToken) + { + try + { + var blocks = await TempBlob(uploadId).DownloadBlockListAsync(BlockListingFilter.Uncommitted, null, null, null, cancellationToken).ConfigureAwait(false); + return blocks.OrderBy(b => BlockIndex(b.Name)).ToList(); + } + catch (StorageException e) when (e.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.NotFound) + { + // Nothing staged yet: the blob itself does not exist. + return new List(); + } + } + + private static async Task WaitForCopyAsync(CloudBlockBlob target, CancellationToken cancellationToken) + { + while (true) + { + await target.FetchAttributesAsync(cancellationToken).ConfigureAwait(false); + var state = target.CopyState; + if (state == null || state.Status == CopyStatus.Success) return; + if (state.Status != CopyStatus.Pending) throw new IOException($"The copy of the upload ended as {state.Status}."); + + await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken).ConfigureAwait(false); + } + } + + private async Task DeleteUploadAsync(string uploadId) + { + UploadDigestTracker.Shared.Forget(uploadId); + if (!IsUploadId(uploadId)) return; + + await TempBlob(uploadId).DeleteIfExistsAsync().ConfigureAwait(false); + await MetaBlob(uploadId).DeleteIfExistsAsync().ConfigureAwait(false); + } +} diff --git a/src/BaGet.Azure/Storage/BlobStorageService.cs b/src/BaGet.Azure/Storage/BlobStorageService.cs index fe07efb38..7380c7728 100644 --- a/src/BaGet.Azure/Storage/BlobStorageService.cs +++ b/src/BaGet.Azure/Storage/BlobStorageService.cs @@ -1,85 +1,143 @@ using System; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using BaGet.Core; -using Microsoft.WindowsAzure.Storage; -using Microsoft.WindowsAzure.Storage.Blob; +using Microsoft.Azure.Storage; +using Microsoft.Azure.Storage.Blob; +using Microsoft.Extensions.Options; -namespace BaGet.Azure +namespace BaGet.Azure; + +// See: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Services/CloudBlobCoreFileStorageService.cs +public partial class BlobStorageService : IStreamingStorageService, IListableStorageService { - // See: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Services/CloudBlobCoreFileStorageService.cs - public class BlobStorageService : IStorageService + private readonly CloudBlobContainer _container; + private readonly TimeSpan _downloadUriExpiry; + + public BlobStorageService(IOptionsSnapshot options, CloudBlobContainer container) { - private readonly CloudBlobContainer _container; + if (options == null) throw new ArgumentNullException(nameof(options)); - public BlobStorageService(CloudBlobContainer container) + _container = container ?? throw new ArgumentNullException(nameof(container)); + _downloadUriExpiry = options.Value.DownloadUriExpiry; + + if (_downloadUriExpiry <= TimeSpan.Zero) { - _container = container ?? throw new ArgumentNullException(nameof(container)); + throw new ArgumentException( + $"The {nameof(AzureBlobStorageOptions.DownloadUriExpiry)} option must be greater than zero", + nameof(options)); } + } - public async Task GetAsync(string path, CancellationToken cancellationToken) + public async Task GetAsync(string path, CancellationToken cancellationToken) + { + try { return await _container .GetBlockBlobReference(path) .OpenReadAsync(cancellationToken); } + catch (StorageException e) when (e.RequestInformation?.HttpStatusCode == 404) + { + // The one "missing content" exception of IStorageService.GetAsync, as FileStorageService throws. + throw new FileNotFoundException("The blob '" + path + "' does not exist.", path, e); + } + } - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken) + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken) + { + var blob = _container.GetBlockBlobReference(path); + var accessPolicy = new SharedAccessBlobPolicy { - // TODO: Make expiry time configurable. - var blob = _container.GetBlockBlobReference(path); - var accessPolicy = new SharedAccessBlobPolicy - { - SharedAccessExpiryTime = DateTimeOffset.Now.Add(TimeSpan.FromMinutes(10)), - Permissions = SharedAccessBlobPermissions.Read - }; + SharedAccessExpiryTime = DateTimeOffset.UtcNow.Add(_downloadUriExpiry), + Permissions = SharedAccessBlobPermissions.Read + }; - var signature = blob.GetSharedAccessSignature(accessPolicy); - var result = new Uri(blob.Uri, signature); + var signature = blob.GetSharedAccessSignature(accessPolicy); + var result = new Uri(blob.Uri, signature); - return Task.FromResult(result); - } + return Task.FromResult(result); + } - public async Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken) - { - var blob = _container.GetBlockBlobReference(path); - var condition = AccessCondition.GenerateIfNotExistsCondition(); + public async Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken) + { + var blob = _container.GetBlockBlobReference(path); + var condition = AccessCondition.GenerateIfNotExistsCondition(); - blob.Properties.ContentType = contentType; + blob.Properties.ContentType = contentType; - try - { - await blob.UploadFromStreamAsync( - content, - condition, - options: null, - operationContext: null, - cancellationToken: cancellationToken); - - return StoragePutResult.Success; - } - catch (StorageException e) when (e.IsAlreadyExistsException()) + try + { + await blob.UploadFromStreamAsync( + content, + condition, + options: null, + operationContext: null, + cancellationToken: cancellationToken); + + return StoragePutResult.Success; + } + catch (StorageException e) when (e.IsAlreadyExistsException()) + { + using (var targetStream = await blob.OpenReadAsync(cancellationToken)) { - using (var targetStream = await blob.OpenReadAsync(cancellationToken)) - { - content.Position = 0; - return content.Matches(targetStream) - ? StoragePutResult.AlreadyExists - : StoragePutResult.Conflict; - } + content.Position = 0; + return content.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; } } + } + + /// + /// Every blob under a prefix, paged until the container says there is no more. The + /// sweep of abandoned staged uploads is the only caller, and without this a container + /// would keep them forever. + /// + public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // a "staging-archive" container entry. + var prefix = pathPrefix.TrimEnd('/') + "/"; + var paths = new List(); + BlobContinuationToken? continuation = null; - public async Task DeleteAsync(string path, CancellationToken cancellationToken) + do { - await _container - .GetBlockBlobReference(path) - .DeleteIfExistsAsync(cancellationToken); + var segment = await _container.ListBlobsSegmentedAsync( + prefix, + useFlatBlobListing: true, + blobListingDetails: BlobListingDetails.None, + maxResults: null, + currentToken: continuation, + options: null, + operationContext: null, + cancellationToken: cancellationToken); + + foreach (var item in segment.Results) + { + // The blob's name is already the path IStorageService takes, relative to + // the container. + if (item is CloudBlob blob) paths.Add(blob.Name); + } + + continuation = segment.ContinuationToken; } + while (continuation != null); + + return paths; + } + + public async Task DeleteAsync(string path, CancellationToken cancellationToken) + { + await _container + .GetBlockBlobReference(path) + .DeleteIfExistsAsync(cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/PackageEntity.cs b/src/BaGet.Azure/Table/PackageEntity.cs index 46e9a053d..07efcee4a 100644 --- a/src/BaGet.Azure/Table/PackageEntity.cs +++ b/src/BaGet.Azure/Table/PackageEntity.cs @@ -2,105 +2,104 @@ using BaGet.Core; using Microsoft.Azure.Cosmos.Table; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// The Azure Table Storage entity that maps to a . +/// The is the and +/// the is the . +/// +public class PackageEntity : TableEntity, IDownloadCount, IListed { - /// - /// The Azure Table Storage entity that maps to a . - /// The is the and - /// the is the . - /// - public class PackageEntity : TableEntity, IDownloadCount, IListed + public PackageEntity() { - public PackageEntity() - { - } + } - public string Id { get; set; } - public string NormalizedVersion { get; set; } - public string OriginalVersion { get; set; } - public string Authors { get; set; } - public string Description { get; set; } - public long Downloads { get; set; } - public bool HasReadme { get; set; } - public bool HasEmbeddedIcon { get; set; } - public bool IsPrerelease { get; set; } - public string Language { get; set; } - public bool Listed { get; set; } - public string MinClientVersion { get; set; } - public DateTime Published { get; set; } - public bool RequireLicenseAcceptance { get; set; } - public int SemVerLevel { get; set; } - public string ReleaseNotes { get; set; } - public string Summary { get; set; } - public string Title { get; set; } + public string? Id { get; set; } + public string? NormalizedVersion { get; set; } + public string? OriginalVersion { get; set; } + public string? Authors { get; set; } + public string? Description { get; set; } + public long Downloads { get; set; } + public bool HasReadme { get; set; } + public bool HasEmbeddedIcon { get; set; } + public bool IsPrerelease { get; set; } + public string? Language { get; set; } + public bool Listed { get; set; } + public string? MinClientVersion { get; set; } + public DateTime Published { get; set; } + public bool RequireLicenseAcceptance { get; set; } + public int SemVerLevel { get; set; } + public string? ReleaseNotes { get; set; } + public string? Summary { get; set; } + public string? Title { get; set; } - public string IconUrl { get; set; } - public string LicenseUrl { get; set; } - public string ProjectUrl { get; set; } + public string? IconUrl { get; set; } + public string? LicenseUrl { get; set; } + public string? ProjectUrl { get; set; } - public string RepositoryUrl { get; set; } - public string RepositoryType { get; set; } + public string? RepositoryUrl { get; set; } + public string? RepositoryType { get; set; } - public string Tags { get; set; } - public string Dependencies { get; set; } - public string PackageTypes { get; set; } - public string TargetFrameworks { get; set; } - } + public string? Tags { get; set; } + public string? Dependencies { get; set; } + public string? PackageTypes { get; set; } + public string? TargetFrameworks { get; set; } +} - /// - /// A single item in . - /// - public class DependencyModel - { - public string Id { get; set; } - public string VersionRange { get; set; } - public string TargetFramework { get; set; } - } +/// +/// A single item in . +/// +public class DependencyModel +{ + public string? Id { get; set; } + public string? VersionRange { get; set; } + public string? TargetFramework { get; set; } +} - /// - /// A single item in . - /// - public class PackageTypeModel - { - public string Name { get; set; } - public string Version { get; set; } - } +/// +/// A single item in . +/// +public class PackageTypeModel +{ + public string? Name { get; set; } + public string? Version { get; set; } +} - /// - /// The Azure Table Storage entity to update the column. - /// The is the and - /// the is the . - /// - public class PackageListingEntity : TableEntity, IListed +/// +/// The Azure Table Storage entity to update the column. +/// The is the and +/// the is the . +/// +public class PackageListingEntity : TableEntity, IListed +{ + public PackageListingEntity() { - public PackageListingEntity() - { - } - - public bool Listed { get; set; } } - /// - /// The Azure Table Storage entity to update the column. - /// The is the and - /// the is the . - /// - public class PackageDownloadsEntity : TableEntity, IDownloadCount - { - public PackageDownloadsEntity() - { - } - - public long Downloads { get; set; } - } + public bool Listed { get; set; } +} - internal interface IListed +/// +/// The Azure Table Storage entity to update the column. +/// The is the and +/// the is the . +/// +public class PackageDownloadsEntity : TableEntity, IDownloadCount +{ + public PackageDownloadsEntity() { - bool Listed { get; set; } } - public interface IDownloadCount - { - long Downloads { get; set; } - } + public long Downloads { get; set; } +} + +internal interface IListed +{ + bool Listed { get; set; } } + +public interface IDownloadCount +{ + long Downloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/PackageEntityExtensions.cs b/src/BaGet.Azure/Table/PackageEntityExtensions.cs index 52d2b87f5..36717169a 100644 --- a/src/BaGet.Azure/Table/PackageEntityExtensions.cs +++ b/src/BaGet.Azure/Table/PackageEntityExtensions.cs @@ -2,84 +2,78 @@ using System.Collections.Generic; using System.Linq; using BaGet.Core; -using Newtonsoft.Json; -namespace BaGet.Azure +namespace BaGet.Azure; + +public static class PackageEntityExtensions { - public static class PackageEntityExtensions + public static Package AsPackage(this PackageEntity entity) { - public static Package AsPackage(this PackageEntity entity) + return new Package { - return new Package - { - Id = entity.Id, - NormalizedVersionString = entity.NormalizedVersion, - OriginalVersionString = entity.OriginalVersion, + Id = entity.Id, + NormalizedVersionString = entity.NormalizedVersion, + OriginalVersionString = entity.OriginalVersion, - // TODO: Convert to System.Text.Json - Authors = JsonConvert.DeserializeObject(entity.Authors), - Description = entity.Description, - Downloads = entity.Downloads, - HasReadme = entity.HasReadme, - HasEmbeddedIcon = entity.HasEmbeddedIcon, - IsPrerelease = entity.IsPrerelease, - Language = entity.Language, - Listed = entity.Listed, - MinClientVersion = entity.MinClientVersion, - Published = entity.Published, - RequireLicenseAcceptance = entity.RequireLicenseAcceptance, - SemVerLevel = (SemVerLevel)entity.SemVerLevel, - Summary = entity.Summary, - Title = entity.Title, - ReleaseNotes = entity.ReleaseNotes, - IconUrl = ParseUri(entity.IconUrl), - LicenseUrl = ParseUri(entity.LicenseUrl), - ProjectUrl = ParseUri(entity.ProjectUrl), - RepositoryUrl = ParseUri(entity.RepositoryUrl), - RepositoryType = entity.RepositoryType, - Tags = JsonConvert.DeserializeObject(entity.Tags), - Dependencies = ParseDependencies(entity.Dependencies), - PackageTypes = ParsePackageTypes(entity.PackageTypes), - TargetFrameworks = ParseTargetFrameworks(entity.TargetFrameworks), - }; - } + Authors = TableJson.Deserialize(entity.Authors), + Description = entity.Description, + Downloads = entity.Downloads, + HasReadme = entity.HasReadme, + HasEmbeddedIcon = entity.HasEmbeddedIcon, + IsPrerelease = entity.IsPrerelease, + Language = entity.Language, + Listed = entity.Listed, + MinClientVersion = entity.MinClientVersion, + Published = entity.Published, + RequireLicenseAcceptance = entity.RequireLicenseAcceptance, + SemVerLevel = (SemVerLevel)entity.SemVerLevel, + Summary = entity.Summary, + Title = entity.Title, + ReleaseNotes = entity.ReleaseNotes, + IconUrl = ParseUri(entity.IconUrl), + LicenseUrl = ParseUri(entity.LicenseUrl), + ProjectUrl = ParseUri(entity.ProjectUrl), + RepositoryUrl = ParseUri(entity.RepositoryUrl), + RepositoryType = entity.RepositoryType, + Tags = TableJson.Deserialize(entity.Tags), + Dependencies = ParseDependencies(entity.Dependencies), + PackageTypes = ParsePackageTypes(entity.PackageTypes), + TargetFrameworks = ParseTargetFrameworks(entity.TargetFrameworks), + }; + } - private static Uri ParseUri(string input) - { - return string.IsNullOrEmpty(input) ? null : new Uri(input); - } + private static Uri? ParseUri(string? input) + { + return string.IsNullOrEmpty(input) ? null : new Uri(input); + } - private static List ParseDependencies(string input) - { - // TODO: Convert to System.Text.Json - return JsonConvert.DeserializeObject>(input) - .Select(e => new PackageDependency - { - Id = e.Id, - VersionRange = e.VersionRange, - TargetFramework = e.TargetFramework, - }) - .ToList(); - } + private static List ParseDependencies(string? input) + { + return TableJson.Deserialize>(input) + .Select(e => new PackageDependency + { + Id = e.Id, + VersionRange = e.VersionRange, + TargetFramework = e.TargetFramework, + }) + .ToList(); + } - private static List ParsePackageTypes(string input) - { - // TODO: Convert to System.Text.Json - return JsonConvert.DeserializeObject>(input) - .Select(e => new PackageType - { - Name = e.Name, - Version = e.Version - }) - .ToList(); - } + private static List ParsePackageTypes(string? input) + { + return TableJson.Deserialize>(input) + .Select(e => new PackageType + { + Name = e.Name, + Version = e.Version + }) + .ToList(); + } - private static List ParseTargetFrameworks(string targetFrameworks) - { - // TODO: Convert to System.Text.Json - return JsonConvert.DeserializeObject>(targetFrameworks) - .Select(f => new TargetFramework { Moniker = f }) - .ToList(); - } + private static List ParseTargetFrameworks(string? targetFrameworks) + { + return TableJson.Deserialize>(targetFrameworks) + .Select(f => new TargetFramework { Moniker = f }) + .ToList(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TableJson.cs b/src/BaGet.Azure/Table/TableJson.cs new file mode 100644 index 000000000..3af0b7f59 --- /dev/null +++ b/src/BaGet.Azure/Table/TableJson.cs @@ -0,0 +1,25 @@ +using System.Text.Encodings.Web; +using System.Text.Json; + +namespace BaGet.Azure; + +/// +/// The JSON held in the table's string columns (authors, tags, dependencies, package +/// types, frameworks). Rows written by earlier versions used Newtonsoft.Json, so this +/// keeps that format: property names as declared, and non-ASCII text unescaped. +/// +internal static class TableJson +{ + internal static readonly JsonSerializerOptions Options = new() + { + // Newtonsoft matched property names case-insensitively, so older rows may differ in case. + PropertyNameCaseInsensitive = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + public static string Serialize(T value) => JsonSerializer.Serialize(value, Options); + + #pragma warning disable CS8603, CS8604 + public static T Deserialize(string? json) => JsonSerializer.Deserialize(json, Options); + #pragma warning restore CS8603, CS8604 +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TableOperationBuilder.cs b/src/BaGet.Azure/Table/TableOperationBuilder.cs index db4742ad4..a3e48f1a1 100644 --- a/src/BaGet.Azure/Table/TableOperationBuilder.cs +++ b/src/BaGet.Azure/Table/TableOperationBuilder.cs @@ -3,128 +3,136 @@ using System.Linq; using BaGet.Core; using Microsoft.Azure.Cosmos.Table; -using Newtonsoft.Json; using NuGet.Versioning; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class TableOperationBuilder { - public class TableOperationBuilder + public TableOperation AddPackage(Package package) { - public TableOperation AddPackage(Package package) - { - if (package == null) throw new ArgumentNullException(nameof(package)); - - var version = package.Version; - var normalizedVersion = version.ToNormalizedString(); - - var entity = new PackageEntity - { - PartitionKey = package.Id.ToLowerInvariant(), - RowKey = normalizedVersion.ToLowerInvariant(), - - Id = package.Id, - NormalizedVersion = normalizedVersion, - OriginalVersion = version.ToFullString(), - Authors = JsonConvert.SerializeObject(package.Authors), - Description = package.Description, - Downloads = package.Downloads, - HasReadme = package.HasReadme, - HasEmbeddedIcon = package.HasEmbeddedIcon, - IsPrerelease = package.IsPrerelease, - Language = package.Language, - Listed = package.Listed, - MinClientVersion = package.MinClientVersion, - Published = package.Published, - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - SemVerLevel = (int)package.SemVerLevel, - Summary = package.Summary, - Title = package.Title, - IconUrl = package.IconUrlString, - LicenseUrl = package.LicenseUrlString, - ReleaseNotes = package.ReleaseNotes, - ProjectUrl = package.ProjectUrlString, - RepositoryUrl = package.RepositoryUrlString, - RepositoryType = package.RepositoryType, - Tags = JsonConvert.SerializeObject(package.Tags), - Dependencies = SerializeList(package.Dependencies, AsDependencyModel), - PackageTypes = SerializeList(package.PackageTypes, AsPackageTypeModel), - TargetFrameworks = SerializeList(package.TargetFrameworks, f => f.Moniker) - }; - - return TableOperation.Insert(entity); - } - - public TableOperation UpdateDownloads(string packageId, NuGetVersion packageVersion, long downloads) + if (package == null) throw new ArgumentNullException(nameof(package)); + + var version = package.Version; + var normalizedVersion = version.ToNormalizedString(); + + #pragma warning disable CS8602 + var entity = new PackageEntity { - var entity = new PackageDownloadsEntity(); + PartitionKey = package.Id.ToLowerInvariant(), + RowKey = normalizedVersion.ToLowerInvariant(), + + Id = package.Id, + NormalizedVersion = normalizedVersion, + OriginalVersion = version.ToFullString(), + Authors = TableJson.Serialize(package.Authors), + Description = package.Description, + Downloads = package.Downloads, + HasReadme = package.HasReadme, + HasEmbeddedIcon = package.HasEmbeddedIcon, + IsPrerelease = package.IsPrerelease, + Language = package.Language, + Listed = package.Listed, + MinClientVersion = package.MinClientVersion, + Published = package.Published, + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + SemVerLevel = (int)package.SemVerLevel, + Summary = package.Summary, + Title = package.Title, + IconUrl = package.IconUrlString, + LicenseUrl = package.LicenseUrlString, + ReleaseNotes = package.ReleaseNotes, + ProjectUrl = package.ProjectUrlString, + RepositoryUrl = package.RepositoryUrlString, + RepositoryType = package.RepositoryType, + Tags = TableJson.Serialize(package.Tags), + Dependencies = SerializeList(package.Dependencies, AsDependencyModel), + PackageTypes = SerializeList(package.PackageTypes, AsPackageTypeModel), + TargetFrameworks = SerializeList(package.TargetFrameworks, f => f.Moniker) + }; + #pragma warning restore CS8602 + + return TableOperation.Insert(entity); + } + + public TableOperation UpdateDownloads(string packageId, NuGetVersion packageVersion, long downloads) + { + var entity = new PackageDownloadsEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.Downloads = downloads; - entity.ETag = "*"; + entity.PartitionKey = packageId.ToLowerInvariant(); + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.Downloads = downloads; + entity.ETag = "*"; - return TableOperation.Merge(entity); - } + return TableOperation.Merge(entity); + } - public TableOperation HardDeletePackage(string packageId, NuGetVersion packageVersion) - { - var entity = new PackageEntity(); + public TableOperation HardDeletePackage(string? packageId, NuGetVersion packageVersion) + { + var entity = new PackageEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.ETag = "*"; + #pragma warning disable CS8602 + entity.PartitionKey = packageId.ToLowerInvariant(); + #pragma warning restore CS8602 + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.ETag = "*"; - return TableOperation.Delete(entity); - } + return TableOperation.Delete(entity); + } - public TableOperation UnlistPackage(string packageId, NuGetVersion packageVersion) - { - var entity = new PackageListingEntity(); + public TableOperation UnlistPackage(string? packageId, NuGetVersion packageVersion) + { + var entity = new PackageListingEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.Listed = false; - entity.ETag = "*"; + #pragma warning disable CS8602 + entity.PartitionKey = packageId.ToLowerInvariant(); + #pragma warning restore CS8602 + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.Listed = false; + entity.ETag = "*"; - return TableOperation.Merge(entity); - } + return TableOperation.Merge(entity); + } - public TableOperation RelistPackage(string packageId, NuGetVersion packageVersion) - { - var entity = new PackageListingEntity(); + public TableOperation RelistPackage(string? packageId, NuGetVersion packageVersion) + { + var entity = new PackageListingEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.Listed = true; - entity.ETag = "*"; + #pragma warning disable CS8602 + entity.PartitionKey = packageId.ToLowerInvariant(); + #pragma warning restore CS8602 + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.Listed = true; + entity.ETag = "*"; - return TableOperation.Merge(entity); - } + return TableOperation.Merge(entity); + } - private static string SerializeList(IReadOnlyList objects, Func map) - { - var data = objects.Select(map).ToList(); + private static string SerializeList(IReadOnlyList? objects, Func map) + { + #pragma warning disable CS8604 + var data = objects.Select(map).ToList(); + #pragma warning restore CS8604 - return JsonConvert.SerializeObject(data); - } + return TableJson.Serialize(data); + } - public static DependencyModel AsDependencyModel(PackageDependency dependency) + public static DependencyModel AsDependencyModel(PackageDependency dependency) + { + return new DependencyModel { - return new DependencyModel - { - Id = dependency.Id, - VersionRange = dependency.VersionRange, - TargetFramework = dependency.TargetFramework - }; - } - - public static PackageTypeModel AsPackageTypeModel(PackageType packageType) + Id = dependency.Id, + VersionRange = dependency.VersionRange, + TargetFramework = dependency.TargetFramework + }; + } + + public static PackageTypeModel AsPackageTypeModel(PackageType packageType) + { + return new PackageTypeModel { - return new PackageTypeModel - { - Name = packageType.Name, - Version = packageType.Version - }; - } + Name = packageType.Name, + Version = packageType.Version + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TablePackageDatabase.cs b/src/BaGet.Azure/Table/TablePackageDatabase.cs index 83174df4c..adbd2600b 100644 --- a/src/BaGet.Azure/Table/TablePackageDatabase.cs +++ b/src/BaGet.Azure/Table/TablePackageDatabase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -8,208 +8,274 @@ using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// Stores the metadata of packages using Azure Table Storage. +/// +public class TablePackageDatabase : IPackageDatabase { - /// - /// Stores the metadata of packages using Azure Table Storage. - /// - public class TablePackageDatabase : IPackageDatabase - { - private const string TableName = "Packages"; - private const int MaxPreconditionFailures = 5; - - private readonly TableOperationBuilder _operationBuilder; - private readonly CloudTable _table; - private readonly ILogger _logger; - - public TablePackageDatabase( - TableOperationBuilder operationBuilder, - CloudTableClient client, - ILogger logger) + private const string TableName = "Packages"; + private const int MaxPreconditionFailures = 5; + + private readonly TableOperationBuilder _operationBuilder; + private readonly CloudTable _table; + private readonly ILogger _logger; + private readonly IRepositoryContext? _repository; + + public TablePackageDatabase( + TableOperationBuilder operationBuilder, + CloudTableClient? client, + ILogger logger, + IRepositoryContext? repository = null) + { + _repository = repository; + _operationBuilder = operationBuilder ?? throw new ArgumentNullException(nameof(operationBuilder)); + _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + // The table has no repository column: it holds the default repository's packages only. Repositories beyond + // the default need a relational database (see RepositoryService), so reaching here for another one is a bug in + // the caller; refuse rather than serve the default repository's packages under another name. + private void RequireDefaultRepository() + { + if (_repository != null && !_repository.Current.IsDefault) { - _operationBuilder = operationBuilder ?? throw new ArgumentNullException(nameof(operationBuilder)); - _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + throw new NotSupportedException( + $"Azure Table storage supports only the '{Repository.DefaultName}' repository, not '{_repository.Current.Name}'; use a relational database for more repositories."); } + } - public async Task AddAsync(Package package, CancellationToken cancellationToken) + public async Task AddAsync(Package package, CancellationToken cancellationToken) + { + RequireDefaultRepository(); + try { - try - { - var operation = _operationBuilder.AddPackage(package); + var operation = _operationBuilder.AddPackage(package); - await _table.ExecuteAsync(operation, cancellationToken); - } - catch (StorageException e) when (e.IsAlreadyExistsException()) - { - return PackageAddResult.PackageAlreadyExists; - } - - return PackageAddResult.Success; + await _table.ExecuteAsync(operation, cancellationToken); } - - public async Task AddDownloadAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + catch (StorageException e) when (e.IsAlreadyExistsException()) { - var attempt = 0; + return PackageAddResult.PackageAlreadyExists; + } - while (true) - { - try - { - var operation = TableOperation.Retrieve( - id.ToLowerInvariant(), - version.ToNormalizedString().ToLowerInvariant()); + return PackageAddResult.Success; + } - var result = await _table.ExecuteAsync(operation, cancellationToken); - var entity = result.Result as PackageDownloadsEntity; + public async Task AddDownloadAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + RequireDefaultRepository(); + var attempt = 0; - if (entity == null) - { - return; - } + while (true) + { + try + { + var operation = TableOperation.Retrieve( + id.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant()); - entity.Downloads += 1; + var result = await _table.ExecuteAsync(operation, cancellationToken); + var entity = result.Result as PackageDownloadsEntity; - await _table.ExecuteAsync(TableOperation.Merge(entity), cancellationToken); - return; - } - catch (StorageException e) - when (attempt < MaxPreconditionFailures && e.IsPreconditionFailedException()) + if (entity == null) { - attempt++; - _logger.LogWarning( - e, - $"Retrying due to precondition failure, attempt {{Attempt}} of {MaxPreconditionFailures}..", - attempt); + return; } + + entity.Downloads += 1; + + await _table.ExecuteAsync(TableOperation.Merge(entity), cancellationToken); + return; + } + catch (StorageException e) + when (attempt < MaxPreconditionFailures && e.IsPreconditionFailedException()) + { + attempt++; + _logger.LogWarning( + e, + $"Retrying due to precondition failure, attempt {{Attempt}} of {MaxPreconditionFailures}..", + attempt); } } + } - public async Task ExistsAsync(string id, CancellationToken cancellationToken) - { - var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); - var query = new TableQuery() - .Select(MinimalColumnSet) - .Where(filter) - .Take(1); + public async Task ExistsAsync(string? id, CancellationToken cancellationToken) + { + RequireDefaultRepository(); + #pragma warning disable CS8602 + var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); + #pragma warning restore CS8602 + var query = new TableQuery() + .Select(MinimalColumnSet) + .Where(filter) + .Take(1); + + var result = await _table.ExecuteQuerySegmentedAsync(query, token: null, cancellationToken); + + return result.Results.Any(); + } - var result = await _table.ExecuteQuerySegmentedAsync(query, token: null, cancellationToken); + public async Task ExistsAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken) + { + RequireDefaultRepository(); + #pragma warning disable CS8602 + var operation = TableOperation.Retrieve( + id.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant(), + MinimalColumnSet); + #pragma warning restore CS8602 - return result.Results.Any(); - } + var execution = await _table.ExecuteAsync(operation, cancellationToken); + + return execution.Result is PackageEntity; + } - public async Task ExistsAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + public async Task> FindAsync(string? id, bool includeUnlisted, CancellationToken cancellationToken) + { + RequireDefaultRepository(); + #pragma warning disable CS8602 + var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); + #pragma warning restore CS8602 + if (!includeUnlisted) { - var operation = TableOperation.Retrieve( - id.ToLowerInvariant(), - version.ToNormalizedString().ToLowerInvariant(), - MinimalColumnSet); + filter = TableQuery.CombineFilters( + filter, + TableOperators.And, + TableQuery.GenerateFilterConditionForBool(nameof(PackageEntity.Listed), QueryComparisons.Equal, true)); + } - var execution = await _table.ExecuteAsync(operation, cancellationToken); + var query = new TableQuery().Where(filter); + var results = new List(); - return execution.Result is PackageEntity; - } + // Request 500 results at a time from the server. + TableContinuationToken? token = null; + query.TakeCount = 500; - public async Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken) + do { - var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); - if (!includeUnlisted) - { - filter = TableQuery.CombineFilters( - filter, - TableOperators.And, - TableQuery.GenerateFilterConditionForBool(nameof(PackageEntity.Listed), QueryComparisons.Equal, true)); - } + var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); - var query = new TableQuery().Where(filter); - var results = new List(); + token = segment.ContinuationToken; - // Request 500 results at a time from the server. - TableContinuationToken token = null; - query.TakeCount = 500; + // Write out the properties for each entity returned. + results.AddRange(segment.Results.Select(r => r.AsPackage())); + } + while (token != null); - do - { - var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); + return results.OrderBy(p => p.Version).ToList(); + } - token = segment.ContinuationToken; + public async Task FindOrNullAsync( + string? id, + NuGetVersion version, + bool includeUnlisted, + CancellationToken cancellationToken) + { + RequireDefaultRepository(); + #pragma warning disable CS8602 + var operation = TableOperation.Retrieve( + id.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant()); + #pragma warning restore CS8602 - // Write out the properties for each entity returned. - results.AddRange(segment.Results.Select(r => r.AsPackage())); - } - while (token != null); + var result = await _table.ExecuteAsync(operation, cancellationToken); + var entity = result.Result as PackageEntity; - return results.OrderBy(p => p.Version).ToList(); + if (entity == null) + { + return null; } - public async Task FindOrNullAsync( - string id, - NuGetVersion version, - bool includeUnlisted, - CancellationToken cancellationToken) + // Filter out the package if it's unlisted. + if (!includeUnlisted && !entity.Listed) { - var operation = TableOperation.Retrieve( - id.ToLowerInvariant(), - version.ToNormalizedString().ToLowerInvariant()); + return null; + } - var result = await _table.ExecuteAsync(operation, cancellationToken); - var entity = result.Result as PackageEntity; + return entity.AsPackage(); + } - if (entity == null) - { - return null; - } + public async Task HardDeletePackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + RequireDefaultRepository(); + return await TryUpdatePackageAsync( + _operationBuilder.HardDeletePackage(id, version), + cancellationToken); + } - // Filter out the package if it's unlisted. - if (!includeUnlisted && !entity.Listed) - { - return null; - } + public async Task RelistPackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + RequireDefaultRepository(); + return await TryUpdatePackageAsync( + _operationBuilder.RelistPackage(id, version), + cancellationToken); + } - return entity.AsPackage(); - } + public async Task UnlistPackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + RequireDefaultRepository(); + return await TryUpdatePackageAsync( + _operationBuilder.UnlistPackage(id, version), + cancellationToken); + } - public async Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await TryUpdatePackageAsync( - _operationBuilder.HardDeletePackage(id, version), - cancellationToken); - } + private List MinimalColumnSet => new() { "PartitionKey" }; - public async Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + private async Task TryUpdatePackageAsync(TableOperation operation, CancellationToken cancellationToken) + { + try { - return await TryUpdatePackageAsync( - _operationBuilder.RelistPackage(id, version), - cancellationToken); + await _table.ExecuteAsync(operation, cancellationToken); } - - public async Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + catch (StorageException e) when (e.IsNotFoundException()) { - return await TryUpdatePackageAsync( - _operationBuilder.UnlistPackage(id, version), - cancellationToken); + return false; } - private List MinimalColumnSet => new List { "PartitionKey" }; + return true; + } - private async Task TryUpdatePackageAsync(TableOperation operation, CancellationToken cancellationToken) - { - try - { - await _table.ExecuteAsync(operation, cancellationToken); - } - catch (StorageException e) when (e.IsNotFoundException()) - { - return false; - } + // Deprecation and vulnerability metadata are stored in relational tables. The Azure + // Table backend has no schema for them, and one cannot be verified without an Azure + // account, so it says so rather than silently discarding what it is given. + private const string MetadataNotSupported = + "Package deprecation and vulnerability metadata are not supported when the database is Azure Table storage."; + + public Task SetDeprecationAsync( + string? id, + NuGetVersion version, + PackageDeprecation deprecation, + CancellationToken cancellationToken) + { + throw new NotSupportedException(MetadataNotSupported); + } - return true; - } + public Task RemoveDeprecationAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + throw new NotSupportedException(MetadataNotSupported); + } + + public Task SetVulnerabilitiesAsync( + string id, + NuGetVersion version, + IReadOnlyList vulnerabilities, + CancellationToken cancellationToken) + { + throw new NotSupportedException(MetadataNotSupported); + } + + public Task> GetAllVulnerabilitiesAsync(CancellationToken cancellationToken) + { + // Nothing can have been stored, so there is nothing to report. + return Task.FromResult>(Array.Empty()); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TableSearchService.cs b/src/BaGet.Azure/Table/TableSearchService.cs index c5beb10a5..4239f3dd5 100644 --- a/src/BaGet.Azure/Table/TableSearchService.cs +++ b/src/BaGet.Azure/Table/TableSearchService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -7,203 +7,308 @@ using BaGet.Protocol.Models; using Microsoft.Azure.Cosmos.Table; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// is ignored: Azure Table storage cannot order by anything +/// but its keys, and sorting one page in memory would be wrong. +/// +public class TableSearchService : ISearchService { - public class TableSearchService : ISearchService + private const string TableName = "Packages"; + + private readonly CloudTable _table; + private readonly ISearchResponseBuilder _responseBuilder; + + public TableSearchService( + CloudTableClient? client, + ISearchResponseBuilder responseBuilder) + { + _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); + _responseBuilder = responseBuilder ?? throw new ArgumentNullException(nameof(responseBuilder)); + } + + public async Task SearchAsync( + SearchRequest request, + CancellationToken cancellationToken) { - private const string TableName = "Packages"; + var results = await SearchAsync( + request.Query, + request.Skip, + request.Take, + request.IncludePrerelease, + request.IncludeSemVer2, + cancellationToken); + + return _responseBuilder.BuildSearch(results.Page, results.TotalHits); + } - private readonly CloudTable _table; - private readonly ISearchResponseBuilder _responseBuilder; + public async Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + var results = await SearchAsync( + request.Query, + request.Skip, + request.Take, + request.IncludePrerelease, + request.IncludeSemVer2, + cancellationToken); - public TableSearchService( - CloudTableClient client, - ISearchResponseBuilder responseBuilder) - { - _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); - _responseBuilder = responseBuilder ?? throw new ArgumentNullException(nameof(responseBuilder)); - } + var packageIds = results.Page.Select(p => p.PackageId).ToList(); + + return _responseBuilder.BuildAutocomplete(packageIds, results.TotalHits); + } - public async Task SearchAsync( - SearchRequest request, - CancellationToken cancellationToken) + public async Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + // A package ID is one partition, so its versions are a single partition query. + var query = new TableQuery(); + query = query.Where(GenerateVersionsFilter(request.PackageId, request.IncludePrerelease, request.IncludeSemVer2)); + + var packages = await LoadPackagesAsync(query, maxPartitions: 1, cancellationToken); + var versions = packages + .OrderBy(p => p.Version) + .Select(p => p.Version.ToNormalizedString()) + .ToList(); + + return _responseBuilder.BuildAutocomplete(versions, versions.Count); + } + + public Task FindDependentsAsync(string? packageId, CancellationToken cancellationToken) + { + var response = _responseBuilder.BuildDependents(new List()); + + return Task.FromResult(response); + } + + /// + /// A page of package registrations and the number of registrations that matched, + /// disregarding skip and take. + /// + private readonly struct SearchPage + { + public SearchPage(List page, long totalHits) { - var results = await SearchAsync( - request.Query, - request.Skip, - request.Take, - request.IncludePrerelease, - request.IncludeSemVer2, - cancellationToken); - - return _responseBuilder.BuildSearch(results); + Page = page; + TotalHits = totalHits; } - public async Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) - { - var results = await SearchAsync( - request.Query, - request.Skip, - request.Take, - request.IncludePrerelease, - request.IncludeSemVer2, - cancellationToken); + public List Page { get; } - var packageIds = results.Select(p => p.PackageId).ToList(); + public long TotalHits { get; } + } - return _responseBuilder.BuildAutocomplete(packageIds); - } + private async Task SearchAsync( + string? searchText, + int skip, + int take, + bool includePrerelease, + bool includeSemVer2, + CancellationToken cancellationToken) + { + var filter = GenerateSearchFilter(searchText, includePrerelease, includeSemVer2); - public Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) - { - // TODO: Support versions autocomplete. - // See: https://github.com/loic-sharma/BaGet/issues/291 - var response = _responseBuilder.BuildAutocomplete(new List()); + var query = new TableQuery(); + query = query.Where(filter); + query.TakeCount = 500; - return Task.FromResult(response); - } + var results = await LoadPackagesAsync(query, maxPartitions: skip + take, cancellationToken); + + var registrations = results + .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) + .Select(group => new PackageRegistration(group.Key, group.ToList())) + .ToList(); - public Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + // Table storage cannot count. The scan above stops after "skip + take" partitions, + // so when it reached that limit there may be more: count them with a scan that + // reads only the partition keys of the matching rows. + var totalHits = registrations.Count < skip + take + ? registrations.Count + : await CountPartitionsAsync(filter, cancellationToken); + + var page = registrations + .Skip(skip) + .Take(take) + .ToList(); + + return new SearchPage(page, totalHits); + } + + private async Task CountPartitionsAsync(string filter, CancellationToken cancellationToken) + { + var query = new TableQuery() + .Where(filter) + .Select(new[] { "PartitionKey" }); + query.TakeCount = 1000; + + var partitionKeys = new List(); + TableContinuationToken? token = null; + do { - var response = _responseBuilder.BuildDependents(new List()); + var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); - return Task.FromResult(response); + token = segment.ContinuationToken; + partitionKeys.AddRange(segment.Results.Select(r => r.PartitionKey)); } + while (token != null); - private async Task> SearchAsync( - string searchText, - int skip, - int take, - bool includePrerelease, - bool includeSemVer2, - CancellationToken cancellationToken) + return CountPartitions(partitionKeys); + } + + /// + /// The number of package IDs among rows in partition key order: each ID is one + /// partition, and a partition's rows are contiguous. + /// + internal static long CountPartitions(IEnumerable partitionKeys) + { + long count = 0; + string? last = null; + + foreach (var key in partitionKeys) { - var query = new TableQuery(); - query = query.Where(GenerateSearchFilter(searchText, includePrerelease, includeSemVer2)); - query.TakeCount = 500; - - var results = await LoadPackagesAsync(query, maxPartitions: skip + take, cancellationToken); - - return results - .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) - .Select(group => new PackageRegistration(group.Key, group.ToList())) - .Skip(skip) - .Take(take) - .ToList(); + if (!string.Equals(key, last, StringComparison.Ordinal)) + { + count++; + last = key; + } } - private async Task> LoadPackagesAsync( - TableQuery query, - int maxPartitions, - CancellationToken cancellationToken) - { - var results = new List(); + return count; + } - var partitions = 0; - string lastPartitionKey = null; - TableContinuationToken token = null; - do - { - var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); + private async Task> LoadPackagesAsync( + TableQuery query, + int maxPartitions, + CancellationToken cancellationToken) + { + var results = new List(); + + var partitions = 0; + string? lastPartitionKey = null; + TableContinuationToken? token = null; + do + { + var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); - token = segment.ContinuationToken; + token = segment.ContinuationToken; - foreach (var result in segment.Results) + foreach (var result in segment.Results) + { + if (lastPartitionKey != result.PartitionKey) { - if (lastPartitionKey != result.PartitionKey) - { - lastPartitionKey = result.PartitionKey; - partitions++; + lastPartitionKey = result.PartitionKey; + partitions++; - if (partitions > maxPartitions) - { - break; - } + // Enough partitions: stop rather than fetch segments only to skip them. + if (partitions > maxPartitions) + { + return results; } - - results.Add(result.AsPackage()); } - } - while (token != null); - return results; + results.Add(result.AsPackage()); + } } + while (token != null); - private string GenerateSearchFilter(string searchText, bool includePrerelease, bool includeSemVer2) + return results; + } + + /// + /// The rows of one package ID that these filters allow. + /// + internal static string GenerateVersionsFilter(string? packageId, bool includePrerelease, bool includeSemVer2) + { + if (packageId == null) throw new ArgumentNullException(nameof(packageId)); + + var partition = TableQuery.GenerateFilterCondition( + "PartitionKey", + QueryComparisons.Equal, + packageId.ToLowerInvariant()); + + return GenerateFilters(partition, includePrerelease, includeSemVer2); + } + + internal static string GenerateSearchFilter(string? searchText, bool includePrerelease, bool includeSemVer2) + { + var result = ""; + + if (!string.IsNullOrWhiteSpace(searchText)) { - var result = ""; + // Filter to rows where the "searchText" prefix matches on the partition key. + // Partition keys are lowercased IDs, and the comparison is ordinal, so the + // prefix must be lowercased too or a capitalised query matches nothing. + var prefix = searchText.TrimEnd().Split(separator: null).Last().ToLowerInvariant(); - if (!string.IsNullOrWhiteSpace(searchText)) - { - // Filter to rows where the "searchText" prefix matches on the partition key. - var prefix = searchText.TrimEnd().Split(separator: null).Last(); + var prefixLower = prefix; + var prefixUpper = prefix + "~"; - var prefixLower = prefix; - var prefixUpper = prefix + "~"; + var partitionLowerFilter = TableQuery.GenerateFilterCondition( + "PartitionKey", + QueryComparisons.GreaterThanOrEqual, + prefixLower); - var partitionLowerFilter = TableQuery.GenerateFilterCondition( - "PartitionKey", - QueryComparisons.GreaterThanOrEqual, - prefixLower); + var partitionUpperFilter = TableQuery.GenerateFilterCondition( + "PartitionKey", + QueryComparisons.LessThanOrEqual, + prefixUpper); - var partitionUpperFilter = TableQuery.GenerateFilterCondition( - "PartitionKey", - QueryComparisons.LessThanOrEqual, - prefixUpper); + result = TableQuery.CombineFilters(partitionLowerFilter, TableOperators.And, partitionUpperFilter); + } - result = GenerateAnd(partitionLowerFilter, partitionUpperFilter); - } + return GenerateFilters(result, includePrerelease, includeSemVer2); + } + + private static string GenerateFilters(string result, bool includePrerelease, bool includeSemVer2) + { + // Filter to rows that are listed. + result = GenerateAnd( + result, + GenerateIsTrue(nameof(PackageEntity.Listed))); - // Filter to rows that are listed. + if (!includePrerelease) + { result = GenerateAnd( result, - GenerateIsTrue(nameof(PackageEntity.Listed))); - - if (!includePrerelease) - { - result = GenerateAnd( - result, - GenerateIsFalse(nameof(PackageEntity.IsPrerelease))); - } + GenerateIsFalse(nameof(PackageEntity.IsPrerelease))); + } - if (!includeSemVer2) - { - result = GenerateAnd( - result, - TableQuery.GenerateFilterConditionForInt( - nameof(PackageEntity.SemVerLevel), - QueryComparisons.Equal, - 0)); - } + if (!includeSemVer2) + { + result = GenerateAnd( + result, + TableQuery.GenerateFilterConditionForInt( + nameof(PackageEntity.SemVerLevel), + QueryComparisons.Equal, + 0)); + } - return result; + return result; - string GenerateAnd(string left, string right) - { - if (string.IsNullOrEmpty(left)) return right; + string GenerateAnd(string left, string right) + { + if (string.IsNullOrEmpty(left)) return right; - return TableQuery.CombineFilters(left, TableOperators.And, right); - } + return TableQuery.CombineFilters(left, TableOperators.And, right); + } - string GenerateIsTrue(string propertyName) - { - return TableQuery.GenerateFilterConditionForBool( - propertyName, - QueryComparisons.Equal, - givenValue: true); - } + string GenerateIsTrue(string propertyName) + { + return TableQuery.GenerateFilterConditionForBool( + propertyName, + QueryComparisons.Equal, + givenValue: true); + } - string GenerateIsFalse(string propertyName) - { - return TableQuery.GenerateFilterConditionForBool( - propertyName, - QueryComparisons.Equal, - givenValue: false); - } + string GenerateIsFalse(string propertyName) + { + return TableQuery.GenerateFilterConditionForBool( + propertyName, + QueryComparisons.Equal, + givenValue: false); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Catalog/BaGet.Catalog.csproj b/src/BaGet.Catalog/BaGet.Catalog.csproj new file mode 100644 index 000000000..70af74d12 --- /dev/null +++ b/src/BaGet.Catalog/BaGet.Catalog.csproj @@ -0,0 +1,28 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's NuGet V3 catalog: an append-only log of package changes, for mirrors. + BaGet.Catalog + enable + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Catalog/Controllers/Protocols/CatalogController.cs b/src/BaGet.Catalog/Controllers/Protocols/CatalogController.cs new file mode 100644 index 000000000..bbfadb563 --- /dev/null +++ b/src/BaGet.Catalog/Controllers/Protocols/CatalogController.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using BaGet.Catalog.Storage; + +namespace BaGet.Catalog.Controllers.Protocols; + +/// +/// The Catalog/3.0.0 resource. +/// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource +/// +public class CatalogController : Controller +{ + private readonly CatalogReader _reader; + private readonly IRepositoryContext? _repository; + + public CatalogController(CatalogReader reader, IRepositoryContext? repository = null) + { + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + _repository = repository; + } + + /// + /// A database that cannot hold the catalog has none, so the whole surface is absent. So is a virtual repository's: it + /// stores nothing, and a merged log of its members would have no commit order a client could resume from. + /// + public override void OnActionExecuting(ActionExecutingContext context) + { + if (!_reader.IsSupported || _repository?.Current.Kind == RepositoryKind.Virtual) + { + context.Result = NotFound(); + return; + } + + base.OnActionExecuting(context); + } + + [HttpGet] + public async Task Index(CancellationToken cancellationToken) + { + return Json(await _reader.GetIndexAsync(cancellationToken)); + } + + [HttpGet] + public async Task Page(int pageIndex, CancellationToken cancellationToken) + { + var page = await _reader.GetPageOrNullAsync(pageIndex, cancellationToken); + if (page == null) + { + return NotFound(); + } + + return Json(page); + } + + [HttpGet] + public async Task Leaf(string commitId, CancellationToken cancellationToken) + { + string? leaf; + try + { + leaf = await _reader.GetLeafOrNullAsync(commitId, cancellationToken); + } + catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) + { + // The entry exists but its document does not, which "catalog rebuild" cannot + // repair: the leaf is a snapshot that was never written. + leaf = null; + } + + if (leaf == null) + { + return NotFound(); + } + + return Content(leaf, "application/json"); + } +} \ No newline at end of file diff --git a/src/BaGet.Catalog/Database/CatalogDatabase.cs b/src/BaGet.Catalog/Database/CatalogDatabase.cs new file mode 100644 index 000000000..7c6ccec0b --- /dev/null +++ b/src/BaGet.Catalog/Database/CatalogDatabase.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Catalog.Database; +/// +/// The catalog log in the relational database, beside the packages. +/// +public class CatalogDatabase : ICatalogDatabase +{ + private readonly IContext _context; + + public CatalogDatabase(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + public bool IsSupported => true; + + public async Task GetLastCommitTimestampAsync(CancellationToken cancellationToken) + { + // Entries are added in commit order, so the highest key is the newest. + #pragma warning disable CS8604 + var last = await _context.CatalogLeafs + .OrderByDescending(e => e.Key) + .Select(e => (DateTime?)e.CommitTimestamp) + .FirstOrDefaultAsync(cancellationToken); + #pragma warning restore CS8604 + + return last.HasValue ? AsUtc(last.Value) : (DateTime?)null; + } + + public async Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken) + { + _context.CatalogLeafs?.Add(entry); + + await _context.SaveChangesAsync(cancellationToken); + } + + public async Task> GetCommitTimestampsAsync(CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var timestamps = await _context.CatalogLeafs + .OrderBy(e => e.Key) + .Select(e => e.CommitTimestamp) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + return timestamps.Select(AsUtc).ToList(); + } + + public async Task<(int Count, IReadOnlyList PageEnds)> GetPageEndsAsync(int pageSize, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var count = await _context.CatalogLeafs.CountAsync(cancellationToken); + + var ends = new List(); + var pages = (count + pageSize - 1) / pageSize; + var lastKey = 0; + for (var page = 0; page < pages; page++) + { + // Keyset paging: each page costs its own size, not the number of entries before it. + var isLast = page == pages - 1; + var entries = _context.CatalogLeafs.AsNoTracking(); + if (isLast) + { + var latest = await entries.OrderByDescending(e => e.Key).Select(e => e.CommitTimestamp).FirstAsync(cancellationToken); + ends.Add(AsUtc(latest)); + break; + } + + var end = await entries + .Where(e => e.Key > lastKey) + .OrderBy(e => e.Key) + .Skip(pageSize - 1) + .Select(e => new { e.Key, e.CommitTimestamp }) + .FirstAsync(cancellationToken); + + lastKey = end.Key; + ends.Add(AsUtc(end.CommitTimestamp)); + } + #pragma warning restore CS8604 + + return (count, ends); + } + + public async Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var entries = await _context.CatalogLeafs + .AsNoTracking() + .OrderBy(e => e.Key) + .Skip(skip) + .Take(take) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + foreach (var entry in entries) + { + entry.CommitTimestamp = AsUtc(entry.CommitTimestamp); + } + + return entries; + } + + public async Task FindOrNullAsync(string commitId, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var entry = await _context.CatalogLeafs + .AsNoTracking() + .FirstOrDefaultAsync(e => e.CommitId == commitId, cancellationToken); + #pragma warning restore CS8604 + + if (entry != null) + { + entry.CommitTimestamp = AsUtc(entry.CommitTimestamp); + } + + return entry; + } + + // Every timestamp is written as UTC, but some providers, such as SQLite, read it + // back without a kind. + private static DateTime AsUtc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc); +} diff --git a/src/BaGet.Catalog/Database/ICatalogDatabase.cs b/src/BaGet.Catalog/Database/ICatalogDatabase.cs new file mode 100644 index 000000000..34537b904 --- /dev/null +++ b/src/BaGet.Catalog/Database/ICatalogDatabase.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; + +namespace BaGet.Catalog.Database; + +/// +/// Where the catalog log is kept. +/// +public interface ICatalogDatabase +{ + /// + /// False when the configured database cannot hold the catalog, such as Azure Table + /// storage. The catalog is then neither written nor advertised. + /// + bool IsSupported { get; } + + /// + /// The newest entry's commit timestamp, or null if the log is empty. + /// + Task GetLastCommitTimestampAsync(CancellationToken cancellationToken); + + Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken); + + /// + /// Every entry's commit timestamp, in commit order. Used to lay out the pages. + /// + Task> GetCommitTimestampsAsync(CancellationToken cancellationToken); + + /// + /// The number of entries and the commit timestamp of the last entry of each full or partial page of + /// entries: all the index needs, without reading every timestamp. + /// + /// The default derives it from . + async Task<(int Count, IReadOnlyList PageEnds)> GetPageEndsAsync(int pageSize, CancellationToken cancellationToken) + { + var all = await GetCommitTimestampsAsync(cancellationToken); + var ends = new List(); + for (var end = pageSize - 1; end < all.Count + pageSize - 1; end += pageSize) + { + ends.Add(all[Math.Min(end, all.Count - 1)]); + } + + return (all.Count, ends); + } + + /// + /// The entries in commit order, skipping . + /// + Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken); + + Task FindOrNullAsync(string commitId, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Catalog/Database/NullCatalogDatabase.cs b/src/BaGet.Catalog/Database/NullCatalogDatabase.cs new file mode 100644 index 000000000..0b0d808c1 --- /dev/null +++ b/src/BaGet.Catalog/Database/NullCatalogDatabase.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Catalog.Database; +/// +/// Used when the configured database cannot hold the catalog. +/// +public class NullCatalogDatabase : ICatalogDatabase +{ + public bool IsSupported => false; + + public Task GetLastCommitTimestampAsync(CancellationToken cancellationToken) + => Task.FromResult(null); + + public Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken) + => throw new NotSupportedException("The configured database does not support the catalog."); + + public Task> GetCommitTimestampsAsync(CancellationToken cancellationToken) + => Task.FromResult>(Array.Empty()); + + public Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken) + => Task.FromResult>(Array.Empty()); + + #pragma warning disable CS8619, CS8625 + public Task FindOrNullAsync(string commitId, CancellationToken cancellationToken) + => Task.FromResult(null); + #pragma warning restore CS8619, CS8625 +} \ No newline at end of file diff --git a/src/BaGet.Catalog/Extensions/CatalogServiceCollectionExtensions.cs b/src/BaGet.Catalog/Extensions/CatalogServiceCollectionExtensions.cs new file mode 100644 index 000000000..71564fd97 --- /dev/null +++ b/src/BaGet.Catalog/Extensions/CatalogServiceCollectionExtensions.cs @@ -0,0 +1,32 @@ +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using BaGet.Catalog.Database; +using BaGet.Catalog.Rebuild; +using BaGet.Catalog.ServiceIndex; +using BaGet.Catalog.Storage; + +namespace BaGet.Catalog.Extensions; + +public static class CatalogServiceCollectionExtensions +{ + public static IServiceCollection AddBaGetCatalog(this IServiceCollection services) + { + // A database without the catalog table, such as Azure Table storage, is + // registered as the null context; the catalog is then switched off. + services.TryAddScoped(provider => + provider.GetRequiredService() is NullContext + ? (ICatalogDatabase)new NullCatalogDatabase() + : new CatalogDatabase(provider.GetRequiredService())); + + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); + + return services; + } +} \ No newline at end of file diff --git a/src/BaGet.Catalog/README.md b/src/BaGet.Catalog/README.md new file mode 100644 index 000000000..0b76287db --- /dev/null +++ b/src/BaGet.Catalog/README.md @@ -0,0 +1,31 @@ +# Extension.BaGet.Catalog + +The NuGet V3 [catalog](https://learn.microsoft.com/nuget/api/catalog-resource) of +[BaGet Extension](https://pieroviano.github.io/BaGet/): an append-only log of package changes, which mirrors follow. + +```powershell +dotnet add package Extension.BaGet.Catalog +``` + +## Usage + +`AddBaGetWebApplication` (`Extension.BaGet.Web`) registers it; standalone: `services.AddBaGetCatalog()`. + +| Item | Role | +|---|---| +| `CatalogWriter` | `IPackageChangeHandler`: appends a catalog entry for every package change | +| `CatalogController`, `CatalogReader` | Serve `v3/catalog/index.json`, `v3/catalog/page{n}.json`, `v3/catalog/data/{commitId}.json` | +| `CatalogRebuilder` | Appends missing entries; run by the host's `catalog rebuild [-r ]` command or from `/admin/operations` (`CatalogRebuildOperation`); the catalog is per repository | +| `CatalogServiceIndexProvider` | Advertises the `Catalog/3.0.0` resource in the service index | + +A database without the catalog table (Azure Table storage) gets `NullCatalogDatabase`: the catalog is off. + +To read a catalog, use `CatalogProcessor` in `Extension.BaGet.Protocol`. + +## Layout + +One type per file, namespace = `BaGet.Catalog` + folder (`CodeLayoutTests`): `Controllers/Protocols` (`CatalogController`), `Database` (`ICatalogDatabase`, `CatalogDatabase`, `NullCatalogDatabase`), `Storage` (`CatalogReader`, `CatalogWriter`), `Rebuild` (`CatalogRebuilder`, `CatalogRebuildOperation`), `ServiceIndex`, `Extensions` (`AddBaGetCatalog`). + +## Links + +[Documentation](https://pieroviano.github.io/BaGet/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Catalog/Rebuild/CatalogRebuildOperation.cs b/src/BaGet.Catalog/Rebuild/CatalogRebuildOperation.cs new file mode 100644 index 000000000..aed9f26ed --- /dev/null +++ b/src/BaGet.Catalog/Rebuild/CatalogRebuildOperation.cs @@ -0,0 +1,28 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Catalog.Database; + +namespace BaGet.Catalog.Rebuild; + +/// The catalog rebuild command as an . +public sealed class CatalogRebuildOperation : IAdminOperation +{ + public string Name => "catalog-rebuild"; + + public string Title => "Rebuild the catalog"; + + public string Description => "Appends the catalog entries missing for the repository's packages (backfills packages pushed before the catalog existed, repairs failed commits)."; + + public bool IsAvailable(IServiceProvider services) + => services.GetRequiredService().IsSupported; + + public async Task RunAsync(IServiceProvider services, CancellationToken cancellationToken) + { + var (added, deleted) = await services.GetRequiredService().RebuildAsync(cancellationToken).ConfigureAwait(false); + + return $"{added} details entries and {deleted} delete entries appended."; + } +} diff --git a/src/BaGet.Catalog/Rebuild/CatalogRebuilder.cs b/src/BaGet.Catalog/Rebuild/CatalogRebuilder.cs new file mode 100644 index 000000000..576999a76 --- /dev/null +++ b/src/BaGet.Catalog/Rebuild/CatalogRebuilder.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using NuGet.Versioning; +using BaGet.Catalog.Database; +using BaGet.Catalog.Storage; + +namespace BaGet.Catalog.Rebuild; + +/// +/// Reconciles the catalog with the packages: appends a details entry for every package +/// version whose latest entry is missing or a delete, and a delete entry for every +/// version whose latest entry is details but which no longer exists. This backfills +/// packages pushed before the catalog existed, and repairs a commit that failed. +/// +/// +/// The log is append-only, so nothing is rewritten. A change whose commit failed while +/// the version kept existing, such as an unlist, cannot be detected and is not repaired. +/// +public class CatalogRebuilder +{ + private readonly ICatalogDatabase _catalog; + private readonly IContext _context; + private readonly CatalogWriter _writer; + private readonly ILogger _logger; + + public CatalogRebuilder( + ICatalogDatabase catalog, + IContext context, + CatalogWriter writer, + ILogger logger) + { + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _writer = writer ?? throw new ArgumentNullException(nameof(writer)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task<(int Added, int Deleted)> RebuildAsync(CancellationToken cancellationToken) + { + if (!_catalog.IsSupported) + { + _logger.LogWarning("The configured database does not support the catalog"); + return (0, 0); + } + + var latest = new Dictionary<(string, string), CatalogEntry>(); + for (var skip = 0; ; skip += CatalogReader.PageSize) + { + var entries = await _catalog.GetEntriesAsync(skip, CatalogReader.PageSize, cancellationToken); + foreach (var entry in entries) + { + latest[Identity(entry.PackageId, entry.PackageVersion)] = entry; + } + + if (entries.Count < CatalogReader.PageSize) break; + } + + #pragma warning disable CS8604 + var packages = await _context.Packages + .AsNoTracking() + .Select(p => new { p.Id, p.NormalizedVersionString }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + var existing = new HashSet<(string, string)>(); + var added = 0; + foreach (var package in packages.OrderBy(p => p.Id, StringComparer.OrdinalIgnoreCase)) + { + var identity = Identity(package.Id, package.NormalizedVersionString); + existing.Add(identity); + + if (latest.TryGetValue(identity, out var entry) && entry.Type == CatalogEntry.PackageDetailsType) + { + continue; + } + + #pragma warning disable CS8604 + await _writer.OnPackageChangedAsync( + package.Id, + NuGetVersion.Parse(package.NormalizedVersionString), + cancellationToken); + #pragma warning restore CS8604 + added++; + } + + var deleted = 0; + foreach (var pair in latest.Where(l => l.Value.Type == CatalogEntry.PackageDetailsType && !existing.Contains(l.Key))) + { + #pragma warning disable CS8604 + await _writer.OnPackageDeletedAsync( + pair.Value.PackageId, + NuGetVersion.Parse(pair.Value.PackageVersion), + cancellationToken); + #pragma warning restore CS8604 + deleted++; + } + + _logger.LogInformation( + "Catalog rebuilt: {Added} details entries and {Deleted} delete entries appended", + added, + deleted); + + return (added, deleted); + } + + // Package IDs are case insensitive. + #pragma warning disable CS8604, CS8619 + private static (string, string) Identity(string? id, string? version) + => (id?.ToLowerInvariant(), NuGetVersion.Parse(version).ToNormalizedString().ToLowerInvariant()); + #pragma warning restore CS8604, CS8619 +} \ No newline at end of file diff --git a/src/BaGet.Catalog/ServiceIndex/CatalogServiceIndexProvider.cs b/src/BaGet.Catalog/ServiceIndex/CatalogServiceIndexProvider.cs new file mode 100644 index 000000000..1a8a4b2b6 --- /dev/null +++ b/src/BaGet.Catalog/ServiceIndex/CatalogServiceIndexProvider.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Protocol.Models; +using BaGet.Catalog.Controllers.Protocols; +using BaGet.Catalog.Database; + +namespace BaGet.Catalog.ServiceIndex; + +/// +/// Advertises Catalog/3.0.0, unless the database cannot hold the catalog or the repository is virtual. +/// +public class CatalogServiceIndexProvider : IServiceIndexResourceProvider +{ + private readonly ICatalogDatabase _catalog; + private readonly IUrlGenerator _url; + private readonly IRepositoryContext? _repository; + + public CatalogServiceIndexProvider(ICatalogDatabase catalog, IUrlGenerator url, IRepositoryContext? repository = null) + { + _repository = repository; + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } + + public IEnumerable GetResources() + { + // A virtual repository has no catalog (CatalogController answers 404 there). + if (!_catalog.IsSupported || _repository?.Current.Kind == RepositoryKind.Virtual) yield break; + + yield return new ServiceIndexItem + { + ResourceUrl = _url.GetCatalogIndexUrl(), + Type = "Catalog/3.0.0", + }; + } +} \ No newline at end of file diff --git a/src/BaGet.Catalog/Storage/CatalogReader.cs b/src/BaGet.Catalog/Storage/CatalogReader.cs new file mode 100644 index 000000000..764f549ba --- /dev/null +++ b/src/BaGet.Catalog/Storage/CatalogReader.cs @@ -0,0 +1,111 @@ +using System; +using System.Linq; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Protocol.Models; +using BaGet.Catalog.Database; + +namespace BaGet.Catalog.Storage; + +/// +/// Builds the catalog documents. The index and pages are built from the database on +/// read, so their URLs always match the host the client used; the leaves are read from +/// storage, since a deleted package's details exist nowhere else. +/// +public class CatalogReader +{ + /// + /// nuget.org uses 550. Any size is valid; a client follows the index. + /// + internal const int PageSize = 500; + + private readonly ICatalogDatabase _catalog; + private readonly IStorageService _storage; + private readonly IUrlGenerator _url; + private readonly IRepositoryContext? _repository; + + public CatalogReader(ICatalogDatabase catalog, IStorageService storage, IUrlGenerator url, IRepositoryContext? repository = null) + { + _repository = repository; + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } + + public bool IsSupported => _catalog.IsSupported; + + public async Task GetIndexAsync(CancellationToken cancellationToken) + { + var (total, ends) = await _catalog.GetPageEndsAsync(PageSize, cancellationToken); + + return new CatalogIndex + { + CommitTimestamp = total == 0 ? DateTimeOffset.UnixEpoch : Utc(ends[^1]), + Count = PageCount(total), + Items = Enumerable.Range(0, PageCount(total)) + .Select(page => new CatalogPageItem + { + CatalogPageUrl = _url.GetCatalogPageUrl(page), + CommitTimestamp = Utc(ends[page]), + Count = Math.Min(PageSize, total - page * PageSize), + }) + .ToList(), + }; + } + + /// + /// One page, or null if the page does not exist. + /// + public async Task GetPageOrNullAsync(int pageIndex, CancellationToken cancellationToken) + { + if (pageIndex < 0) return null; + + var entries = await _catalog.GetEntriesAsync(pageIndex * PageSize, PageSize, cancellationToken); + if (entries.Count == 0) return null; + + return new CatalogPage + { + CommitTimestamp = Utc(entries[^1].CommitTimestamp), + Count = entries.Count, + CatalogIndexUrl = _url.GetCatalogIndexUrl(), + Items = entries + .Select(e => new CatalogLeafItem + { + CatalogLeafUrl = _url.GetCatalogLeafUrl(e.CommitId), + Type = "nuget:" + e.Type, + CommitTimestamp = Utc(e.CommitTimestamp), + PackageId = e.PackageId, + PackageVersion = e.PackageVersion, + }) + .ToList(), + }; + } + + /// + /// One leaf document as JSON, or null if no such leaf exists. + /// + public async Task GetLeafOrNullAsync(string commitId, CancellationToken cancellationToken) + { + if (!Guid.TryParseExact(commitId, "D", out _)) return null; + + var entry = await _catalog.FindOrNullAsync(commitId, cancellationToken); + if (entry == null) return null; + + JsonNode? leaf; + using (var stream = await _storage.GetAsync(CatalogWriter.LeafPath(_repository?.Current ?? RepositoryInfo.Default, entry.CommitId), cancellationToken)) + { + leaf = await JsonNode.ParseAsync(stream, cancellationToken: cancellationToken); + } + + // The leaf's own URL is not stored, so it follows the host like every other URL. + leaf?["@id"] = _url.GetCatalogLeafUrl(entry.CommitId); + + return leaf?.ToJsonString(); + } + + internal static int PageCount(int entries) => (entries + PageSize - 1) / PageSize; + + private static DateTimeOffset Utc(DateTime value) => new(DateTime.SpecifyKind(value, DateTimeKind.Utc)); +} \ No newline at end of file diff --git a/src/BaGet.Catalog/Storage/CatalogWriter.cs b/src/BaGet.Catalog/Storage/CatalogWriter.cs new file mode 100644 index 000000000..df8e09b4d --- /dev/null +++ b/src/BaGet.Catalog/Storage/CatalogWriter.cs @@ -0,0 +1,279 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Protocol.Models; +using Microsoft.Extensions.Logging; +using NuGet.Versioning; +using BaGet.Catalog.Database; + +namespace BaGet.Catalog.Storage; + +/// +/// Appends a catalog entry for every package change. Each entry's leaf document is +/// written to storage first, so a leaf can always be served once its entry exists. +/// +public class CatalogWriter : IPackageChangeHandler +{ + internal static readonly JsonSerializerOptions LeafSerializerOptions = new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + // Commit timestamps must strictly increase, or a mirror reading the catalog + // "after" its cursor could miss an entry. Commits in this process are serialized. + // Instances of a cluster are ordered by the per-repository lease "catalog:{repository key}" (IJobLease; without + // a cluster it is in process and the lock above already serialises). + private static readonly SemaphoreSlim CommitLock = new(1, 1); + + private readonly ICatalogDatabase _catalog; + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _packageStorage; + private readonly IStorageService _storage; + private readonly SystemTime _time; + private readonly ILogger _logger; + private readonly MaintenanceGate? _gate; + private readonly IRepositoryContext? _repository; + private readonly IJobLease? _lease; + + /// How long a commit waits for another node's commit of the same repository before it gives up. + internal static TimeSpan LeaseWait { get; set; } = TimeSpan.FromSeconds(30); + + public CatalogWriter( + ICatalogDatabase catalog, + IPackageDatabase packages, + IPackageStorageService packageStorage, + IStorageService storage, + SystemTime time, + ILogger logger, + MaintenanceGate? gate = null, + IRepositoryContext? repository = null, + IJobLease? lease = null) + { + _lease = lease; + _gate = gate; + _repository = repository; + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _packageStorage = packageStorage ?? throw new ArgumentNullException(nameof(packageStorage)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// Where a leaf document is stored: catalog/{commit}.json for the default repository, + /// repos/{name}/catalog/{commit}.json for any other (see ). + /// + internal static string LeafPath(RepositoryInfo repository, string? commitId) + => RepositoryStorage.Scope(repository, $"catalog/{commitId}.json"); + + public async Task OnPackageChangedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_catalog.IsSupported) return; + + var package = await _packages.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); + if (package == null) + { + _logger.LogWarning( + "Package {PackageId} {PackageVersion} changed but no longer exists; no catalog entry written", + id, + version); + return; + } + + var (hash, size) = await HashPackageAsync(package, cancellationToken); + + await CommitAsync( + CatalogEntry.PackageDetailsType, + package.Id, + package.Version, + (commitId, timestamp) => BuildDetailsLeaf(package, hash, size, commitId, timestamp), + cancellationToken); + } + + public async Task OnPackageDeletedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_catalog.IsSupported) return; + + await CommitAsync( + CatalogEntry.PackageDeleteType, + id, + version, + (commitId, timestamp) => new PackageDeleteCatalogLeaf + { + Type = new[] { CatalogEntry.PackageDeleteType, "catalog:Permalink" }, + CommitId = commitId, + CommitTimestamp = timestamp, + PackageId = id, + PackageVersion = version.ToNormalizedString(), + Published = timestamp, + }, + cancellationToken); + } + + internal static PackageDetailsCatalogLeaf BuildDetailsLeaf( + Package package, + string hash, + long size, + string commitId, + DateTimeOffset timestamp) + { + var published = new DateTimeOffset(DateTime.SpecifyKind(package.Published, DateTimeKind.Utc)); + + return new PackageDetailsCatalogLeaf + { + Type = new[] { CatalogEntry.PackageDetailsType, "catalog:Permalink" }, + CommitId = commitId, + CommitTimestamp = timestamp, + PackageId = package.Id, + PackageVersion = package.NormalizedVersionString, + VerbatimVersion = package.OriginalVersionString ?? package.NormalizedVersionString, + Published = published, + Created = published, + LastEdited = timestamp, + Authors = string.Join(", ", package.Authors ?? Array.Empty()), + Description = package.Description, + DependencyGroups = RegistrationBuilder.ToDependencyGroups(package).ToList(), + IconUrl = NullIfEmpty(package.IconUrlString), + IsPrerelease = package.IsPrerelease, + Language = NullIfEmpty(package.Language), + LicenseUrl = NullIfEmpty(package.LicenseUrlString), + Listed = package.Listed, + MinClientVersion = NullIfEmpty(package.MinClientVersion), + PackageHash = hash, + PackageHashAlgorithm = "SHA512", + PackageSize = size, + ProjectUrl = NullIfEmpty(package.ProjectUrlString), + ReleaseNotes = NullIfEmpty(package.ReleaseNotes), + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + Summary = NullIfEmpty(package.Summary), + Tags = package.Tags?.ToList(), + Title = NullIfEmpty(package.Title), + }; + } + + /// + /// The next commit timestamp: now, truncated to milliseconds so that every database + /// provider stores it exactly, and always later than the previous commit. + /// + internal static DateTime NextTimestamp(DateTime now, DateTime? last) + { + now = now.ToUniversalTime(); + var truncated = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerMillisecond, DateTimeKind.Utc); + + if (last.HasValue && truncated <= last.Value) + { + return last.Value.AddMilliseconds(1); + } + + return truncated; + } + + private async Task CommitAsync( + string type, + string? id, + NuGetVersion version, + Func buildLeaf, + CancellationToken cancellationToken) + { + await CommitLock.WaitAsync(cancellationToken); + IAsyncDisposable? leaseHandle = null; + try + { + leaseHandle = await AcquireLeaseAsync(cancellationToken); + + // Before the leaf is written: a closed database would refuse the entry and leave the leaf orphaned. + _gate?.ThrowIfClosed(); + + var last = await _catalog.GetLastCommitTimestampAsync(cancellationToken); + var timestamp = NextTimestamp(_time.UtcNow, last); + var commitId = Guid.NewGuid().ToString("D"); + + var leaf = buildLeaf(commitId, new DateTimeOffset(timestamp)); + + using (var content = new MemoryStream()) + { + await JsonSerializer.SerializeAsync(content, leaf, leaf.GetType(), LeafSerializerOptions, cancellationToken); + content.Position = 0; + + var result = await _storage.PutAsync(LeafPath(_repository?.Current ?? RepositoryInfo.Default, commitId), content, "application/json", cancellationToken); + if (result == StoragePutResult.Conflict) + { + throw new InvalidOperationException($"Catalog leaf {commitId} already exists with different content"); + } + } + + await _catalog.AddAsync( + new CatalogEntry + { + CommitId = commitId, + CommitTimestamp = timestamp, + Type = type, + PackageId = id, + PackageVersion = version.ToNormalizedString(), + }, + cancellationToken); + + _logger.LogInformation( + "Committed catalog {Type} entry {CommitId} for {PackageId} {PackageVersion}", + type, + commitId, + id, + version); + } + finally + { + if (leaseHandle != null) await leaseHandle.DisposeAsync(); + CommitLock.Release(); + } + } + + // Waits for the repository's commit lease: a timestamp is "last entry + 1" and two nodes reading the same last + // entry would give the later key an equal or earlier timestamp, which a catalog consumer's cursor skips for good. + private async Task AcquireLeaseAsync(CancellationToken cancellationToken) + { + if (_lease == null) return null; + + var job = "catalog:" + (_repository?.Current ?? RepositoryInfo.Default).Key; + var deadline = DateTime.UtcNow + LeaseWait; + while (true) + { + var handle = await _lease.TryAcquireAsync(job, cancellationToken); + if (handle != null) return handle; + + // A store that cannot be reached is not another node holding the lease: waiting would block every commit + // (and, through the lock, every push) for the whole wait and then lose the entry. Commit under the local lock. + if (_lease is IJobLeaseAvailability availability && !await availability.IsAvailableAsync(cancellationToken)) + { + _logger.LogWarning("The lease store is unreachable; committing catalog entry for '{Job}' without the cross-node lease.", job); + return null; + } + + if (DateTime.UtcNow >= deadline) + { + throw new TimeoutException($"The catalog commit lease '{job}' stayed with another node for {LeaseWait.TotalSeconds:0} s."); + } + + await Task.Delay(TimeSpan.FromMilliseconds(25), cancellationToken); + } + } + + private async Task<(string Hash, long Size)> HashPackageAsync(Package package, CancellationToken cancellationToken) + { + using var stream = await _packageStorage.GetPackageStreamAsync(package.Id, package.Version, cancellationToken); + using var counting = new CountingStream(stream); + using var sha512 = SHA512.Create(); + + var hash = await sha512.ComputeHashAsync(counting, cancellationToken); + + return (Convert.ToBase64String(hash), counting.BytesRead); + } + + private static string? NullIfEmpty(string? value) => string.IsNullOrEmpty(value) ? null : value; +} diff --git a/src/BaGet.Catalog/Storage/CountingStream.cs b/src/BaGet.Catalog/Storage/CountingStream.cs new file mode 100644 index 000000000..f9a997b1a --- /dev/null +++ b/src/BaGet.Catalog/Storage/CountingStream.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Catalog.Storage; + +/// +/// Counts the bytes read through it, since a storage stream may not know its length. +/// +internal sealed class CountingStream : Stream +{ + private readonly Stream? _source; + + public CountingStream(Stream? source) => _source = source; + + public long BytesRead { get; private set; } + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override int Read(byte[] buffer, int offset, int count) + { + #pragma warning disable CS8602 + var read = _source.Read(buffer, offset, count); + #pragma warning restore CS8602 + BytesRead += read; + return read; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var read = await _source.ReadAsync(buffer, cancellationToken); + #pragma warning restore CS8602 + BytesRead += read; + return read; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/src/BaGet.Core/Access/AccessInspection.cs b/src/BaGet.Core/Access/AccessInspection.cs new file mode 100644 index 000000000..d87cbac96 --- /dev/null +++ b/src/BaGet.Core/Access/AccessInspection.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Core; + +/// +/// One grant or project role behind an access decision, for the admin pages that explain it. +/// +/// Where it comes from, such as Permission target 'Anyone reads every repository'. +/// What kind of principal holds it. +/// The principal's id (user id, group or organization key). +/// The principal in words (a user name, group Developers, organization Contoso). +/// What the grant or role carries. +/// What of it applies here: minus Read when the Everyone group's Read is +/// gated off by the repository's anonymous-read switch. +/// The package filter of the target, such as Contoso.* except Contoso.Internal.*; null for all. +/// Why differs from , if it does. +public sealed record AccessReason( + string Source, + PrincipalType PrincipalType, + string PrincipalId, + string Principal, + AccessAction Granted, + AccessAction Effective, + string? Packages, + string? Note); + +/// What a caller may do in a repository, and why (). +/// Every action the caller holds. +/// A rule that grants everything or bypasses the model (administrator, global API key, no +/// access model), instead of ; null when the grants decide. +/// The grants and project roles that apply to the caller. +public sealed record AccessExplanation(AccessAction Actions, string? Override, IReadOnlyList Reasons) +{ + /// Whether the caller holds . + public bool Has(AccessAction action) => (Actions & action) == action; +} + +/// Who holds what in one repository (). +/// The repository. +/// The repository's anonymous-read switch. +/// The name of the project the repository belongs to, if any. +/// False where there is no access model (Azure Table): everyone reads, any authenticated +/// caller writes, subject to ownership. +/// Every grant and project role that applies to the repository. +public sealed record RepositoryAccessSummary( + RepositoryInfo Repository, + bool AnonymousRead, + string? Project, + bool ModelAvailable, + IReadOnlyList Holders) +{ + /// The principals that effectively hold , without repeats. + public IReadOnlyList Who(AccessAction action) + => Holders.Where(h => (h.Effective & action) == action).Select(h => h.Principal).Distinct(StringComparer.Ordinal).ToList(); +} + +/// +/// The same case-insensitive * globs the evaluator uses for repository names and package IDs, for the admin +/// pages' previews and test box: what they show is what the evaluator decides. +/// +public static class AccessPatterns +{ + /// Whether any of matches . + /// The globs; blank entries are ignored. + /// A repository name or package ID. + /// Whether no pattern at all matches everything (include lists) or nothing. + public static bool IsMatch(IEnumerable? patterns, string? value, bool emptyMeansAll = false) + => GlobSet.Parse(patterns, emptyMeansAll).IsMatch(value); + + /// + /// Splits what an administrator typed (one pattern per line, or separated by commas or semicolons) into patterns. + /// + public static string[] Split(string? text) + => (text ?? string.Empty) + .Split(new[] { '\r', '\n', ',', ';' }, StringSplitOptions.RemoveEmptyEntries) + .Select(p => p.Trim()) + .Where(p => p.Length > 0) + .ToArray(); + + /// + /// Whether a target with these patterns applies to , and which pattern decided: the + /// evaluator's rule (an include pattern matches, or there is none, and no exclude pattern matches). + /// + public static PatternTest Test(IEnumerable? include, IEnumerable? exclude, string packageId) + { + var inc = (include ?? Array.Empty()).Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p.Trim()).ToList(); + var exc = (exclude ?? Array.Empty()).Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p.Trim()).ToList(); + + var excluded = exc.FirstOrDefault(p => IsMatch(new[] { p }, packageId)); + if (excluded != null) return new PatternTest(false, $"excluded by '{excluded}'"); + + if (inc.Count == 0) return new PatternTest(true, "no include pattern, so every package is included"); + + var included = inc.FirstOrDefault(p => IsMatch(new[] { p }, packageId)); + return included != null + ? new PatternTest(true, $"included by '{included}'") + : new PatternTest(false, "matches no include pattern"); + } + + /// The package filter in words, or null when the target applies to every package. + public static string? DescribeScope(IEnumerable? include, IEnumerable? exclude) + { + var inc = (include ?? Array.Empty()).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray(); + var exc = (exclude ?? Array.Empty()).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray(); + if ((inc.Length == 0 || inc.Contains("*")) && exc.Length == 0) return null; + + var text = inc.Length == 0 ? "*" : string.Join(", ", inc); + return exc.Length == 0 ? text : text + " except " + string.Join(", ", exc); + } +} + +/// The outcome of . +/// Whether the target applies to the package. +/// Which pattern decided, in words. +public sealed record PatternTest(bool Matches, string Explanation); + +/// A group as the admin pages list it. +public sealed record GroupSummary(int Key, string Name, string? Description, bool IsBuiltIn, int MemberCount); + +/// A member of a group. +public sealed record GroupMemberInfo(string UserId, string UserName); + +/// A grant, with the target and principal in words. +public sealed record GrantInfo(string Target, PrincipalType PrincipalType, string PrincipalId, string Principal, AccessAction Actions); + +/// A group with its members and the grants naming it. +public sealed record GroupDetails(GroupSummary Group, IReadOnlyList Members, IReadOnlyList Grants); + +/// A permission target as the admin pages list it. +public sealed record TargetSummary( + int Key, + string Name, + IReadOnlyList RepositoryPatterns, + IReadOnlyList IncludePatterns, + IReadOnlyList ExcludePatterns, + int? ProjectKey, + string? ProjectName, + bool IsBuiltIn, + int GrantCount); + +/// A permission target with its grants. +public sealed record TargetDetails(TargetSummary Target, IReadOnlyList Grants); + +/// A project as the admin pages list it. +public sealed record ProjectSummary(int Key, string Name, string? DisplayName, int RepositoryCount, int MemberCount); + +/// A member of a project. +public sealed record ProjectMemberInfo(PrincipalType PrincipalType, string PrincipalId, string Principal, ProjectRole Role); + +/// A project with its repositories, members and targets. +public sealed record ProjectDetails( + ProjectSummary Project, + IReadOnlyList Repositories, + IReadOnlyList Members, + IReadOnlyList Targets); + +/// A role a user holds in a project, directly or through a group. +public sealed record UserProjectRole(string Project, ProjectRole Role, string Via); + +/// Which audit entries to list; every filter is optional. +/// The user name that made the change (exact, case-insensitive). +/// What it happened to (contains, case-insensitive). +/// Earliest time (UTC, inclusive). +/// Latest time (UTC, exclusive). +public sealed record AuditFilter(string? Actor = null, string? Subject = null, DateTime? From = null, DateTime? To = null); diff --git a/src/BaGet.Core/Access/AccessModel.cs b/src/BaGet.Core/Access/AccessModel.cs new file mode 100644 index 000000000..efac7cc07 --- /dev/null +++ b/src/BaGet.Core/Access/AccessModel.cs @@ -0,0 +1,239 @@ +using System; + +namespace BaGet.Core; + +/// +/// What a permission grants. Independent flags: does not imply , as in +/// Artifactory. Package ownership () is a second, separate requirement +/// for the actions that change an existing package ID. +/// +[Flags] +public enum AccessAction +{ + None = 0, + + /// Use the repository's feed, symbols and pages. + Read = 1, + + /// Edit a version's deprecation and vulnerabilities. + Annotate = 2, + + /// Push new packages and new versions. + Deploy = 4, + + /// Unlist, relist and delete versions. + Delete = 8, + + /// Administer the owners of a package ID and the repository's targets. + Manage = 16, + + /// Every action. + All = Read | Annotate | Deploy | Delete | Manage, +} + +/// Who a or names. +public enum PrincipalType +{ + /// A user; the principal id is BaGetUser.Id. + User, + + /// A ; the principal id is its . + Group, + + /// An (its members); the principal id is its . + Organization, +} + +/// A member's role in a , applying to the project's repositories. +public enum ProjectRole +{ + /// . + Viewer, + + /// Read, Annotate and Deploy. + Developer, + + /// Every action. + Admin, +} + +/// What each grants. +public static class ProjectRoles +{ + public static AccessAction ActionsOf(ProjectRole role) => role switch + { + ProjectRole.Admin => AccessAction.All, + ProjectRole.Developer => AccessAction.Read | AccessAction.Annotate | AccessAction.Deploy, + _ => AccessAction.Read, + }; +} + +/// +/// A named set of users. The two built-in groups are implicit and have no member rows: +/// is every caller, anonymous ones included, and +/// is every caller that presented valid credentials. +/// +public class Group +{ + public int Key { get; set; } + + /// Unique (case-insensitive); see . + public string? Name { get; set; } + + public string? Description { get; set; } + + public DateTime Created { get; set; } + + /// Everyone and Authenticated: not deletable, membership implicit. + public bool IsBuiltIn { get; set; } +} + +/// The built-in groups and permission targets the upgrade migration seeds (and the admin pages can restore). +public static class BuiltInNames +{ + public const string Everyone = "Everyone"; + public const string Authenticated = "Authenticated"; + + /// Target: every caller reads every repository (what the server did before the access model). + public const string AnyoneReads = "Anyone reads every repository"; + + /// Target: authenticated callers deploy, annotate, delete and manage every repository, with package + /// ownership still applied inside (what the server did before the access model). + public const string AuthenticatedDeploy = "Authenticated users deploy"; +} + +public class GroupMember +{ + public int Key { get; set; } + + public int GroupKey { get; set; } + + public Group? Group { get; set; } + + /// The member's BaGetUser.Id. + public string? UserId { get; set; } +} + +/// +/// A rule saying which repositories and package IDs its s apply to. +/// +public class PermissionTarget +{ + public int Key { get; set; } + + /// Unique (case-insensitive); see . + public string? Name { get; set; } + + /// Repository names or * globs; the target applies to a repository matching any. Empty matches none. + public string[]? RepositoryPatterns { get; set; } + + /// Package ID globs the target applies to; empty means *. + public string[]? IncludePatterns { get; set; } + + /// Package ID globs the target does not apply to, whatever say. + public string[]? ExcludePatterns { get; set; } + + /// + /// The that administers the target. When set, the target applies only to repositories of + /// that project. A Restrict foreign key to (nullable); deleting the project deletes its targets first. + /// + public int? ProjectKey { get; set; } + + /// Seeded by the upgrade migration; restorable, but nothing is special about it once edited. + public bool IsBuiltIn { get; set; } + + public DateTime Created { get; set; } +} + +public class PermissionGrant +{ + public int Key { get; set; } + + public int TargetKey { get; set; } + + public PermissionTarget? Target { get; set; } + + public PrincipalType PrincipalType { get; set; } + + /// See . + public string? PrincipalId { get; set; } + + public AccessAction Actions { get; set; } +} + +/// A user or group with a role in a project. +public class ProjectMember +{ + public int Key { get; set; } + + public int ProjectKey { get; set; } + + public Project? Project { get; set; } + + /// or . + public PrincipalType PrincipalType { get; set; } + + public string? PrincipalId { get; set; } + + public ProjectRole Role { get; set; } +} + +/// One change to the access model. +public class AccessAuditEntry +{ + public int Key { get; set; } + + public DateTime Created { get; set; } + + /// The user name that made the change; null for the server itself. + public string? Actor { get; set; } + + /// What happened, such as group.create or grant.set. + public string? Action { get; set; } + + /// What it happened to (a group, target or repository name). + public string? Subject { get; set; } + + /// JSON with the details (never credentials). + public string? Details { get; set; } +} + +/// The one rule for the names of groups, permission targets and projects. +public static class AccessNames +{ + public const int MaxLength = 128; + + /// Letters, digits, -, ., _ and spaces inside, 1 to 128 characters, starting with a letter or digit. + public static bool IsValid(string? name, out string? error) + { + if (string.IsNullOrWhiteSpace(name)) + { + error = "A name is required."; + return false; + } + + if (name.Length > MaxLength) + { + error = $"A name is at most {MaxLength} characters."; + return false; + } + + if (!char.IsLetterOrDigit(name[0]) || name != name.Trim()) + { + error = "A name starts with a letter or digit and has no surrounding spaces."; + return false; + } + + foreach (var c in name) + { + if (!char.IsLetterOrDigit(c) && c != '-' && c != '.' && c != '_' && c != ' ') + { + error = "A name uses only letters, digits, spaces, '-', '.' and '_'."; + return false; + } + } + + error = null; + return true; + } +} diff --git a/src/BaGet.Core/Access/AccessModelSaveChangesInterceptor.cs b/src/BaGet.Core/Access/AccessModelSaveChangesInterceptor.cs new file mode 100644 index 000000000..a1dbc172d --- /dev/null +++ b/src/BaGet.Core/Access/AccessModelSaveChangesInterceptor.cs @@ -0,0 +1,90 @@ +using System; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace BaGet.Core; + +/// +/// Bumps after any committed change to what access decisions read: the access model's +/// own tables, repositories (the anonymous-read flag, the project), projects and organization membership. Doing it +/// here, once, means no code path that edits those rows can forget to invalidate the evaluator's cache. +/// +public sealed class AccessModelSaveChangesInterceptor : SaveChangesInterceptor +{ + private static readonly Type[] Relevant = + { + typeof(Group), typeof(GroupMember), typeof(PermissionTarget), typeof(PermissionGrant), typeof(ProjectMember), + typeof(Project), typeof(Repository), typeof(Organization), typeof(OrganizationMember), + }; + + private readonly AccessModelVersion _version; + private readonly ConditionalWeakTable _pending = new(); + + public AccessModelSaveChangesInterceptor(AccessModelVersion version) + { + _version = version ?? throw new ArgumentNullException(nameof(version)); + } + + public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + { + Mark(eventData.Context); + return result; + } + + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, + InterceptionResult result, + CancellationToken cancellationToken = default) + { + Mark(eventData.Context); + return new ValueTask>(result); + } + + public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) + { + Commit(eventData.Context); + return result; + } + + public override ValueTask SavedChangesAsync( + SaveChangesCompletedEventData eventData, + int result, + CancellationToken cancellationToken = default) + { + Commit(eventData.Context); + return new ValueTask(result); + } + + public override void SaveChangesFailed(DbContextErrorEventData eventData) => Forget(eventData.Context); + + public override Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = default) + { + Forget(eventData.Context); + return Task.CompletedTask; + } + + private void Mark(DbContext? context) + { + if (context == null) return; + + var changed = context.ChangeTracker.Entries().Any(e => + e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted + && Relevant.Contains(e.Entity.GetType())); + + if (changed) _pending.AddOrUpdate(context, this); + } + + private void Commit(DbContext? context) + { + if (context != null && _pending.Remove(context)) _version.Bump(); + } + + private void Forget(DbContext? context) + { + if (context != null) _pending.Remove(context); + } +} diff --git a/src/BaGet.Core/Access/AccessRepositoryAccess.cs b/src/BaGet.Core/Access/AccessRepositoryAccess.cs new file mode 100644 index 000000000..32784100c --- /dev/null +++ b/src/BaGet.Core/Access/AccessRepositoryAccess.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Turns a signed-in browser session into a . Implemented by the accounts feature; a host +/// without accounts has none, and every browser caller is anonymous. +/// +public interface ISessionPrincipalFactory +{ + /// Null when nobody is signed in or the account no longer exists. + Task CreateAsync(ClaimsPrincipal? user); +} + +/// +/// over the access model: the web UI offers, and opens, the repositories the +/// signed-in user (or an anonymous visitor) may read through . Replaces +/// . +/// +public sealed class AccessRepositoryAccess : IRepositoryAccess +{ + private readonly IAccessEvaluator _evaluator; + private readonly IRepositoryService _repositories; + private readonly ISessionPrincipalFactory? _sessions; + private readonly IVirtualRepositories? _virtuals; + + public AccessRepositoryAccess( + IAccessEvaluator evaluator, + IRepositoryService repositories, + ISessionPrincipalFactory? sessions = null, + IVirtualRepositories? virtuals = null) + { + _virtuals = virtuals; + _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _sessions = sessions; + } + + /// + public bool SupportsMultipleRepositories => _repositories.SupportsMultipleRepositories; + + private async Task PrincipalAsync(ClaimsPrincipal? user) + => _sessions == null ? null : await _sessions.CreateAsync(user).ConfigureAwait(false); + + /// + public async Task> ReadableAsync(ClaimsPrincipal? user, CancellationToken cancellationToken) + => await _evaluator.ReadableRepositoriesAsync(await PrincipalAsync(user).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); + + /// + /// The repositories the signed-in user holds Deploy in. A visitor who is not signed in may still push with an + /// API key typed into the upload page, which is authorized per package when submitted, so for them every + /// readable repository is offered. + /// + public async Task> WritableAsync(ClaimsPrincipal? user, CancellationToken cancellationToken) + { + var principal = await PrincipalAsync(user).ConfigureAwait(false); + + // A remote repository takes no uploads, whatever the caller holds. + var writable = principal == null + ? (await _evaluator.ReadableRepositoriesAsync(null, cancellationToken).ConfigureAwait(false)) + .Where(r => r.Kind == RepositoryKind.Local).ToList() + : (await _evaluator.RepositoriesWithAsync(principal, AccessAction.Deploy, cancellationToken).ConfigureAwait(false)).ToList(); + + // A virtual repository takes uploads when the caller can read it and write to the repository it deploys to. + if (_virtuals != null) + { + var targets = writable.Select(r => r.Key).ToHashSet(); + foreach (var candidate in await _evaluator.ReadableRepositoriesAsync(principal, cancellationToken).ConfigureAwait(false)) + { + if (candidate.Kind != RepositoryKind.Virtual) continue; + + var target = await _virtuals.DeployTargetAsync(candidate, cancellationToken).ConfigureAwait(false); + if (target != null && targets.Contains(target.Key)) writable.Add(candidate); + } + } + + return writable + .OrderBy(r => r.IsDefault ? 0 : 1) + .ThenBy(r => r.Name, StringComparer.Ordinal) + .ToList(); + } + + /// + /// A signed-in user needs Deploy on the repository (Read is not required: a drop box can be pushed to); a visitor + /// who is not signed in needs Read, as lists. + /// + public async Task CanWriteAsync(ClaimsPrincipal? user, RepositoryInfo repository, CancellationToken cancellationToken) + { + if (repository.Kind == RepositoryKind.Remote) return false; + + // A virtual repository's uploads go to its deploy repository: the caller needs to read the virtual one and to + // write to that. + if (repository.Kind == RepositoryKind.Virtual) + { + var target = _virtuals == null ? null : await _virtuals.DeployTargetAsync(repository, cancellationToken).ConfigureAwait(false); + + return target != null + && await CanReadAsync(user, repository, cancellationToken).ConfigureAwait(false) + && await CanWriteAsync(user, target, cancellationToken).ConfigureAwait(false); + } + + var principal = await PrincipalAsync(user).ConfigureAwait(false); + + return principal == null + ? await CanReadAsync(user, repository, cancellationToken).ConfigureAwait(false) + : await _evaluator.IsAllowedAsync(principal, repository, packageId: null, AccessAction.Deploy, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task CanReadAsync(ClaimsPrincipal? user, RepositoryInfo repository, CancellationToken cancellationToken) + => await _evaluator.IsAllowedAsync( + await PrincipalAsync(user).ConfigureAwait(false), repository, packageId: null, AccessAction.Read, cancellationToken).ConfigureAwait(false); + + /// + public async Task CanReadPackageAsync(ClaimsPrincipal? user, RepositoryInfo repository, string packageId, CancellationToken cancellationToken) + { + var principal = await PrincipalAsync(user).ConfigureAwait(false); + + return await _evaluator.IsAllowedAsync(principal, repository, packageId: null, AccessAction.Read, cancellationToken).ConfigureAwait(false) + && await _evaluator.IsAllowedAsync(principal, repository, packageId, AccessAction.Read, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Core/Access/AccessSnapshot.cs b/src/BaGet.Core/Access/AccessSnapshot.cs new file mode 100644 index 000000000..ea93ec974 --- /dev/null +++ b/src/BaGet.Core/Access/AccessSnapshot.cs @@ -0,0 +1,425 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Case-insensitive glob patterns in which * stands for any run of characters (package IDs and repository +/// names are case-insensitive). Compiled once into the , so a check allocates nothing. +/// +internal sealed class GlobSet +{ + private readonly string[] _patterns; + private readonly bool _all; + + private GlobSet(string[] patterns) + { + _patterns = patterns; + _all = patterns.Any(p => p == "*"); + } + + /// The globs; blank entries are ignored. + /// Whether no pattern at all matches everything (include lists) or nothing. + public static GlobSet Parse(IEnumerable? patterns, bool emptyMeansAll) + { + var list = (patterns ?? Array.Empty()).Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p.Trim()).ToArray(); + return list.Length == 0 && emptyMeansAll ? new GlobSet(new[] { "*" }) : new GlobSet(list); + } + + public bool IsMatch(string? value) + { + if (value == null) return false; + if (_all) return true; + + foreach (var pattern in _patterns) + { + if (Match(pattern, value)) return true; + } + + return false; + } + + // The classic iterative wildcard match: remember the last '*' and retry from there on a mismatch. + internal static bool Match(string pattern, string text) + { + int p = 0, t = 0, star = -1, mark = 0; + while (t < text.Length) + { + if (p < pattern.Length && pattern[p] == '*') + { + star = p++; + mark = t; + } + else if (p < pattern.Length && char.ToUpperInvariant(pattern[p]) == char.ToUpperInvariant(text[t])) + { + p++; + t++; + } + else if (star >= 0) + { + p = star + 1; + t = ++mark; + } + else + { + return false; + } + } + + while (p < pattern.Length && pattern[p] == '*') p++; + return p == pattern.Length; + } +} + +/// The groups and organizations one user belongs to, besides the implicit built-in groups. +internal sealed record Membership(HashSet GroupKeys, HashSet OrganizationKeys) +{ + public static readonly Membership None = new(new HashSet(), new HashSet()); +} + +internal sealed record RepositoryRow(int Key, string Name, bool AnonymousRead, int? ProjectKey); + +internal sealed record GrantRow(PrincipalType PrincipalType, string PrincipalId, AccessAction Actions); + +internal sealed record TargetRow(int Key, string Name, string? Scope, GlobSet Repositories, GlobSet Include, GlobSet Exclude, int? ProjectKey, GrantRow[] Grants); + +internal sealed record ProjectMemberRow(PrincipalType PrincipalType, string PrincipalId, ProjectRole Role); + +/// +/// The whole access model, read from the database once and kept in memory until the model changes +/// () or passes. Small by design: a few +/// hundred targets at most. What a user belongs to is loaded on first use and kept with the snapshot. +/// +internal sealed class AccessSnapshot +{ + private readonly ConcurrentDictionary _memberships = new(StringComparer.Ordinal); + + public AccessSnapshot( + long version, + DateTime loaded, + IReadOnlyDictionary repositories, + int? everyoneKey, + int? authenticatedKey, + IReadOnlyList targets, + IReadOnlyDictionary projectMembers, + IReadOnlyDictionary groupNames, + IReadOnlyDictionary organizationNames, + IReadOnlyDictionary projectNames) + { + Version = version; + Loaded = loaded; + Repositories = repositories; + EveryoneKey = everyoneKey; + AuthenticatedKey = authenticatedKey; + Targets = targets; + ProjectMembers = projectMembers; + GroupNames = groupNames; + OrganizationNames = organizationNames; + ProjectNames = projectNames; + } + + public IReadOnlyDictionary GroupNames { get; } + + public IReadOnlyDictionary OrganizationNames { get; } + + public IReadOnlyDictionary ProjectNames { get; } + + public long Version { get; } + + public DateTime Loaded { get; } + + public IReadOnlyDictionary Repositories { get; } + + public int? EveryoneKey { get; } + + public int? AuthenticatedKey { get; } + + public IReadOnlyList Targets { get; } + + public IReadOnlyDictionary ProjectMembers { get; } + + public async Task MembershipAsync(IContext context, string userId, CancellationToken cancellationToken) + { + if (_memberships.TryGetValue(userId, out var cached)) return cached; + + var groups = await context.GroupMembers!.AsNoTracking() + .Where(m => m.UserId == userId) + .Select(m => m.GroupKey) + .ToListAsync(cancellationToken).ConfigureAwait(false); + var organizations = await context.OrganizationMembers!.AsNoTracking() + .Where(m => m.UserId == userId && m.OrganizationKey != null) + .Select(m => m.OrganizationKey!.Value) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + var membership = new Membership(groups.ToHashSet(), organizations.ToHashSet()); + _memberships[userId] = membership; + return membership; + } + + /// + /// The actions holds on , and on + /// when given. Targets with a package filter apply to a repository-level question (null ID) whatever the filter says, + /// since some package in the repository may match. + /// + /// Who asks; null is anonymous. + /// The caller's groups and organizations. + /// The repository. + /// The package ID, or null for the repository as a whole. + /// When given, receives one entry per grant or project role that applies: the explanation. + public AccessAction Granted( + BaGetPrincipal? principal, + Membership membership, + RepositoryInfo repository, + string? packageId, + List? reasons = null) + { + Repositories.TryGetValue(repository.Key, out var row); + var anonymousRead = row?.AnonymousRead ?? true; + var projectKey = row?.ProjectKey; + var userId = principal?.UserId; + + var granted = AccessAction.None; + + foreach (var target in Targets) + { + if (!target.Repositories.IsMatch(repository.Name)) continue; + if (target.ProjectKey != null && target.ProjectKey != projectKey) continue; + if (packageId != null && (!target.Include.IsMatch(packageId) || target.Exclude.IsMatch(packageId))) continue; + + foreach (var grant in target.Grants) + { + if (!Applies(grant.PrincipalType, grant.PrincipalId, principal, userId, membership, out var viaEveryone)) continue; + + // Anonymous read is a property of the repository: while it is off, the Everyone group's Read does + // not apply there (a user with a Read grant of their own still reads). + var actions = viaEveryone && !anonymousRead ? grant.Actions & ~AccessAction.Read : grant.Actions; + granted |= actions; + reasons?.Add(Reason(target, grant, actions, viaEveryone && !anonymousRead, principal)); + } + } + + if (projectKey != null && ProjectMembers.TryGetValue(projectKey.Value, out var members)) + { + foreach (var member in members) + { + if (Applies(member.PrincipalType, member.PrincipalId, principal, userId, membership, out var viaEveryone)) + { + // Same rule as for a permission target: while anonymous read is off, Everyone's Read does not apply, + // whether it comes from a grant or from a project role. + var blocked = viaEveryone && !anonymousRead; + var actions = ProjectRoles.ActionsOf(member.Role); + if (blocked) actions &= ~AccessAction.Read; + granted |= actions; + reasons?.Add(ProjectReason(projectKey.Value, member, actions, blocked, principal)); + } + } + } + + return granted; + } + + /// + /// Every grant and project role that applies to whoever holds it. Target package + /// filters are reported in , not applied. + /// + public IReadOnlyList Holders(RepositoryInfo repository) + { + Repositories.TryGetValue(repository.Key, out var row); + var anonymousRead = row?.AnonymousRead ?? true; + var projectKey = row?.ProjectKey; + var result = new List(); + + foreach (var target in Targets) + { + if (!target.Repositories.IsMatch(repository.Name)) continue; + if (target.ProjectKey != null && target.ProjectKey != projectKey) continue; + + foreach (var grant in target.Grants) + { + var viaEveryone = grant.PrincipalType == PrincipalType.Group + && int.TryParse(grant.PrincipalId, out var group) && group == EveryoneKey; + var blocked = viaEveryone && !anonymousRead; + result.Add(Reason(target, grant, blocked ? grant.Actions & ~AccessAction.Read : grant.Actions, blocked, principal: null)); + } + } + + if (projectKey != null && ProjectMembers.TryGetValue(projectKey.Value, out var members)) + { + foreach (var member in members) + { + var blocked = member.PrincipalType == PrincipalType.Group + && int.TryParse(member.PrincipalId, out var group) && group == EveryoneKey && !anonymousRead; + var actions = ProjectRoles.ActionsOf(member.Role); + result.Add(ProjectReason(projectKey.Value, member, blocked ? actions & ~AccessAction.Read : actions, blocked, principal: null)); + } + } + + return result; + } + + private AccessReason Reason(TargetRow target, GrantRow grant, AccessAction effective, bool anonymousReadOff, BaGetPrincipal? principal) + => new( + $"Permission target '{target.Name}'", + grant.PrincipalType, + grant.PrincipalId, + PrincipalText(grant.PrincipalType, grant.PrincipalId, principal), + grant.Actions, + effective, + target.Scope, + anonymousReadOff ? "Anonymous read is off for this repository, so Everyone's Read does not apply." : null); + + private AccessReason ProjectReason(int projectKey, ProjectMemberRow member, AccessAction effective, bool anonymousReadOff, BaGetPrincipal? principal) + { + var actions = ProjectRoles.ActionsOf(member.Role); + var project = ProjectNames.TryGetValue(projectKey, out var name) ? name : projectKey.ToString(); + + return new AccessReason( + $"Project '{project}', role {member.Role}", + member.PrincipalType, + member.PrincipalId, + PrincipalText(member.PrincipalType, member.PrincipalId, principal), + actions, + effective, + Packages: null, + Note: anonymousReadOff ? "Anonymous read is off for this repository, so Everyone's Read does not apply." : null); + } + + private string PrincipalText(PrincipalType type, string id, BaGetPrincipal? principal) + { + var parsed = int.TryParse(id, out var key); + + return type switch + { + PrincipalType.User => "user " + (principal?.UserId == id ? (principal.UserName ?? id) : id), + PrincipalType.Group => "group " + (parsed && GroupNames.TryGetValue(key, out var group) ? group : id), + _ => "organization " + (parsed && OrganizationNames.TryGetValue(key, out var organization) ? organization : id), + }; + } + + private bool Applies( + PrincipalType type, + string id, + BaGetPrincipal? principal, + string? userId, + Membership membership, + out bool viaEveryone) + { + viaEveryone = false; + switch (type) + { + case PrincipalType.User: + return userId != null && string.Equals(id, userId, StringComparison.Ordinal); + + case PrincipalType.Organization: + return int.TryParse(id, out var organization) && membership.OrganizationKeys.Contains(organization); + + case PrincipalType.Group: + if (!int.TryParse(id, out var group)) return false; + if (group == EveryoneKey) + { + viaEveryone = true; + return true; + } + + if (group == AuthenticatedKey) return principal != null; + return membership.GroupKeys.Contains(group); + + default: + return false; + } + } +} + +/// +/// A counter bumped after every committed change to the access model (see ): +/// a snapshot older than the counter is reloaded. Per process; other instances catch up within +/// . +/// +public sealed class AccessModelVersion +{ + private long _current; + + public long Current => Interlocked.Read(ref _current); + + /// Called after so a cluster can tell the other nodes (they reload their snapshot). + internal Action? Publisher { get; set; } + + public void Bump() + { + Interlocked.Increment(ref _current); + Publisher?.Invoke(); + } + + /// A change another node made: reload here, without telling the cluster again. + internal void BumpFromCluster() => Interlocked.Increment(ref _current); +} + +/// The singleton that owns the current . +public sealed class AccessModelCache +{ + /// + /// How long a snapshot is trusted without a version bump, which bounds how stale another instance of the server + /// can leave this one. + /// + public static readonly TimeSpan TimeToLive = TimeSpan.FromSeconds(30); + + private readonly AccessModelVersion _version; + private volatile AccessSnapshot? _snapshot; + + public AccessModelCache(AccessModelVersion version) + { + _version = version ?? throw new ArgumentNullException(nameof(version)); + } + + internal async Task GetAsync(IContext context, CancellationToken cancellationToken) + { + var current = _snapshot; + var now = DateTime.UtcNow; + if (current != null && current.Version == _version.Current && now - current.Loaded < TimeToLive) return current; + + // Read the version first: a change committed while loading bumps it, and the snapshot is then already stale. + var version = _version.Current; + + var repositories = (await context.Repositories!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false)) + .ToDictionary(r => r.Key, r => new RepositoryRow(r.Key, r.Name ?? string.Empty, r.AnonymousRead, r.ProjectKey)); + + var groups = await context.Groups!.AsNoTracking().Where(g => g.IsBuiltIn).ToListAsync(cancellationToken).ConfigureAwait(false); + var everyone = groups.FirstOrDefault(g => g.Name == BuiltInNames.Everyone)?.Key; + var authenticated = groups.FirstOrDefault(g => g.Name == BuiltInNames.Authenticated)?.Key; + + var targets = await context.PermissionTargets!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + var grants = (await context.PermissionGrants!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false)) + .GroupBy(g => g.TargetKey) + .ToDictionary(g => g.Key, g => g.Select(x => new GrantRow(x.PrincipalType, x.PrincipalId ?? string.Empty, x.Actions)).ToArray()); + + var rows = targets.Select(t => new TargetRow( + t.Key, + t.Name ?? string.Empty, + AccessPatterns.DescribeScope(t.IncludePatterns, t.ExcludePatterns), + GlobSet.Parse(t.RepositoryPatterns, emptyMeansAll: false), + GlobSet.Parse(t.IncludePatterns, emptyMeansAll: true), + GlobSet.Parse(t.ExcludePatterns, emptyMeansAll: false), + t.ProjectKey, + grants.TryGetValue(t.Key, out var g) ? g : Array.Empty())).ToList(); + + var members = (await context.ProjectMembers!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false)) + .GroupBy(m => m.ProjectKey) + .ToDictionary(g => g.Key, g => g.Select(m => new ProjectMemberRow(m.PrincipalType, m.PrincipalId ?? string.Empty, m.Role)).ToArray()); + + var groupNames = (await context.Groups!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false)) + .ToDictionary(g => g.Key, g => g.Name ?? string.Empty); + var organizationNames = (await context.Organizations!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false)) + .ToDictionary(o => o.Key, o => o.Name ?? string.Empty); + var projectNames = (await context.Projects!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false)) + .ToDictionary(p => p.Key, p => p.Name ?? string.Empty); + + var loaded = new AccessSnapshot(version, now, repositories, everyone, authenticated, rows, members, groupNames, organizationNames, projectNames); + _snapshot = loaded; + return loaded; + } +} diff --git a/src/BaGet.Core/Access/AccessUpgradeCheck.cs b/src/BaGet.Core/Access/AccessUpgradeCheck.cs new file mode 100644 index 000000000..c13504d4b --- /dev/null +++ b/src/BaGet.Core/Access/AccessUpgradeCheck.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// Upgrade aid for the access model. Before it existed could be saved as false +/// and did nothing; now it makes the repository private. The saved setting is kept (the admin chose it), but a +/// repository that is private and has no Read grant for anyone besides administrators is reported at every startup, so +/// the change is visible. The warning stops once the switch is on or a Read grant exists. +/// +public static class AccessUpgradeCheck +{ + /// + /// The non-default repositories with AnonymousRead off in which no grant or project role gives anyone + /// Read (administrators and the global API key always can, and are not counted). + /// + public static async Task> FindPrivateWithoutReadersAsync( + IRepositoryService repositories, + IAccessEvaluator evaluator, + CancellationToken cancellationToken) + { + if (!repositories.SupportsMultipleRepositories) return Array.Empty(); + + var result = new List(); + foreach (var repository in await repositories.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (repository.IsDefault) continue; + + var summary = await evaluator.DescribeAsync(repository, cancellationToken).ConfigureAwait(false); + if (summary.ModelAvailable && !summary.AnonymousRead && !summary.Holders.Any(h => (h.Effective & AccessAction.Read) != 0)) + { + result.Add(repository.Name); + } + } + + return result; + } + + /// Logs one Warning naming those repositories; never throws (a startup check must not stop the host). + public static async Task WarnAsync( + IRepositoryService repositories, + IAccessEvaluator evaluator, + ILogger logger, + CancellationToken cancellationToken) + { + try + { + var names = await FindPrivateWithoutReadersAsync(repositories, evaluator, cancellationToken).ConfigureAwait(false); + if (names.Count > 0) + { + logger.LogWarning( + "Repositories {Repositories} have anonymous read off and no Read grant for anyone but administrators, so only administrators can read them. " + + "Before access control that switch did nothing. Switch anonymous read on, or grant Read, at /admin/repositories", + string.Join(", ", names)); + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception e) + { + logger.LogDebug(e, "The access upgrade check failed"); + } + } +} diff --git a/src/BaGet.Core/Access/IAccessAdministration.cs b/src/BaGet.Core/Access/IAccessAdministration.cs new file mode 100644 index 000000000..1291746c9 --- /dev/null +++ b/src/BaGet.Core/Access/IAccessAdministration.cs @@ -0,0 +1,910 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// A change to the access model that cannot be made, with a message fit for an administrator. +public class AccessModelException : Exception +{ + public AccessModelException(string message) : base(message) { } +} + +/// +/// Edits the access model: groups and their members, permission targets and grants, project members. Every change is +/// written to in the same save, and goes through the database context, so it is refused +/// while the is closed and invalidates the evaluator's cache +/// (). What the admin pages use. +/// +public interface IAccessAdministration +{ + /// Creates a group. + /// The name is invalid or taken. + Task CreateGroupAsync(string name, string? description, string? actor, CancellationToken cancellationToken); + + /// Deletes a group, its members and every grant naming it. + /// Unknown group, or a built-in one. + Task DeleteGroupAsync(string name, string? actor, CancellationToken cancellationToken); + + /// Adds a user to a group (idempotent). + /// Unknown group, or a built-in one (membership is implicit). + Task AddGroupMemberAsync(string group, string userId, string? actor, CancellationToken cancellationToken); + + /// Removes a user from a group (idempotent). + Task RemoveGroupMemberAsync(string group, string userId, string? actor, CancellationToken cancellationToken); + + /// Creates a permission target without grants. + /// Unique name. + /// Repository names or * globs. + /// Package ID globs; null or empty means all. + /// Package ID globs to leave out. + /// The administering project, if any. + /// The user making the change. + /// The cancellation token. + /// The name is invalid or taken, or no repository pattern is given. + Task CreateTargetAsync( + string name, + IReadOnlyCollection repositoryPatterns, + IReadOnlyCollection? includePatterns, + IReadOnlyCollection? excludePatterns, + int? projectKey, + string? actor, + CancellationToken cancellationToken); + + /// Replaces a target's patterns. + Task UpdateTargetAsync( + string name, + IReadOnlyCollection repositoryPatterns, + IReadOnlyCollection? includePatterns, + IReadOnlyCollection? excludePatterns, + string? actor, + CancellationToken cancellationToken); + + /// Deletes a target and its grants (built-in ones too; brings them back). + Task DeleteTargetAsync(string name, string? actor, CancellationToken cancellationToken); + + /// + /// Sets the actions a principal holds through a target, replacing any earlier grant to the same principal; + /// removes it. + /// + /// The target's name. + /// What kind of principal. + /// A user's id, or a group's or organization's key. + /// The actions granted. + /// The user making the change. + /// The cancellation token. + Task SetGrantAsync( + string target, + PrincipalType type, + string principalId, + AccessAction actions, + string? actor, + CancellationToken cancellationToken); + + /// Creates a project (no repositories yet: set ). + Task CreateProjectAsync(string name, string? displayName, string? actor, CancellationToken cancellationToken); + + /// Gives a user or group a role in a project, replacing an earlier one. + Task SetProjectMemberAsync( + string project, + PrincipalType type, + string principalId, + ProjectRole role, + string? actor, + CancellationToken cancellationToken); + + /// Removes a user or group from a project. + Task RemoveProjectMemberAsync( + string project, + PrincipalType type, + string principalId, + string? actor, + CancellationToken cancellationToken); + + /// Renames a group. Built-in groups keep their names (the evaluator finds them by name). + /// Unknown or built-in group, or the new name is invalid or taken. + Task RenameGroupAsync(string name, string newName, string? actor, CancellationToken cancellationToken); + + /// + /// Deletes a project: its members, its permission targets (with their grants) and its link to repositories, which + /// stay and become project-less. Audited. + /// + /// Unknown project. + Task DeleteProjectAsync(string name, string? actor, CancellationToken cancellationToken); + + /// Puts a repository in a project, or takes it out of its project when is null. + /// Unknown repository or project. + Task SetRepositoryProjectAsync(string repository, string? project, string? actor, CancellationToken cancellationToken); + + /// Every group with its member count, ordered by name (built-ins first). + Task> ListGroupsAsync(CancellationToken cancellationToken); + + /// The group with its members and the grants naming it, or null. + Task GetGroupAsync(string name, CancellationToken cancellationToken); + + /// The names of the groups is a member of (the implicit built-ins excluded). + Task> GroupsOfUserAsync(string userId, CancellationToken cancellationToken); + + /// Every permission target, ordered by name. + Task> ListTargetsAsync(CancellationToken cancellationToken); + + /// The target with its grants, or null. + Task GetTargetAsync(string name, CancellationToken cancellationToken); + + /// Every project with its counts, ordered by name. + Task> ListProjectsAsync(CancellationToken cancellationToken); + + /// The project with its repositories, members and targets, or null. + Task GetProjectAsync(string name, CancellationToken cancellationToken); + + /// + /// The roles holds in projects, directly or through a group (including the built-in + /// Authenticated and Everyone groups). + /// + Task> ProjectRolesOfUserAsync(string userId, CancellationToken cancellationToken); + + /// Whether holds the Admin role in . + Task IsProjectAdminAsync(string userId, string project, CancellationToken cancellationToken); + + /// + /// The id of the user, group or organization called (what and + /// take), or null when there is none. + /// + Task ResolvePrincipalAsync(PrincipalType type, string name, CancellationToken cancellationToken); + + /// Users whose name contains , ordered by name; for the member pickers. + Task> SearchUsersAsync(string text, int take, CancellationToken cancellationToken); + + /// The audit entries matching , newest first. + Task> AuditAsync(AuditFilter filter, int take, CancellationToken cancellationToken); + + /// Re-creates the built-in groups and targets with their upgrade defaults where they are missing. + Task RestoreBuiltInsAsync(string? actor, CancellationToken cancellationToken); + + /// The most recent audit entries, newest first. + Task> AuditAsync(int take, CancellationToken cancellationToken); +} + +/// over the relational database. +public class AccessAdministration : IAccessAdministration +{ + private readonly IContext _context; + private readonly SystemTime _time; + + public AccessAdministration(IContext context, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + /// + /// Adds an audit entry to the context without saving, so the caller's own save writes both. + /// + internal static void Audit(IContext context, DateTime now, string? actor, string action, string? subject, object? details = null) + { + context.AccessAuditEntries!.Add(new AccessAuditEntry + { + Created = now, + Actor = actor, + Action = action, + Subject = subject, + Details = details == null ? null : JsonSerializer.Serialize(details), + }); + } + + /// + /// Stages (no save) the removal of everything the access model holds for a principal that is going away: its + /// group memberships (users only), permission grants and project roles. The caller saves it together with the + /// deletion of the principal itself, so the database applies all of it or none of it; the interceptor then + /// invalidates the evaluator's cache. Shared by the user and the organization deletion paths. + /// + /// How many rows were staged for removal. + internal static async Task StageCleanupAsync(IContext context, PrincipalType type, string? id, CancellationToken cancellationToken) + { + if (id == null || context.PermissionGrants == null) return 0; + + var removed = 0; + if (type == PrincipalType.User) + { + var memberships = await context.GroupMembers!.Where(m => m.UserId == id).ToListAsync(cancellationToken).ConfigureAwait(false); + context.GroupMembers!.RemoveRange(memberships); + removed += memberships.Count; + } + + var grants = await context.PermissionGrants.Where(g => g.PrincipalType == type && g.PrincipalId == id).ToListAsync(cancellationToken).ConfigureAwait(false); + context.PermissionGrants.RemoveRange(grants); + var roles = await context.ProjectMembers!.Where(m => m.PrincipalType == type && m.PrincipalId == id).ToListAsync(cancellationToken).ConfigureAwait(false); + context.ProjectMembers!.RemoveRange(roles); + + return removed + grants.Count + roles.Count; + } + + private void Audit(string? actor, string action, string? subject, object? details = null) + => Audit(_context, _time.UtcNow, actor, action, subject, details); + + /// + public async Task CreateGroupAsync(string name, string? description, string? actor, CancellationToken cancellationToken) + { + if (!AccessNames.IsValid(name, out var error)) throw new AccessModelException(error!); + if (await FindGroupAsync(name, cancellationToken).ConfigureAwait(false) != null) + { + throw new AccessModelException($"There is already a group named '{name}'."); + } + + var group = new Group { Name = name, Description = description, Created = _time.UtcNow }; + _context.Groups!.Add(group); + Audit(actor, "group.create", name); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return group; + } + + /// + public async Task DeleteGroupAsync(string name, string? actor, CancellationToken cancellationToken) + { + var group = await GroupAsync(name, cancellationToken).ConfigureAwait(false); + if (group.IsBuiltIn) throw new AccessModelException($"'{group.Name}' is a built-in group and cannot be deleted."); + + var id = group.Key.ToString(); + var grants = await _context.PermissionGrants! + .Where(g => g.PrincipalType == PrincipalType.Group && g.PrincipalId == id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + var projectRoles = await _context.ProjectMembers! + .Where(m => m.PrincipalType == PrincipalType.Group && m.PrincipalId == id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + _context.PermissionGrants!.RemoveRange(grants); + _context.ProjectMembers!.RemoveRange(projectRoles); + _context.Groups!.Remove(group); + Audit(actor, "group.delete", group.Name, new { grants = grants.Count, projectMemberships = projectRoles.Count }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task AddGroupMemberAsync(string group, string userId, string? actor, CancellationToken cancellationToken) + { + var row = await GroupAsync(group, cancellationToken).ConfigureAwait(false); + if (row.IsBuiltIn) throw new AccessModelException($"Membership of the built-in group '{row.Name}' is implicit."); + if (string.IsNullOrEmpty(userId)) throw new AccessModelException("A user is required."); + // GroupMember.UserId is a foreign key to the users table: say so instead of failing the save. + if (!await _context.Users.AnyAsync(u => u.Id == userId, cancellationToken).ConfigureAwait(false)) throw new AccessModelException("There is no such user."); + + if (await _context.GroupMembers!.AnyAsync(m => m.GroupKey == row.Key && m.UserId == userId, cancellationToken).ConfigureAwait(false)) return; + + _context.GroupMembers!.Add(new GroupMember { GroupKey = row.Key, UserId = userId }); + Audit(actor, "group.member.add", row.Name, new { userId }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task RemoveGroupMemberAsync(string group, string userId, string? actor, CancellationToken cancellationToken) + { + var row = await GroupAsync(group, cancellationToken).ConfigureAwait(false); + var member = await _context.GroupMembers!.FirstOrDefaultAsync(m => m.GroupKey == row.Key && m.UserId == userId, cancellationToken).ConfigureAwait(false); + if (member == null) return; + + _context.GroupMembers!.Remove(member); + Audit(actor, "group.member.remove", row.Name, new { userId }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task CreateTargetAsync( + string name, + IReadOnlyCollection repositoryPatterns, + IReadOnlyCollection? includePatterns, + IReadOnlyCollection? excludePatterns, + int? projectKey, + string? actor, + CancellationToken cancellationToken) + { + if (!AccessNames.IsValid(name, out var error)) throw new AccessModelException(error!); + if (await FindTargetAsync(name, cancellationToken).ConfigureAwait(false) != null) + { + throw new AccessModelException($"There is already a permission target named '{name}'."); + } + + var target = new PermissionTarget { Name = name, ProjectKey = projectKey, Created = _time.UtcNow }; + Apply(target, repositoryPatterns, includePatterns, excludePatterns); + _context.PermissionTargets!.Add(target); + Audit(actor, "target.create", name, Describe(target)); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return target; + } + + /// + public async Task UpdateTargetAsync( + string name, + IReadOnlyCollection repositoryPatterns, + IReadOnlyCollection? includePatterns, + IReadOnlyCollection? excludePatterns, + string? actor, + CancellationToken cancellationToken) + { + var target = await TargetAsync(name, cancellationToken).ConfigureAwait(false); + Apply(target, repositoryPatterns, includePatterns, excludePatterns); + Audit(actor, "target.update", name, Describe(target)); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task DeleteTargetAsync(string name, string? actor, CancellationToken cancellationToken) + { + var target = await TargetAsync(name, cancellationToken).ConfigureAwait(false); + var grants = await _context.PermissionGrants!.Where(g => g.TargetKey == target.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + + _context.PermissionGrants!.RemoveRange(grants); + _context.PermissionTargets!.Remove(target); + Audit(actor, "target.delete", name, new { grants = grants.Count }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task SetGrantAsync( + string target, + PrincipalType type, + string principalId, + AccessAction actions, + string? actor, + CancellationToken cancellationToken) + { + var row = await TargetAsync(target, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrEmpty(principalId)) throw new AccessModelException("A principal is required."); + if ((actions & ~AccessAction.All) != 0) throw new AccessModelException("Unknown actions."); + + var grant = await _context.PermissionGrants!.FirstOrDefaultAsync( + g => g.TargetKey == row.Key && g.PrincipalType == type && g.PrincipalId == principalId, cancellationToken).ConfigureAwait(false); + + if (actions == AccessAction.None) + { + if (grant == null) return; + _context.PermissionGrants!.Remove(grant); + } + else if (grant == null) + { + _context.PermissionGrants!.Add(new PermissionGrant { TargetKey = row.Key, PrincipalType = type, PrincipalId = principalId, Actions = actions }); + } + else + { + grant.Actions = actions; + } + + Audit(actor, "grant.set", row.Name, new { principalType = type.ToString(), principalId, actions = actions.ToString() }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task CreateProjectAsync(string name, string? displayName, string? actor, CancellationToken cancellationToken) + { + if (!AccessNames.IsValid(name, out var error)) throw new AccessModelException(error!); + if (await _context.Projects!.AnyAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false)) + { + throw new AccessModelException($"There is already a project named '{name}'."); + } + + var project = new Project { Name = name, DisplayName = displayName, Created = _time.UtcNow }; + _context.Projects!.Add(project); + Audit(actor, "project.create", name); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return project; + } + + /// + public async Task SetProjectMemberAsync( + string project, + PrincipalType type, + string principalId, + ProjectRole role, + string? actor, + CancellationToken cancellationToken) + { + if (type == PrincipalType.Organization) throw new AccessModelException("A project member is a user or a group."); + var row = await ProjectAsync(project, cancellationToken).ConfigureAwait(false); + + var member = await _context.ProjectMembers!.FirstOrDefaultAsync( + m => m.ProjectKey == row.Key && m.PrincipalType == type && m.PrincipalId == principalId, cancellationToken).ConfigureAwait(false); + if (member == null) + { + _context.ProjectMembers!.Add(new ProjectMember { ProjectKey = row.Key, PrincipalType = type, PrincipalId = principalId, Role = role }); + } + else + { + member.Role = role; + } + + Audit(actor, "project.member.set", row.Name, new { principalType = type.ToString(), principalId, role = role.ToString() }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task RemoveProjectMemberAsync(string project, PrincipalType type, string principalId, string? actor, CancellationToken cancellationToken) + { + var row = await ProjectAsync(project, cancellationToken).ConfigureAwait(false); + var member = await _context.ProjectMembers!.FirstOrDefaultAsync( + m => m.ProjectKey == row.Key && m.PrincipalType == type && m.PrincipalId == principalId, cancellationToken).ConfigureAwait(false); + if (member == null) return; + + _context.ProjectMembers!.Remove(member); + Audit(actor, "project.member.remove", row.Name, new { principalType = type.ToString(), principalId }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task RenameGroupAsync(string name, string newName, string? actor, CancellationToken cancellationToken) + { + var group = await GroupAsync(name, cancellationToken).ConfigureAwait(false); + if (group.IsBuiltIn) throw new AccessModelException($"'{group.Name}' is a built-in group and cannot be renamed."); + if (!AccessNames.IsValid(newName, out var error)) throw new AccessModelException(error!); + + var other = await FindGroupAsync(newName, cancellationToken).ConfigureAwait(false); + if (other != null && other.Key != group.Key) throw new AccessModelException($"There is already a group named '{newName}'."); + + var old = group.Name; + group.Name = newName; + Audit(actor, "group.rename", newName, new { from = old }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task DeleteProjectAsync(string name, string? actor, CancellationToken cancellationToken) + { + var project = await ProjectAsync(name, cancellationToken).ConfigureAwait(false); + + var targets = await _context.PermissionTargets!.Where(t => t.ProjectKey == project.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var targetKeys = targets.Select(t => t.Key).ToList(); + var grants = await _context.PermissionGrants!.Where(g => targetKeys.Contains(g.TargetKey)).ToListAsync(cancellationToken).ConfigureAwait(false); + var members = await _context.ProjectMembers!.Where(m => m.ProjectKey == project.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var repositories = await _context.Repositories!.Where(r => r.ProjectKey == project.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + + foreach (var repository in repositories) repository.ProjectKey = null; + var scanPolicies = await _context.ScanPolicies!.Where(p => p.ProjectKey == project.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + _context.ScanPolicies!.RemoveRange(scanPolicies); + // The project's retention policy applies to nothing once it is gone (and its ProjectKey is a foreign key). A run of it that is + // still going ends normally: it only reads the policy up front and RetentionEngine.RecordRunAsync skips a policy that is gone. + var retentionPolicies = await _context.RetentionPolicies!.Where(p => p.ProjectKey == project.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + _context.RetentionPolicies!.RemoveRange(retentionPolicies); + foreach (var policy in retentionPolicies) Audit(actor, "retention.policy.delete", policy.Name, new { project = project.Name, reason = "project deleted" }); + _context.PermissionGrants!.RemoveRange(grants); + _context.PermissionTargets!.RemoveRange(targets); + _context.ProjectMembers!.RemoveRange(members); + _context.Projects!.Remove(project); + Audit(actor, "project.delete", project.Name, new { targets = targets.Count, members = members.Count, repositories = repositories.Count, scanPolicies = scanPolicies.Count, retentionPolicies = retentionPolicies.Count }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task SetRepositoryProjectAsync(string repository, string? project, string? actor, CancellationToken cancellationToken) + { + var row = await _context.Repositories!.FirstOrDefaultAsync(r => r.Name == repository, cancellationToken).ConfigureAwait(false) + ?? throw new AccessModelException($"There is no repository named '{repository}'."); + var target = project == null ? null : await ProjectAsync(project, cancellationToken).ConfigureAwait(false); + + row.ProjectKey = target?.Key; + Audit(actor, "repository.project", repository, new { project }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> ListGroupsAsync(CancellationToken cancellationToken) + { + var groups = await _context.Groups!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + var counts = await _context.GroupMembers!.AsNoTracking() + .GroupBy(m => m.GroupKey) + .Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + + return groups + .OrderBy(g => g.IsBuiltIn ? 0 : 1) + .ThenBy(g => g.Name, StringComparer.OrdinalIgnoreCase) + .Select(g => Summarize(g, counts)) + .ToList(); + } + + /// + public async Task GetGroupAsync(string name, CancellationToken cancellationToken) + { + var group = await FindGroupAsync(name, cancellationToken).ConfigureAwait(false); + if (group == null) return null; + var groupKey = group.Key; + + var members = await (from m in _context.GroupMembers!.AsNoTracking() + join u in _context.Users.AsNoTracking() on m.UserId equals u.Id + where m.GroupKey == groupKey + orderby u.UserName + select new GroupMemberInfo(u.Id, u.UserName ?? u.Id)).ToListAsync(cancellationToken).ConfigureAwait(false); + + var id = group.Key.ToString(); + var grants = await _context.PermissionGrants!.AsNoTracking() + .Where(g => g.PrincipalType == PrincipalType.Group && g.PrincipalId == id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new GroupDetails( + new GroupSummary(group.Key, group.Name ?? string.Empty, group.Description, group.IsBuiltIn, members.Count), + members, + await DescribeGrantsAsync(grants, cancellationToken).ConfigureAwait(false)); + } + + /// + public async Task> GroupsOfUserAsync(string userId, CancellationToken cancellationToken) + => await (from m in _context.GroupMembers!.AsNoTracking() + join g in _context.Groups!.AsNoTracking() on m.GroupKey equals g.Key + where m.UserId == userId + orderby g.Name + select g.Name!).ToListAsync(cancellationToken).ConfigureAwait(false); + + /// + public async Task> ListTargetsAsync(CancellationToken cancellationToken) + { + var targets = await _context.PermissionTargets!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + var counts = await _context.PermissionGrants!.AsNoTracking() + .GroupBy(g => g.TargetKey) + .Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + + return await SummarizeAsync(targets, counts, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task GetTargetAsync(string name, CancellationToken cancellationToken) + { + var target = await FindTargetAsync(name, cancellationToken).ConfigureAwait(false); + if (target == null) return null; + + var grants = await _context.PermissionGrants!.AsNoTracking().Where(g => g.TargetKey == target.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var summary = (await SummarizeAsync(new[] { target }, new Dictionary { { target.Key, grants.Count } }, cancellationToken).ConfigureAwait(false))[0]; + + return new TargetDetails(summary, await DescribeGrantsAsync(grants, cancellationToken, target.Name).ConfigureAwait(false)); + } + + /// + public async Task> ListProjectsAsync(CancellationToken cancellationToken) + { + var projects = await _context.Projects!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + var repositories = await _context.Repositories!.AsNoTracking().Where(r => r.ProjectKey != null) + .GroupBy(r => r.ProjectKey!.Value).Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + var members = await _context.ProjectMembers!.AsNoTracking() + .GroupBy(m => m.ProjectKey).Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + + return projects + .OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase) + .Select(p => new ProjectSummary( + p.Key, + p.Name ?? string.Empty, + p.DisplayName, + repositories.TryGetValue(p.Key, out var r) ? r : 0, + members.TryGetValue(p.Key, out var m) ? m : 0)) + .ToList(); + } + + /// + public async Task GetProjectAsync(string name, CancellationToken cancellationToken) + { + var project = await _context.Projects!.AsNoTracking().FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (project == null) return null; + + var repositories = await _context.Repositories!.AsNoTracking() + .Where(r => r.ProjectKey == project.Key).Select(r => r.Name!).ToListAsync(cancellationToken).ConfigureAwait(false); + var members = await _context.ProjectMembers!.AsNoTracking().Where(m => m.ProjectKey == project.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var targets = await _context.PermissionTargets!.AsNoTracking().Where(t => t.ProjectKey == project.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var counts = await _context.PermissionGrants!.AsNoTracking() + .GroupBy(g => g.TargetKey).Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + + var namer = await PrincipalNamerAsync(members.Select(m => (m.PrincipalType, m.PrincipalId ?? string.Empty)), cancellationToken).ConfigureAwait(false); + + return new ProjectDetails( + new ProjectSummary(project.Key, project.Name ?? string.Empty, project.DisplayName, repositories.Count, members.Count), + repositories.OrderBy(r => r, StringComparer.Ordinal).ToList(), + members + .Select(m => new ProjectMemberInfo(m.PrincipalType, m.PrincipalId ?? string.Empty, namer(m.PrincipalType, m.PrincipalId ?? string.Empty), m.Role)) + .OrderBy(m => m.Principal, StringComparer.OrdinalIgnoreCase) + .ToList(), + await SummarizeAsync(targets, counts, cancellationToken).ConfigureAwait(false)); + } + + /// + public async Task> ProjectRolesOfUserAsync(string userId, CancellationToken cancellationToken) + { + var groupKeys = await GroupKeysOfAsync(userId, cancellationToken).ConfigureAwait(false); + var groupNames = await _context.Groups!.AsNoTracking().ToDictionaryAsync(g => g.Key, g => g.Name ?? string.Empty, cancellationToken).ConfigureAwait(false); + var projects = await _context.Projects!.AsNoTracking().ToDictionaryAsync(p => p.Key, p => p.Name ?? string.Empty, cancellationToken).ConfigureAwait(false); + var members = await _context.ProjectMembers!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + + var roles = new List(); + foreach (var member in members) + { + if (!projects.TryGetValue(member.ProjectKey, out var project)) continue; + + if (member.PrincipalType == PrincipalType.User && member.PrincipalId == userId) + { + roles.Add(new UserProjectRole(project, member.Role, "directly")); + } + else if (member.PrincipalType == PrincipalType.Group + && int.TryParse(member.PrincipalId, out var group) && groupKeys.Contains(group)) + { + roles.Add(new UserProjectRole(project, member.Role, "through group " + (groupNames.TryGetValue(group, out var n) ? n : member.PrincipalId))); + } + } + + return roles.OrderBy(r => r.Project, StringComparer.OrdinalIgnoreCase).ToList(); + } + + /// + public async Task IsProjectAdminAsync(string userId, string project, CancellationToken cancellationToken) + => (await ProjectRolesOfUserAsync(userId, cancellationToken).ConfigureAwait(false)) + .Any(r => r.Role == ProjectRole.Admin && string.Equals(r.Project, project, StringComparison.Ordinal)); + + /// + public async Task ResolvePrincipalAsync(PrincipalType type, string name, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(name)) return null; + name = name.Trim(); + var lower = name.ToLowerInvariant(); + + switch (type) + { + case PrincipalType.User: + var upper = name.ToUpperInvariant(); + return await _context.Users.AsNoTracking() + .Where(u => u.NormalizedUserName == upper) + .Select(u => u.Id).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + + case PrincipalType.Group: + return (await FindGroupAsync(name, cancellationToken).ConfigureAwait(false))?.Key.ToString(); + + default: + var organization = await _context.Organizations!.AsNoTracking() + .FirstOrDefaultAsync(o => o.Name!.ToLower() == lower, cancellationToken).ConfigureAwait(false); + return organization?.Key.ToString(); + } + } + + /// + public async Task> SearchUsersAsync(string text, int take, CancellationToken cancellationToken) + { + var upper = (text ?? string.Empty).Trim().ToUpperInvariant(); + + return await _context.Users.AsNoTracking() + .Where(u => u.NormalizedUserName!.Contains(upper)) + .OrderBy(u => u.UserName) + .Take(Math.Max(1, take)) + .Select(u => new GroupMemberInfo(u.Id, u.UserName ?? u.Id)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> AuditAsync(AuditFilter filter, int take, CancellationToken cancellationToken) + { + IQueryable query = _context.AccessAuditEntries!.AsNoTracking(); + + if (!string.IsNullOrWhiteSpace(filter?.Actor)) + { + var actor = filter!.Actor!.Trim().ToLowerInvariant(); + query = query.Where(e => e.Actor!.ToLower() == actor); + } + + if (!string.IsNullOrWhiteSpace(filter?.Subject)) + { + var subject = filter!.Subject!.Trim().ToLowerInvariant(); + query = query.Where(e => e.Subject!.ToLower().Contains(subject)); + } + + if (filter?.From != null) + { + var from = filter.From.Value; + query = query.Where(e => e.Created >= from); + } + + if (filter?.To != null) + { + var to = filter.To.Value; + query = query.Where(e => e.Created < to); + } + + return await query + .OrderByDescending(e => e.Created).ThenByDescending(e => e.Key) + .Take(Math.Max(1, take)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + private static GroupSummary Summarize(Group group, IReadOnlyDictionary counts) + => new(group.Key, group.Name ?? string.Empty, group.Description, group.IsBuiltIn, counts.TryGetValue(group.Key, out var n) ? n : 0); + + private async Task> SummarizeAsync( + IEnumerable targets, + IReadOnlyDictionary grantCounts, + CancellationToken cancellationToken) + { + var projects = await _context.Projects!.AsNoTracking().ToDictionaryAsync(p => p.Key, p => p.Name ?? string.Empty, cancellationToken).ConfigureAwait(false); + + return targets + .OrderBy(t => t.Name, StringComparer.OrdinalIgnoreCase) + .Select(t => new TargetSummary( + t.Key, + t.Name ?? string.Empty, + t.RepositoryPatterns ?? Array.Empty(), + t.IncludePatterns ?? Array.Empty(), + t.ExcludePatterns ?? Array.Empty(), + t.ProjectKey, + t.ProjectKey != null && projects.TryGetValue(t.ProjectKey.Value, out var project) ? project : null, + t.IsBuiltIn, + grantCounts.TryGetValue(t.Key, out var n) ? n : 0)) + .ToList(); + } + + private async Task> DescribeGrantsAsync( + IReadOnlyList grants, + CancellationToken cancellationToken, + string? targetName = null) + { + var namer = await PrincipalNamerAsync(grants.Select(g => (g.PrincipalType, g.PrincipalId ?? string.Empty)), cancellationToken).ConfigureAwait(false); + var targets = targetName != null + ? null + : await _context.PermissionTargets!.AsNoTracking().ToDictionaryAsync(t => t.Key, t => t.Name ?? string.Empty, cancellationToken).ConfigureAwait(false); + + return grants + .Select(g => new GrantInfo( + targetName ?? (targets!.TryGetValue(g.TargetKey, out var t) ? t : g.TargetKey.ToString()), + g.PrincipalType, + g.PrincipalId ?? string.Empty, + namer(g.PrincipalType, g.PrincipalId ?? string.Empty), + g.Actions)) + .OrderBy(g => g.Target, StringComparer.OrdinalIgnoreCase) + .ThenBy(g => g.Principal, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + // Resolves principals to words with one query per kind, for the ids that are asked about. + private async Task> PrincipalNamerAsync( + IEnumerable<(PrincipalType Type, string Id)> principals, + CancellationToken cancellationToken) + { + var list = principals.ToList(); + var groupKeys = list.Where(p => p.Type == PrincipalType.Group && int.TryParse(p.Id, out _)).Select(p => int.Parse(p.Id)).Distinct().ToList(); + var organizationKeys = list.Where(p => p.Type == PrincipalType.Organization && int.TryParse(p.Id, out _)).Select(p => int.Parse(p.Id)).Distinct().ToList(); + var userIds = list.Where(p => p.Type == PrincipalType.User).Select(p => p.Id).Distinct().ToList(); + + var groups = await _context.Groups!.AsNoTracking().Where(g => groupKeys.Contains(g.Key)).ToDictionaryAsync(g => g.Key, g => g.Name ?? string.Empty, cancellationToken).ConfigureAwait(false); + var organizations = await _context.Organizations!.AsNoTracking().Where(o => organizationKeys.Contains(o.Key)).ToDictionaryAsync(o => o.Key, o => o.Name ?? string.Empty, cancellationToken).ConfigureAwait(false); + var users = await _context.Users.AsNoTracking().Where(u => userIds.Contains(u.Id)).ToDictionaryAsync(u => u.Id, u => u.UserName ?? u.Id, cancellationToken).ConfigureAwait(false); + + return (type, id) => type switch + { + PrincipalType.User => "user " + (users.TryGetValue(id, out var user) ? user : id), + PrincipalType.Group => "group " + (int.TryParse(id, out var g) && groups.TryGetValue(g, out var group) ? group : id), + _ => "organization " + (int.TryParse(id, out var o) && organizations.TryGetValue(o, out var organization) ? organization : id), + }; + } + + // The keys of the groups whose members include the user, built-ins that apply to every signed-in caller included. + private async Task> GroupKeysOfAsync(string userId, CancellationToken cancellationToken) + { + var keys = await _context.GroupMembers!.AsNoTracking().Where(m => m.UserId == userId).Select(m => m.GroupKey).ToListAsync(cancellationToken).ConfigureAwait(false); + var builtIn = await _context.Groups!.AsNoTracking().Where(g => g.IsBuiltIn).Select(g => g.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + + return keys.Concat(builtIn).ToHashSet(); + } + + /// + public async Task RestoreBuiltInsAsync(string? actor, CancellationToken cancellationToken) + { + var everyone = await EnsureBuiltInGroupAsync(BuiltInNames.Everyone, "Every caller, anonymous ones included.", cancellationToken).ConfigureAwait(false); + var authenticated = await EnsureBuiltInGroupAsync(BuiltInNames.Authenticated, "Every caller that presented valid credentials.", cancellationToken).ConfigureAwait(false); + + // Keys are generated here, so save the groups before naming them in grants. + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + await EnsureBuiltInTargetAsync(BuiltInNames.AnyoneReads, everyone, AccessAction.Read, cancellationToken).ConfigureAwait(false); + await EnsureBuiltInTargetAsync( + BuiltInNames.AuthenticatedDeploy, + authenticated, + AccessAction.Annotate | AccessAction.Deploy | AccessAction.Delete | AccessAction.Manage, + cancellationToken).ConfigureAwait(false); + + Audit(actor, "builtins.restore", null); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> AuditAsync(int take, CancellationToken cancellationToken) + => await _context.AccessAuditEntries!.AsNoTracking() + .OrderByDescending(e => e.Created).ThenByDescending(e => e.Key) + .Take(Math.Max(1, take)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + private async Task EnsureBuiltInGroupAsync(string name, string description, CancellationToken cancellationToken) + { + var group = await FindGroupAsync(name, cancellationToken).ConfigureAwait(false); + if (group != null) + { + group.IsBuiltIn = true; + return group; + } + + group = new Group { Name = name, Description = description, Created = _time.UtcNow, IsBuiltIn = true }; + _context.Groups!.Add(group); + return group; + } + + private async Task EnsureBuiltInTargetAsync(string name, Group group, AccessAction actions, CancellationToken cancellationToken) + { + var target = await FindTargetAsync(name, cancellationToken).ConfigureAwait(false); + if (target == null) + { + target = new PermissionTarget + { + Name = name, + RepositoryPatterns = new[] { "*" }, + IncludePatterns = new[] { "*" }, + ExcludePatterns = Array.Empty(), + IsBuiltIn = true, + Created = _time.UtcNow, + }; + _context.PermissionTargets!.Add(target); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + var id = group.Key.ToString(); + if (!await _context.PermissionGrants!.AnyAsync( + g => g.TargetKey == target.Key && g.PrincipalType == PrincipalType.Group && g.PrincipalId == id, cancellationToken).ConfigureAwait(false)) + { + _context.PermissionGrants!.Add(new PermissionGrant { TargetKey = target.Key, PrincipalType = PrincipalType.Group, PrincipalId = id, Actions = actions }); + } + } + + private static void Apply( + PermissionTarget target, + IReadOnlyCollection repositoryPatterns, + IReadOnlyCollection? includePatterns, + IReadOnlyCollection? excludePatterns) + { + string[] Clean(IEnumerable? patterns) + => (patterns ?? Array.Empty()).Select(p => p?.Trim() ?? string.Empty).Where(p => p.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + + var repositories = Clean(repositoryPatterns); + if (repositories.Length == 0) throw new AccessModelException("A permission target needs at least one repository pattern."); + + target.RepositoryPatterns = repositories; + var include = Clean(includePatterns); + target.IncludePatterns = include.Length == 0 ? new[] { "*" } : include; + target.ExcludePatterns = Clean(excludePatterns); + } + + private static object Describe(PermissionTarget target) => new + { + repositories = target.RepositoryPatterns, + include = target.IncludePatterns, + exclude = target.ExcludePatterns, + projectKey = target.ProjectKey, + }; + + private Task FindGroupAsync(string name, CancellationToken cancellationToken) + { + var lower = name.ToLowerInvariant(); + return _context.Groups!.FirstOrDefaultAsync(g => g.Name!.ToLower() == lower, cancellationToken); + } + + private Task FindTargetAsync(string name, CancellationToken cancellationToken) + { + var lower = name.ToLowerInvariant(); + return _context.PermissionTargets!.FirstOrDefaultAsync(t => t.Name!.ToLower() == lower, cancellationToken); + } + + private async Task GroupAsync(string name, CancellationToken cancellationToken) + => await FindGroupAsync(name, cancellationToken).ConfigureAwait(false) ?? throw new AccessModelException($"There is no group named '{name}'."); + + private async Task TargetAsync(string name, CancellationToken cancellationToken) + => await FindTargetAsync(name, cancellationToken).ConfigureAwait(false) ?? throw new AccessModelException($"There is no permission target named '{name}'."); + + private async Task ProjectAsync(string name, CancellationToken cancellationToken) + => await _context.Projects!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false) + ?? throw new AccessModelException($"There is no project named '{name}'."); +} diff --git a/src/BaGet.Core/Access/IAccessEvaluator.cs b/src/BaGet.Core/Access/IAccessEvaluator.cs new file mode 100644 index 000000000..2eb6864cb --- /dev/null +++ b/src/BaGet.Core/Access/IAccessEvaluator.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Decides what a caller may do in a repository, from the access model (groups, permission targets, project +/// roles). The first of two requirements for a write: package ownership () +/// is the second and still applies inside Deploy, Delete and Annotate. +/// +public interface IAccessEvaluator +{ + /// + /// Whether holds in , on + /// when given (the targets' include and exclude patterns apply), else on the + /// repository as a whole (some package may match). A null principal is an anonymous caller. + /// + /// + /// A principal whose API key is limited to other repositories () holds no + /// action here, not even as an administrator, and reads as an anonymous caller. + /// The server's superuser (global API key) and administrators (D5 of the access plan) hold every action. Where the + /// database is not relational (Azure Table) there is no access model: reading is open and any authenticated caller + /// holds the write actions, as before the model existed. + /// + Task IsAllowedAsync( + BaGetPrincipal? principal, + RepositoryInfo repository, + string? packageId, + AccessAction action, + CancellationToken cancellationToken); + + /// + /// The NuGet repositories may read, ordered by name (default first). + /// + Task> ReadableRepositoriesAsync(BaGetPrincipal? principal, CancellationToken cancellationToken); + + /// + /// The NuGet repositories in which holds , ordered like + /// . + /// + Task> RepositoriesWithAsync(BaGetPrincipal? principal, AccessAction action, CancellationToken cancellationToken); + + /// + /// What may do in (on when + /// given) and which grants and project roles say so: the same decision as , with its + /// reasons, for the admin and account pages. + /// + Task ExplainAsync( + BaGetPrincipal? principal, + RepositoryInfo repository, + string? packageId, + CancellationToken cancellationToken); + + /// Who holds what in , whatever the caller (the repository page's view). + Task DescribeAsync(RepositoryInfo repository, CancellationToken cancellationToken); +} + +/// +/// over the relational database, through the cached . +/// +public sealed class AccessEvaluator : IAccessEvaluator +{ + private readonly IContext _context; + private readonly AccessModelCache _cache; + private readonly IRepositoryService _repositories; + + public AccessEvaluator(IContext context, AccessModelCache cache, IRepositoryService repositories) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _cache = cache ?? throw new ArgumentNullException(nameof(cache)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + } + + /// + public async Task IsAllowedAsync( + BaGetPrincipal? principal, + RepositoryInfo repository, + string? packageId, + AccessAction action, + CancellationToken cancellationToken) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + if (action == AccessAction.None) return true; + + // Nothing is deployed to a remote repository, whoever asks (an administrator included): it holds what the + // server itself cached from its upstream. Reading, deleting cached packages and the rest follow the model. + if (repository.Kind == RepositoryKind.Remote && (action & AccessAction.Deploy) != 0) return false; + + // Nor to a virtual repository: a push to it goes to its deploy repository (the request is redirected there before + // anything is authorized), and Deploy is judged on that one. + if (repository.Kind == RepositoryKind.Virtual && (action & AccessAction.Deploy) != 0) return false; + + // An API key limited to some repositories (ApiKeyRepository) is not a credential in the others: it grants + // nothing there, and a read is judged as the anonymous caller's, so a key never sees more than no key at all. + if (principal != null && !principal.AllowsRepository(repository.Key)) + { + if (action != AccessAction.Read) return false; + principal = null; + } + + if (_context is NullContext) return action == AccessAction.Read || principal != null; + if (principal != null && (principal.IsSuperuser || principal.IsAdministrator)) return true; + + var snapshot = await _cache.GetAsync(_context, cancellationToken).ConfigureAwait(false); + var membership = await MembershipAsync(snapshot, principal, cancellationToken).ConfigureAwait(false); + + return (snapshot.Granted(principal, membership, repository, packageId) & action) == action; + } + + /// + public Task> ReadableRepositoriesAsync(BaGetPrincipal? principal, CancellationToken cancellationToken) + => RepositoriesWithAsync(principal, AccessAction.Read, cancellationToken); + + /// + public async Task> RepositoriesWithAsync( + BaGetPrincipal? principal, + AccessAction action, + CancellationToken cancellationToken) + { + var all = await _repositories.ListAsync(cancellationToken).ConfigureAwait(false); + var result = new List(); + + foreach (var repository in all) + { + if (await IsAllowedAsync(principal, repository, packageId: null, action, cancellationToken).ConfigureAwait(false)) + { + result.Add(repository); + } + } + + return result + .OrderBy(r => r.IsDefault ? 0 : 1) + .ThenBy(r => r.Name, StringComparer.Ordinal) + .ToList(); + } + + /// + public async Task ExplainAsync( + BaGetPrincipal? principal, + RepositoryInfo repository, + string? packageId, + CancellationToken cancellationToken) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + + var explanation = await ExplainCoreAsync(principal, repository, packageId, cancellationToken).ConfigureAwait(false); + + // Mirrors IsAllowedAsync: Deploy is never held in a remote or a virtual repository. + return repository.Kind == RepositoryKind.Remote || repository.Kind == RepositoryKind.Virtual + ? explanation with { Actions = explanation.Actions & ~AccessAction.Deploy } + : explanation; + } + + private async Task ExplainCoreAsync( + BaGetPrincipal? principal, + RepositoryInfo repository, + string? packageId, + CancellationToken cancellationToken) + { + + if (_context is NullContext) + { + return new AccessExplanation( + principal != null ? AccessAction.All : AccessAction.Read, + "This database has no access model: everyone reads and any authenticated caller writes, subject to package ownership.", + Array.Empty()); + } + + if (principal != null && principal.IsSuperuser) + { + return new AccessExplanation(AccessAction.All, "The server's global API key holds every action everywhere.", Array.Empty()); + } + + if (principal != null && principal.IsAdministrator) + { + return new AccessExplanation(AccessAction.All, "Server administrators hold every action everywhere.", Array.Empty()); + } + + var snapshot = await _cache.GetAsync(_context, cancellationToken).ConfigureAwait(false); + var membership = await MembershipAsync(snapshot, principal, cancellationToken).ConfigureAwait(false); + var reasons = new List(); + var actions = snapshot.Granted(principal, membership, repository, packageId, reasons); + + return new AccessExplanation(actions, null, reasons); + } + + /// + public async Task DescribeAsync(RepositoryInfo repository, CancellationToken cancellationToken) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + if (_context is NullContext) return new RepositoryAccessSummary(repository, AnonymousRead: true, Project: null, ModelAvailable: false, Array.Empty()); + + var snapshot = await _cache.GetAsync(_context, cancellationToken).ConfigureAwait(false); + snapshot.Repositories.TryGetValue(repository.Key, out var row); + var holders = snapshot.Holders(repository); + + var userIds = holders.Where(h => h.PrincipalType == PrincipalType.User).Select(h => h.PrincipalId).Distinct().ToList(); + if (userIds.Count > 0) + { + var names = await _context.Users.AsNoTracking() + .Where(u => userIds.Contains(u.Id)) + .Select(u => new { u.Id, u.UserName }) + .ToDictionaryAsync(u => u.Id, u => u.UserName, cancellationToken).ConfigureAwait(false); + holders = holders + .Select(h => h.PrincipalType == PrincipalType.User && names.TryGetValue(h.PrincipalId, out var name) + ? h with { Principal = "user " + name } + : h) + .ToList(); + } + + return new RepositoryAccessSummary( + repository, + row?.AnonymousRead ?? true, + row?.ProjectKey != null && snapshot.ProjectNames.TryGetValue(row.ProjectKey.Value, out var project) ? project : null, + ModelAvailable: true, + holders); + } + + private Task MembershipAsync(AccessSnapshot snapshot, BaGetPrincipal? principal, CancellationToken cancellationToken) + => principal?.UserId == null + ? Task.FromResult(Membership.None) + : snapshot.MembershipAsync(_context, principal.UserId, cancellationToken); +} diff --git a/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs b/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs index 7c4c63de3..1906ae08f 100644 --- a/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs +++ b/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs @@ -1,30 +1,38 @@ using System; +using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +public class ApiKeyAuthenticationService : IAuthenticationService { - public class ApiKeyAuthenticationService : IAuthenticationService - { - private readonly string _apiKey; + private readonly byte[]? _apiKey; - public ApiKeyAuthenticationService(IOptionsSnapshot options) - { - if (options == null) throw new ArgumentNullException(nameof(options)); + public ApiKeyAuthenticationService(IOptionsSnapshot options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); - _apiKey = string.IsNullOrEmpty(options.Value.ApiKey) ? null : options.Value.ApiKey; - } + _apiKey = string.IsNullOrEmpty(options.Value.ApiKey) + ? null + : Encoding.UTF8.GetBytes(options.Value.ApiKey); + } - public Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken) - => Task.FromResult(Authenticate(apiKey)); + public Task AuthenticateAsync(string? apiKey, CancellationToken cancellationToken) + => Task.FromResult(Authenticate(apiKey)); - private bool Authenticate(string apiKey) - { - // No authentication is necessary if there is no required API key. - if (_apiKey == null) return true; + private bool Authenticate(string? apiKey) + { + // No authentication is necessary if there is no required API key. + if (_apiKey == null) return true; + if (string.IsNullOrEmpty(apiKey)) return false; - return _apiKey == apiKey; - } + // Compared in fixed time. An ordinary string comparison returns at the first + // differing character, so the time it takes says how much of the key was right, + // and a caller who can measure that can learn the key one character at a time. + // Only the length still leaks, which is what every fixed-time comparison does. + return CryptographicOperations.FixedTimeEquals(_apiKey, Encoding.UTF8.GetBytes(apiKey)); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Authentication/BaGetPrincipal.cs b/src/BaGet.Core/Authentication/BaGetPrincipal.cs new file mode 100644 index 000000000..fefc36931 --- /dev/null +++ b/src/BaGet.Core/Authentication/BaGetPrincipal.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace BaGet.Core; + +/// +/// Who an API key authenticated, and what it may do. +/// +public sealed class BaGetPrincipal +{ + /// + /// The server's global API key, or any caller when no key is configured: it may do + /// anything to any package. + /// + public static readonly BaGetPrincipal Superuser = new( + userId: null, + userName: null, + isSuperuser: true, + scopes: ApiKeyScopes.All, + packageGlobPattern: "*"); + + public BaGetPrincipal( + string? userId, + string? userName, + bool isSuperuser, + IReadOnlyList? scopes, + string? packageGlobPattern, + bool isAdministrator = false, + IReadOnlyList? repositoryKeys = null, + bool isInteractiveSession = false) + { + IsInteractiveSession = isInteractiveSession; + RepositoryKeys = repositoryKeys; + UserId = userId; + UserName = userName; + IsSuperuser = isSuperuser; + IsAdministrator = isAdministrator; + Scopes = scopes ?? Array.Empty(); + PackageGlobPattern = string.IsNullOrEmpty(packageGlobPattern) ? "*" : packageGlobPattern; + } + + public string? UserId { get; } + + public string? UserName { get; } + + public bool IsSuperuser { get; } + + /// + /// The credential is a person's interactive session (the browser cookie, or a session token of /api/ui/session), not an API key: it + /// has the rights of the signed-in user with every scope and no repository limit. Account self-service and package ownership screens + /// are open to it and never to a key. + /// + public bool IsInteractiveSession { get; } + + /// + /// The user is an administrator: skips package ownership, never the key's scopes or glob. + /// + public bool IsAdministrator { get; } + + public IReadOnlyList Scopes { get; } + + /// + /// The keys of the only repositories the credential may be used in (), or null for + /// every repository: the global key, a browser session and a key without a repository limit. + /// + public IReadOnlyList? RepositoryKeys { get; } + + /// + /// Whether the credential may be used in repository . Only a limit of the + /// credential: what the user may do there is still decided by . + /// + public bool AllowsRepository(int repositoryKey) => RepositoryKeys == null || RepositoryKeys.Contains(repositoryKey); + + public string PackageGlobPattern { get; } + + public bool HasScope(string scope) => IsSuperuser || Scopes.Contains(scope, StringComparer.Ordinal); + + public bool MatchesPackage(string? packageId) => IsSuperuser || GlobMatches(PackageGlobPattern, packageId); + + /// + /// Match a package ID against a glob in which "*" stands for any run of characters. + /// Package IDs are case insensitive, so the match is too. + /// + internal static bool GlobMatches(string pattern, string? packageId) + { + if (packageId == null) return false; + + var regex = "^" + Regex.Escape(pattern).Replace("\\*", ".*") + "$"; + + return Regex.IsMatch(packageId, regex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } +} \ No newline at end of file diff --git a/src/BaGet.Core/Authentication/IAuthenticationService.cs b/src/BaGet.Core/Authentication/IAuthenticationService.cs index 3a3a02429..faebf7438 100644 --- a/src/BaGet.Core/Authentication/IAuthenticationService.cs +++ b/src/BaGet.Core/Authentication/IAuthenticationService.cs @@ -1,10 +1,16 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IAuthenticationService { - public interface IAuthenticationService - { - Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken); - } -} + Task AuthenticateAsync(string? apiKey, CancellationToken cancellationToken); + + /// + /// Who the API key authenticated, or null if it did not. An implementation that only + /// knows the global key reports every success as . + /// + async Task AuthenticatePrincipalAsync(string? apiKey, CancellationToken cancellationToken) + => await AuthenticateAsync(apiKey, cancellationToken) ? BaGetPrincipal.Superuser : null; +} \ No newline at end of file diff --git a/src/BaGet.Core/Authentication/IPackageAuthorizationService.cs b/src/BaGet.Core/Authentication/IPackageAuthorizationService.cs new file mode 100644 index 000000000..64e78e6a2 --- /dev/null +++ b/src/BaGet.Core/Authentication/IPackageAuthorizationService.cs @@ -0,0 +1,64 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +public enum PackageAction +{ + /// + /// Push a package or a symbol package. + /// + Push, + + /// + /// Unlist, relist or delete a version (the access model's ). + /// + Manage, + + /// + /// Edit a version's deprecation or vulnerabilities (). Needs ownership and the + /// unlist scope, like . + /// + Annotate, +} + +/// +/// Decides whether an authenticated principal may act on a package ID. +/// +public interface IPackageAuthorizationService +{ + Task AuthorizeAsync( + BaGetPrincipal? principal, + PackageAction action, + string? packageId, + CancellationToken cancellationToken); + + /// + /// Called after a successful push, so that a user pushing a new package ID becomes + /// its owner. + /// + /// The pusher. + /// The pushed ID. + /// + /// The ID had no version before this push, decided by the caller before submitting. Pushing a + /// version of an existing ID never claims it. + /// + /// The cancellation token. + Task OnPushedAsync(BaGetPrincipal principal, string? packageId, bool isNewId, CancellationToken cancellationToken); +} + +/// +/// Without accounts every authenticated caller is the superuser, as it always was. +/// +public class AllowAuthenticatedAuthorizationService : IPackageAuthorizationService +{ + public Task AuthorizeAsync( + BaGetPrincipal? principal, + PackageAction action, + string? packageId, + CancellationToken cancellationToken) + => Task.FromResult(principal != null); + + public Task OnPushedAsync(BaGetPrincipal principal, string? packageId, bool isNewId, CancellationToken cancellationToken) + => Task.CompletedTask; +} \ No newline at end of file diff --git a/src/BaGet.Core/BaGet.Core.csproj b/src/BaGet.Core/BaGet.Core.csproj index e88788429..79d731733 100644 --- a/src/BaGet.Core/BaGet.Core.csproj +++ b/src/BaGet.Core/BaGet.Core.csproj @@ -1,23 +1,44 @@ - netstandard2.0 - + net10.0 + latest NuGet - The core libraries that power BaGet. + The core libraries that power BaGet Extension. + enable + $(NoWarn);NU1510 + + + + + + - + + + + + + + + + + + + + + diff --git a/src/BaGet.Core/BaGetApplication.cs b/src/BaGet.Core/BaGetApplication.cs index 9894b41ad..b03f13c2c 100644 --- a/src/BaGet.Core/BaGetApplication.cs +++ b/src/BaGet.Core/BaGetApplication.cs @@ -1,15 +1,14 @@ using System; using Microsoft.Extensions.DependencyInjection; -namespace BaGet.Core +namespace BaGet.Core; + +public class BaGetApplication { - public class BaGetApplication + public BaGetApplication(IServiceCollection services) { - public BaGetApplication(IServiceCollection services) - { - Services = services ?? throw new ArgumentNullException(nameof(services)); - } - - public IServiceCollection Services { get; } + Services = services ?? throw new ArgumentNullException(nameof(services)); } -} + + public IServiceCollection Services { get; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/AccountsOptions.cs b/src/BaGet.Core/Configuration/AccountsOptions.cs new file mode 100644 index 000000000..b0dc99c23 --- /dev/null +++ b/src/BaGet.Core/Configuration/AccountsOptions.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// User accounts, package owners and per-user API keys. +/// +[RestartRequired] +public class AccountsOptions +{ + /// + /// Off by default, so that an upgraded server behaves exactly as before: only the + /// global authenticates. + /// + /// + /// While this is on, a caller must prove who they are: the global + /// if one is configured, otherwise a user's own key. + /// An unset means there is no global key, not that + /// the server is open - otherwise ownership, which is the point of accounts, could be + /// bypassed by sending no key at all. + /// + public bool Enabled { get; set; } + + /// + /// Whether anyone may create a local account from the sign-in page. + /// + public bool AllowRegistration { get; set; } = true; + + /// + /// Whether an account created by self-service (the registration page, or the first sign-in through the external + /// provider) stays disabled until an administrator approves it on the Users page. Accounts an administrator + /// creates are never pending. Off by default: new accounts sign in at once, as before. + /// + public bool RequireApproval { get; set; } + + /// + /// User names promoted to administrator at startup, separated by semicolons. Applied + /// only while the server has no administrator, and only to accounts that already exist, + /// so it bootstraps the first administrator and nothing more: a listed name registered + /// later is not promoted, and a demotion is not reversed. See also the "account promote" command. + /// + [RestartRequired] + public string? InitialAdministrators { get; set; } + + /// + /// Whether a server with no users at all creates the administrator "Admin" at startup, with a + /// well-known default password ("Admin1234!") to change at the first sign-in (every start warns until it is). Turn it off to bootstrap + /// only through or the "account promote" command. + /// + [RestartRequired] + public bool CreateDefaultAdministrator { get; set; } = true; + + /// + /// How long an access token of an interactive session (POST /api/ui/session, for a single-page application) is accepted. Short on + /// purpose: a client renews it with its refresh token. Not shown on the Settings page (set it in appsettings.json or the environment). + /// + [HiddenSetting] + public TimeSpan SessionTokenLifetime { get; set; } = TimeSpan.FromMinutes(15); + + /// + /// How long a refresh token of an interactive session is accepted after it was issued; every refresh issues a new one, so a client in regular + /// use stays signed in. Changing the password or signing out everywhere ends every session at once. + /// + [HiddenSetting] + public TimeSpan SessionRefreshLifetime { get; set; } = TimeSpan.FromDays(14); + + /// + /// The longest a token session lasts, counted from the sign-in (authenticatedAt), however often it is refreshed: past it the user signs in again. + /// Not shown on the Settings page. + /// + [HiddenSetting] + public TimeSpan SessionMaxLifetime { get; set; } = TimeSpan.FromDays(30); + + /// + /// An external OpenID Connect provider, such as Microsoft Entra ID. Unused unless + /// is set. + /// + public AccountsOpenIdConnectOptions OpenIdConnect { get; set; } = new(); + + /// + /// More OpenID Connect providers, by id (Accounts:OpenIdConnectProviders:<id>, see ). The id is the + /// authentication scheme, the stored login-provider name and part of the callback path /signin-oidc-<id>. Not a row of the Settings page + /// (its "Sign-in providers" panel edits them); restart-required. + /// + [HiddenSetting] + public Dictionary OpenIdConnectProviders { get; set; } = new(StringComparer.OrdinalIgnoreCase); +} + +public class AccountsOpenIdConnectOptions +{ + public string? Authority { get; set; } + + public string? ClientId { get; set; } + + [SensitiveSetting] + public string? ClientSecret { get; set; } + + /// + /// The provider's name on the sign-in button. + /// + public string DisplayName { get; set; } = "OpenID Connect"; + + public bool IsConfigured => !string.IsNullOrEmpty(Authority) && !string.IsNullOrEmpty(ClientId); +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/AvatarModel.cs b/src/BaGet.Core/Configuration/AvatarModel.cs new file mode 100644 index 000000000..47546f5f7 --- /dev/null +++ b/src/BaGet.Core/Configuration/AvatarModel.cs @@ -0,0 +1,7 @@ +namespace BaGet.Core; + +/// +/// What the shared avatar partial renders. A null means no image is to be +/// requested, and the account's initial is shown instead. +/// +public record AvatarModel(string Name, string? Url, int Size); diff --git a/src/BaGet.Core/Configuration/BaGetOptions.cs b/src/BaGet.Core/Configuration/BaGetOptions.cs index efd19ee8d..37e48015f 100644 --- a/src/BaGet.Core/Configuration/BaGetOptions.cs +++ b/src/BaGet.Core/Configuration/BaGetOptions.cs @@ -1,54 +1,104 @@ -using System.ComponentModel.DataAnnotations; +namespace BaGet.Core; -namespace BaGet.Core +public class BaGetOptions { - public class BaGetOptions - { - /// - /// The API Key required to authenticate package - /// operations. If empty, package operations do not require authentication. - /// - public string ApiKey { get; set; } - - /// - /// The application root URL for usage in reverse proxy scenarios. - /// - public string PathBase { get; set; } - - /// - /// If enabled, the database will be updated at app startup by running - /// Entity Framework migrations. This is not recommended in production. - /// - public bool RunMigrationsAtStartup { get; set; } = true; - - /// - /// How BaGet should interpret package deletion requests. - /// - public PackageDeletionBehavior PackageDeletionBehavior { get; set; } = PackageDeletionBehavior.Unlist; - - /// - /// If enabled, pushing a package that already exists will replace the - /// existing package. - /// - public bool AllowPackageOverwrites { get; set; } = false; - - /// - /// If true, disables package pushing, deleting, and re-listing. - /// - public bool IsReadOnlyMode { get; set; } = false; - - /// - /// The URLs the BaGet server will use. - /// As per documentation here (Server URLs). - /// - public string Urls { get; set; } - - public DatabaseOptions Database { get; set; } - - public StorageOptions Storage { get; set; } - - public SearchOptions Search { get; set; } - - public MirrorOptions Mirror { get; set; } - } -} + /// + /// The API Key required to authenticate package + /// operations. If empty, package operations do not require authentication. + /// + [SensitiveSetting] + public string? ApiKey { get; set; } + + /// + /// The application root URL for usage in reverse proxy scenarios. + /// + [RestartRequired] + public string? PathBase { get; set; } + + /// + /// The host names BaGet will serve, separated by semicolons. A request whose + /// "Host" header matches none of them is rejected with a 400 response, before it + /// reaches a handler. An entry may be a wildcard subdomain ("*.example.com") and + /// may carry a port, in which case the port must match too; an entry without a + /// port matches any port. + /// + /// If empty, or if any entry is "*", every host is allowed. That is the default: + /// BaGet is commonly run behind a reverse proxy on a host name it cannot know. + /// + /// This is ASP.NET Core's own "AllowedHosts" configuration key, so an existing + /// value keeps working unchanged. + /// See: https://learn.microsoft.com/aspnet/core/fundamentals/servers/kestrel/host-filtering + /// + [RestartRequired] + public string? AllowedHosts { get; set; } + + /// + /// If enabled, the database will be updated at app startup by running + /// Entity Framework migrations. This is not recommended in production. + /// + [RestartRequired] + public bool RunMigrationsAtStartup { get; set; } = true; + + /// + /// How BaGet should interpret package deletion requests. + /// + public PackageDeletionBehavior PackageDeletionBehavior { get; set; } = PackageDeletionBehavior.Unlist; + + /// + /// If enabled, pushing a package that already exists will replace the + /// existing package. + /// + public bool AllowPackageOverwrites { get; set; } = false; + + /// + /// If true, disables package pushing, deleting, and re-listing. + /// + public bool IsReadOnlyMode { get; set; } = false; + + /// + /// The URLs the BaGet server will use. + /// As per documentation here (Server URLs). + /// + [RestartRequired] + public string? Urls { get; set; } + + public DatabaseOptions? Database { get; set; } + + public StorageOptions? Storage { get; set; } + + public SearchOptions? Search { get; set; } + + public MirrorOptions? Mirror { get; set; } + + public RemoteOptions? Remote { get; set; } + + public NpmOptions? Npm { get; set; } + + public MavenOptions? Maven { get; set; } + + public OciOptions? Oci { get; set; } + + public ScanningOptions? Scanning { get; set; } + + public FeedsOptions? Feeds { get; set; } + + public AccountsOptions? Accounts { get; set; } + + public EmailOptions? Email { get; set; } + + public SiteOptions? Site { get; set; } + + public ValidationOptions? Validation { get; set; } + + public TelemetryOptions? Telemetry { get; set; } + + public HaOptions? Ha { get; set; } + + public ProxyOptions? Proxy { get; set; } + + public CorsSettings? Cors { get; set; } + + public FrontendOptions? Frontend { get; set; } + + public DataProtectionKeyOptions? DataProtection { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/BindOptions.cs b/src/BaGet.Core/Configuration/BindOptions.cs index ca6fd47a1..9c8d6fbdc 100644 --- a/src/BaGet.Core/Configuration/BindOptions.cs +++ b/src/BaGet.Core/Configuration/BindOptions.cs @@ -2,25 +2,24 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Automatically binds configs to options. +/// +/// The options to bind to. +public class BindOptions : IConfigureOptions where TOptions : class { + private readonly IConfiguration _config; + /// - /// Automatically binds configs to options. + /// Automatically bind these configurations to the options. /// - /// The options to bind to. - public class BindOptions : IConfigureOptions where TOptions : class + /// The configs to automatically bind to options. + public BindOptions(IConfiguration config) { - private readonly IConfiguration _config; - - /// - /// Automatically bind these configurations to the options. - /// - /// The configs to automatically bind to options. - public BindOptions(IConfiguration config) - { - _config = config ?? throw new ArgumentNullException(nameof(config)); - } - - public void Configure(TOptions options) => _config.Bind(options); + _config = config ?? throw new ArgumentNullException(nameof(config)); } -} + + public void Configure(TOptions options) => _config.Bind(options); +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/CorsSettings.cs b/src/BaGet.Core/Configuration/CorsSettings.cs new file mode 100644 index 000000000..11e949b89 --- /dev/null +++ b/src/BaGet.Core/Configuration/CorsSettings.cs @@ -0,0 +1,16 @@ +namespace BaGet.Core; + +/// +/// Which web origins may call BaGet's APIs from a browser (Cors:*), read by the host at startup. +/// +[RestartRequired] +public class CorsSettings +{ + /// + /// The origins (https://app.example.com) allowed to call BaGet from a browser, separated by semicolons. Empty (the default) allows + /// any origin, without credentials: the APIs authenticate with headers a page must set itself, so no ambient credential can be ridden. + /// With a list, only those origins are allowed and they may send credentials; the same list decides where the external sign-in of a + /// single-page application may return tokens to. + /// + public string? AllowedOrigins { get; set; } +} diff --git a/src/BaGet.Core/Configuration/DataProtectionKeyOptions.cs b/src/BaGet.Core/Configuration/DataProtectionKeyOptions.cs new file mode 100644 index 000000000..25fa182e9 --- /dev/null +++ b/src/BaGet.Core/Configuration/DataProtectionKeyOptions.cs @@ -0,0 +1,17 @@ +namespace BaGet.Core; + +/// +/// Where the data protection key ring is kept (DataProtection:*). The ring encrypts remote repository passwords, +/// replication peer keys, sessions, antiforgery tokens, registry tokens and reset or confirmation links, so it must +/// outlive the process. Ignored when Ha:Enabled (the ring is then in the database). +/// +[RestartRequired] +public class DataProtectionKeyOptions +{ + /// + /// The folder that holds the key ring. Default: DataProtection-Keys next to the settings overrides file + /// (so inside the mounted volume when SettingsOverridesPath is). A relative path starts at the content root + /// (or BAGET_CONFIG_ROOT). The keys are plain XML files: protect the folder like the database. + /// + public string? KeyPath { get; set; } +} diff --git a/src/BaGet.Core/Configuration/DatabaseOptions.cs b/src/BaGet.Core/Configuration/DatabaseOptions.cs index 0b95a7103..74fbaefe9 100644 --- a/src/BaGet.Core/Configuration/DatabaseOptions.cs +++ b/src/BaGet.Core/Configuration/DatabaseOptions.cs @@ -1,12 +1,38 @@ using System.ComponentModel.DataAnnotations; -namespace BaGet.Core +namespace BaGet.Core; + +[RestartRequired] +public class DatabaseOptions { - public class DatabaseOptions - { - public string Type { get; set; } - - [Required] - public string ConnectionString { get; set; } - } -} + /// + /// The database engine. + /// + [AllowedSettingValues("AzureTable", "MySql", "PostgreSql", "Sqlite", "SqlServer")] + public string? Type { get; set; } + + /// + /// The connection string of the chosen database engine; for AzureTable, the Azure storage account's + /// connection string. With MySql, also set Database:MySqlServerVersion to avoid detecting it by connecting. + /// + [Required] + [SensitiveSetting] + [SettingExample(nameof(Type), "Sqlite", "Data Source=baget.db")] + [SettingExample(nameof(Type), "SqlServer", "Server=localhost;Database=BaGet;Trusted_Connection=True;TrustServerCertificate=True")] + [SettingExample(nameof(Type), "PostgreSql", "Host=localhost;Port=5432;Database=baget;Username=baget;Password=")] + [SettingExample(nameof(Type), "MySql", "Server=localhost;Port=3306;Database=baget;User=baget;Password=")] + [SettingExample(nameof(Type), "AzureTable", "DefaultEndpointsProtocol=https;AccountName=;AccountKey=;EndpointSuffix=core.windows.net")] + public string? ConnectionString { get; set; } + + /// + /// The MySQL server version, such as "8.0.0-mysql" or "10.11.0-mariadb". Optional. + /// + /// + /// When this is not set, the version is detected by connecting to the server. Detection + /// happens while the database options are being built, which also happens when the + /// Entity Framework design-time tools enumerate the contexts, so an unreachable server + /// makes commands such as "dotnet ef migrations add" fail even for another provider. + /// Set this to keep option building offline. + /// + public string? MySqlServerVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/EmailOptions.cs b/src/BaGet.Core/Configuration/EmailOptions.cs new file mode 100644 index 000000000..f85b68e2e --- /dev/null +++ b/src/BaGet.Core/Configuration/EmailOptions.cs @@ -0,0 +1,43 @@ +namespace BaGet.Core; + +/// +/// Outgoing email. Optional: while is false, every feature +/// that needs email (password recovery, email confirmation) is switched off rather +/// than left half working, and an administrator recovers an account from the command line. +/// +[RestartRequired] +public class EmailOptions +{ + public SmtpOptions Smtp { get; set; } = new(); + + /// + /// Set at startup when SMTP is configured but links in emails cannot be trusted (no + /// "Site:PublicUrl" and unrestricted "AllowedHosts"): email is then treated as not configured. + /// + [HiddenSetting] + public bool Suppressed { get; set; } + + public bool IsConfigured => !Suppressed && !string.IsNullOrEmpty(Smtp?.Host) && !string.IsNullOrEmpty(Smtp?.From); +} + +public class SmtpOptions +{ + public string? Host { get; set; } + + public int Port { get; set; } = 587; + + public string? UserName { get; set; } + + [SensitiveSetting] + public string? Password { get; set; } + + /// + /// Use TLS: implicit on port 465, STARTTLS otherwise. + /// + public bool EnableSsl { get; set; } = true; + + /// + /// The sender's address, optionally with a display name: "BaGet <baget@example.com>". + /// + public string? From { get; set; } +} diff --git a/src/BaGet.Core/Configuration/FeedsOptions.cs b/src/BaGet.Core/Configuration/FeedsOptions.cs new file mode 100644 index 000000000..2f59fdd7b --- /dev/null +++ b/src/BaGet.Core/Configuration/FeedsOptions.cs @@ -0,0 +1,16 @@ +namespace BaGet.Core; + +/// +/// Which protocol surfaces BaGet exposes. +/// +public class FeedsOptions +{ + /// + /// Whether the NuGet V2 (OData) feed is served under "api/v2". + /// + /// + /// On by default: clients that cannot speak V3 - "nuget list", older + /// Install-Package, and PowerShellGet - have no other way in. + /// + public bool EnableV2 { get; set; } = true; +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs b/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs index a74dba3dd..a5298836d 100644 --- a/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs +++ b/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs @@ -3,26 +3,26 @@ using System.IO; using System.Linq; -namespace BaGet.Core +namespace BaGet.Core; + +[RestartRequired] +public class FileSystemStorageOptions : IValidatableObject { - public class FileSystemStorageOptions : IValidatableObject - { - /// - /// The path at which content will be stored. Defaults to the same path - /// as the main BaGet executable. This path will be created if it does not - /// exist at startup. Packages will be stored in a subfolder named "packages". - /// - public string Path { get; set; } + /// + /// The path at which content will be stored. Defaults to the same path + /// as the main BaGet executable. This path will be created if it does not + /// exist at startup. Packages will be stored in a subfolder named "packages". + /// + public string? Path { get; set; } - public IEnumerable Validate(ValidationContext validationContext) + public IEnumerable Validate(ValidationContext validationContext) + { + // Convert an empty storage path to the current working directory. + if (string.IsNullOrEmpty(Path)) { - // Convert an empty storage path to the current working directory. - if (string.IsNullOrEmpty(Path)) - { - Path = Directory.GetCurrentDirectory(); - } - - return Enumerable.Empty(); + Path = Directory.GetCurrentDirectory(); } + + return Enumerable.Empty(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/FrontendOptions.cs b/src/BaGet.Core/Configuration/FrontendOptions.cs new file mode 100644 index 000000000..3e0524d41 --- /dev/null +++ b/src/BaGet.Core/Configuration/FrontendOptions.cs @@ -0,0 +1,65 @@ +namespace BaGet.Core; + +/// +/// The web front ends the host serves (Frontend:*), read by the host at startup. +/// +[RestartRequired] +public class FrontendOptions +{ + /// + /// A folder holding a built single-page application (it contains index.html) that BaGet serves under . Empty + /// (the default) serves none. Relative paths are resolved against the content root. + /// + public string? SpaPath { get; set; } + + /// + /// The URL path the single-page application is served under, /app by default. A GET below it that matches no file answers + /// index.html, so the application's own router works; it never shadows /api, the protocols or the MVC screens. + /// + public string SpaBasePath { get; set; } = "/app"; + + /// + /// Whether the server-rendered MVC screens are served. On by default; off, the host serves the APIs only (and the single-page application, if any). + /// + public bool Mvc { get; set; } = true; + + /// + /// Whether the links in account emails (confirm email, reset password) point at the single-page application under + /// instead of the server-rendered screens: {SpaBasePath}/confirm-email?userId=&code=[&email=], {SpaBasePath}/reset-password?userId=&code=, + /// {SpaBasePath}/sign-in (the same query values as the screens' links). Unset (the default) follows : on when the screens are off. + /// + public bool? SpaLinks { get; set; } + + /// + /// The absolute address of a single-page application hosted elsewhere (https://app.example.com, or with a path): account emails then link to + /// {SpaUrl}/confirm-email, {SpaUrl}/reset-password and the cookie's login path is {SpaUrl}/sign-in. Takes precedence over . + /// + public string? SpaUrl { get; set; } + + /// as a path with a leading slash and none at the end (/ for the root). + public string NormalizedBasePath() + { + var trimmed = (SpaBasePath ?? string.Empty).Trim().TrimEnd('/'); + + return trimmed.Length == 0 ? "/" : trimmed.StartsWith('/') ? trimmed : "/" + trimmed; + } + + /// The base path of the application's email-link routes, or null when emails link to the server-rendered screens. + public string? EmailLinkBase + { + get + { + // An application hosted elsewhere, by its absolute address. + if (!string.IsNullOrWhiteSpace(SpaUrl)) return SpaUrl.Trim().TrimEnd('/'); + + // The one BaGet serves (Frontend:SpaPath), or, on the operator's word (SpaLinks=true), one a reverse proxy serves under the base path. With the screens off and + // neither, nothing is served at the base path: a link there would be a 404, so there is no base (startup refuses to mail then). + if (SpaLinks == true || (SpaLinks ?? !Mvc) && !string.IsNullOrWhiteSpace(SpaPath)) return NormalizedBasePath().TrimEnd('/'); + + return null; + } + } + + /// Whether account emails would link to a page that does not exist: the screens are off and no application is named to link to. + public bool EmailLinksWouldBeDead => !Mvc && EmailLinkBase == null; +} diff --git a/src/BaGet.Core/Configuration/IEmailMessageSender.cs b/src/BaGet.Core/Configuration/IEmailMessageSender.cs new file mode 100644 index 000000000..92194a4ec --- /dev/null +++ b/src/BaGet.Core/Configuration/IEmailMessageSender.cs @@ -0,0 +1,26 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Sends a plain-text message that a user wrote, to one recipient. Unlike Identity's +/// own emails the content is untrusted, so implementations must not let it reach a header. +/// Only usable while . +/// +public interface IEmailMessageSender +{ + /// The one recipient. + /// Where a reply goes, or null. + /// The reply-to's display name, or null. + /// Fixed text chosen by the server. + /// The message. + /// Cancels sending. + Task SendAsync( + string to, + string? replyTo, + string? replyToName, + string subject, + string textBody, + CancellationToken cancellationToken); +} diff --git a/src/BaGet.Core/Configuration/MavenOptions.cs b/src/BaGet.Core/Configuration/MavenOptions.cs new file mode 100644 index 000000000..f6de319a6 --- /dev/null +++ b/src/BaGet.Core/Configuration/MavenOptions.cs @@ -0,0 +1,14 @@ +namespace BaGet.Core; + +/// +/// How Maven repositories behave (Maven:*); read on each request, so a change applies without a restart. +/// +public class MavenOptions +{ + /// + /// The largest single file a deploy may store, in bytes (the request body is spooled to a temporary file while it is + /// hashed, so the limit also bounds the disk used by one request). Default 1 GiB; zero or negative: no limit beyond the + /// web server's own. + /// + public long MaxFileBytes { get; set; } = 1024L * 1024 * 1024; +} diff --git a/src/BaGet.Core/Configuration/MirrorOptions.cs b/src/BaGet.Core/Configuration/MirrorOptions.cs index 09db895d3..040eac0c6 100644 --- a/src/BaGet.Core/Configuration/MirrorOptions.cs +++ b/src/BaGet.Core/Configuration/MirrorOptions.cs @@ -2,40 +2,40 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -namespace BaGet.Core +namespace BaGet.Core; + +[RestartRequired] +public class MirrorOptions : IValidatableObject { - public class MirrorOptions : IValidatableObject - { - /// - /// If true, packages that aren't found locally will be indexed - /// using the upstream source. - /// - public bool Enabled { get; set; } + /// + /// If true, packages that aren't found locally will be indexed + /// using the upstream source. + /// + public bool Enabled { get; set; } - /// - /// The v3 index that will be mirrored. - /// - public Uri PackageSource { get; set; } + /// + /// The v3 index that will be mirrored. + /// + public Uri? PackageSource { get; set; } - /// - /// Whether or not the package source is a v2 package source feed. - /// - public bool Legacy { get; set; } + /// + /// Whether or not the package source is a v2 package source feed. + /// + public bool Legacy { get; set; } - /// - /// The time before a download from the package source times out. - /// - [Range(0, int.MaxValue)] - public int PackageDownloadTimeoutSeconds { get; set; } = 600; + /// + /// The time before a download from the package source times out. + /// + [Range(0, int.MaxValue)] + public int PackageDownloadTimeoutSeconds { get; set; } = 600; - public IEnumerable Validate(ValidationContext validationContext) + public IEnumerable Validate(ValidationContext validationContext) + { + if (Enabled && PackageSource == null) { - if (Enabled && PackageSource == null) - { - yield return new ValidationResult( - $"The {nameof(PackageSource)} configuration is required if mirroring is enabled", - new[] { nameof(PackageSource) }); - } + yield return new ValidationResult( + $"The {nameof(PackageSource)} configuration is required if mirroring is enabled", + new[] { nameof(PackageSource) }); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/NpmOptions.cs b/src/BaGet.Core/Configuration/NpmOptions.cs new file mode 100644 index 000000000..e4a77650f --- /dev/null +++ b/src/BaGet.Core/Configuration/NpmOptions.cs @@ -0,0 +1,23 @@ +using System; + +namespace BaGet.Core; + +/// +/// How npm repositories behave (Npm:*); both settings are read on each request, so a change applies without a restart. +/// +public class NpmOptions +{ + /// + /// How long after a version was published its owner may still unpublish it with Deploy alone, as npmjs lets an author take + /// back a mistake within 72 hours. Later, unpublishing needs the Delete action (and ownership, and the + /// package:unlist scope of a key). A whole package counts as young only while every version is. Zero or negative: + /// the Delete action is always required. + /// + public TimeSpan UnpublishWindow { get; set; } = TimeSpan.FromHours(72); + + /// + /// The largest npm publish request body accepted, in bytes (the tarball travels inside the JSON as base64, so a + /// tarball is about three quarters of it). Default 512 MiB; zero or negative: no limit beyond the web server's own. + /// + public long MaxPublishBytes { get; set; } = 512L * 1024 * 1024; +} diff --git a/src/BaGet.Core/Configuration/OciOptions.cs b/src/BaGet.Core/Configuration/OciOptions.cs new file mode 100644 index 000000000..36d58b2ad --- /dev/null +++ b/src/BaGet.Core/Configuration/OciOptions.cs @@ -0,0 +1,36 @@ +using System; + +namespace BaGet.Core; + +/// +/// How Docker / OCI repositories behave (Oci:*); read on each request, so a change applies without a restart. +/// +public class OciOptions +{ + /// + /// How long a token from /v2/token (the docker login flow) stays valid. Short on purpose: a token is checked + /// by its signature and expiry only, so a permission taken away applies when the tokens issued before it have expired. + /// Default 5 minutes, at least 10 seconds. + /// + public TimeSpan TokenLifetime { get; set; } = TimeSpan.FromMinutes(5); + + /// + /// The service the registry names in its WWW-Authenticate challenge and expects back at the token endpoint. + /// Default BaGet. + /// + public string Service { get; set; } = "BaGet"; + + /// The largest manifest or index accepted, in bytes. Default 4 MiB, as the specification recommends. + public int MaxManifestBytes { get; set; } = 4 * 1024 * 1024; + + /// + /// How long an upload session may sit idle before it is discarded (checked whenever a new upload starts). Default 24 hours. + /// + public TimeSpan UploadExpiry { get; set; } = TimeSpan.FromHours(24); + + /// + /// How long a layer that no manifest references stays after it was uploaded before prune may remove it, so a push + /// in progress (layers first, manifest last) is never pruned. Default 1 hour. + /// + public TimeSpan PruneGrace { get; set; } = TimeSpan.FromHours(1); +} diff --git a/src/BaGet.Core/Configuration/OpenIdConnectProvider.cs b/src/BaGet.Core/Configuration/OpenIdConnectProvider.cs new file mode 100644 index 000000000..78529dc11 --- /dev/null +++ b/src/BaGet.Core/Configuration/OpenIdConnectProvider.cs @@ -0,0 +1,20 @@ +namespace BaGet.Core; + +/// +/// An OpenID Connect provider as registered at startup: the legacy Accounts:OpenIdConnect block (id oidc) or a named one. +/// +/// The authentication scheme, the stored login-provider name. +/// The name on the sign-in button. +/// The provider's settings. +/// True for the single Accounts:OpenIdConnect block. +public sealed record OpenIdConnectProvider(string Id, string DisplayName, OpenIdConnectProviderOptions Options, bool IsLegacy) +{ + /// The callback path the authentication handler listens on. + public string CallbackPath => IsLegacy ? "/signin-oidc" : "/signin-oidc-" + Id; + + /// The path the provider redirects to after a sign-out. + public string SignedOutCallbackPath => IsLegacy ? "/signout-callback-oidc" : "/signout-callback-oidc-" + Id; + + /// The path a provider's front-channel sign-out calls. + public string RemoteSignOutPath => IsLegacy ? "/signout-oidc" : "/signout-oidc-" + Id; +} diff --git a/src/BaGet.Core/Configuration/OpenIdConnectProviderOptions.cs b/src/BaGet.Core/Configuration/OpenIdConnectProviderOptions.cs new file mode 100644 index 000000000..d76e62071 --- /dev/null +++ b/src/BaGet.Core/Configuration/OpenIdConnectProviderOptions.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// One named OpenID Connect provider (Accounts:OpenIdConnectProviders:<id>). The id is the authentication scheme, the stored +/// login-provider name and part of the callback path (/signin-oidc-<id>). Providers are registered at startup, so a change needs a restart. +/// +public class OpenIdConnectProviderOptions +{ + /// The provider's issuer address (its discovery document is read from here). + public string? Authority { get; set; } + + /// The client id registered at the provider. + public string? ClientId { get; set; } + + /// The client secret registered at the provider. Never shown back. + [SensitiveSetting] + public string? ClientSecret { get; set; } + + /// The provider's name on the sign-in button. Defaults to the id. + public string? DisplayName { get; set; } + + /// Extra scopes to request, separated by spaces or semicolons (openid profile email are always requested). + public string? Scopes { get; set; } + + /// + /// Extra parameters of the authorization request, such as domain_hint. They never replace a parameter BaGet sets itself (prompt and + /// max_age of a re-authentication, state, nonce, redirect_uri, client_id, scope, response_type ...). + /// + public Dictionary Parameters { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + /// The claim holding the preferred user name (default preferred_username). + public string? UserNameClaim { get; set; } + + /// The claim holding the email address (default email). + public string? EmailClaim { get; set; } + + /// The claim saying the email address is verified (default email_verified); only true confirms the address. + public string? EmailVerifiedClaim { get; set; } + + /// + /// The claim type that decides the administrator flag together with . When both are set the provider is + /// authoritative for the administrator flag of the users who sign in through it: each sign-in promotes when the value is present and demotes + /// when it is absent (never the last administrator). + /// + public string? AdministratorClaim { get; set; } + + /// The value of that makes a user an administrator. + public string? AdministratorValue { get; set; } + + /// The claim holding the user's groups, used with . + public string? GroupClaim { get; set; } + + /// + /// Claim value to BaGet group name. At each sign-in through this provider the user joins the mapped groups whose value is present and leaves the mapped + /// groups whose value is absent; other groups are never touched and an unknown group is skipped, not created. A value holds no :. + /// + public Dictionary GroupMappings { get; set; } = new(StringComparer.Ordinal); + + /// Whether the provider has what it needs to be offered. + public bool IsConfigured => !string.IsNullOrEmpty(Authority) && !string.IsNullOrEmpty(ClientId); +} diff --git a/src/BaGet.Core/Configuration/OpenIdConnectProviderSet.cs b/src/BaGet.Core/Configuration/OpenIdConnectProviderSet.cs new file mode 100644 index 000000000..2e3532bb7 --- /dev/null +++ b/src/BaGet.Core/Configuration/OpenIdConnectProviderSet.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Core; + +/// +/// The providers whose authentication handlers were registered at startup (singleton): what the sign-in screen offers and what the +/// challenge, the callback and the re-authentication accept. Resolved once by . +/// +public sealed class OpenIdConnectProviderSet +{ + /// No provider. + public static OpenIdConnectProviderSet Empty { get; } = new(Array.Empty()); + + /// Creates the set. + public OpenIdConnectProviderSet(IReadOnlyList providers) + => All = providers ?? throw new ArgumentNullException(nameof(providers)); + + /// Every configured provider, the legacy one first, then the named ones by id. + public IReadOnlyList All { get; } + + /// Whether any provider is configured. + public bool Any => All.Count > 0; + + /// The provider with this id (case-insensitive), or null. + public OpenIdConnectProvider? Find(string? id) + => string.IsNullOrEmpty(id) ? null : All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/BaGet.Core/Configuration/OpenIdConnectProviders.cs b/src/BaGet.Core/Configuration/OpenIdConnectProviders.cs new file mode 100644 index 000000000..3e93c85eb --- /dev/null +++ b/src/BaGet.Core/Configuration/OpenIdConnectProviders.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace BaGet.Core; + +/// The rules for the OpenID Connect providers of : resolving, ids and validation. +public static class OpenIdConnectProviders +{ + /// The id of the single Accounts:OpenIdConnect block. + public const string LegacyId = "oidc"; + + /// The configuration key whose children are the named providers. + public const string SectionKey = "Accounts:OpenIdConnectProviders"; + + /// The default claim holding the user name. + public const string DefaultUserNameClaim = "preferred_username"; + + /// The default claim holding the email address. + public const string DefaultEmailClaim = "email"; + + /// The default claim saying the address is verified. + public const string DefaultEmailVerifiedClaim = "email_verified"; + + private static readonly Regex IdPattern = new("^[a-z0-9-]{1,32}$", RegexOptions.CultureInvariant); + + /// Why cannot be a provider id, or null: lower-case letters, digits and -, 1 to 32 characters. + public static string? ValidateId(string? id) + => id != null && IdPattern.IsMatch(id) ? null : "A provider id has 1 to 32 characters: lower-case letters, digits and '-'."; + + /// + /// The configured providers: the legacy block (when it has an authority and a client id) as , then the named ones (ids are + /// read case-insensitively and kept lower-case; one that lacks an authority or a client id is skipped). + /// + /// An invalid or repeated id, oidc beside the legacy block, or inconsistent mappings. + public static OpenIdConnectProviderSet Resolve(AccountsOptions options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); + + var providers = new List(); + var legacy = options.OpenIdConnect; + if (legacy.IsConfigured) + { + providers.Add(new OpenIdConnectProvider( + LegacyId, + legacy.DisplayName, + new OpenIdConnectProviderOptions + { + Authority = legacy.Authority, + ClientId = legacy.ClientId, + ClientSecret = legacy.ClientSecret, + DisplayName = legacy.DisplayName, + }, + IsLegacy: true)); + } + + var seen = new HashSet(StringComparer.Ordinal); + foreach (var pair in (options.OpenIdConnectProviders ?? new()).OrderBy(p => p.Key, StringComparer.OrdinalIgnoreCase)) + { + var id = pair.Key.ToLowerInvariant(); + var problem = ValidateId(id); + if (problem != null) throw new InvalidOperationException($"'{SectionKey}:{pair.Key}': {problem}"); + if (!seen.Add(id)) throw new InvalidOperationException($"'{SectionKey}:{pair.Key}': the provider id '{id}' is used twice (ids ignore case)."); + if (id == LegacyId && legacy.IsConfigured) + { + throw new InvalidOperationException( + $"'{SectionKey}:{pair.Key}': the id '{LegacyId}' belongs to the single 'Accounts:OpenIdConnect' block, which is configured too. Rename the provider or remove the block."); + } + + var value = pair.Value ?? new OpenIdConnectProviderOptions(); + if (!value.IsConfigured) continue; + + var errors = Validate(value); + if (errors.Count > 0) throw new InvalidOperationException($"'{SectionKey}:{pair.Key}': {string.Join(" ", errors)}"); + + providers.Add(new OpenIdConnectProvider(id, string.IsNullOrWhiteSpace(value.DisplayName) ? id : value.DisplayName.Trim(), value, IsLegacy: false)); + } + + return new OpenIdConnectProviderSet(providers); + } + + /// What is wrong with a provider's settings (an empty list when nothing is). + public static IReadOnlyList Validate(OpenIdConnectProviderOptions options) + { + var errors = new List(); + + if (!Uri.TryCreate(options.Authority, UriKind.Absolute, out var authority) || (authority.Scheme != Uri.UriSchemeHttps && authority.Scheme != Uri.UriSchemeHttp)) + { + errors.Add("The authority must be an http(s) address."); + } + + if (string.IsNullOrWhiteSpace(options.ClientId)) errors.Add("The client id is required."); + + var hasAdminClaim = !string.IsNullOrWhiteSpace(options.AdministratorClaim); + if (hasAdminClaim != !string.IsNullOrWhiteSpace(options.AdministratorValue)) + { + errors.Add("The administrator claim and the administrator value go together."); + } + + var mappings = options.GroupMappings ?? new(); + if (mappings.Count > 0 && string.IsNullOrWhiteSpace(options.GroupClaim)) errors.Add("Group mappings need a group claim."); + foreach (var pair in mappings) + { + if (string.IsNullOrWhiteSpace(pair.Key) || pair.Key.Contains(':')) errors.Add($"A group mapping value ('{pair.Key}') is empty or holds ':'."); + if (string.IsNullOrWhiteSpace(pair.Value)) errors.Add($"The group mapping for '{pair.Key}' names no group."); + } + + foreach (var name in (options.Parameters ?? new()).Keys) + { + if (string.IsNullOrWhiteSpace(name) || name.Contains(':')) errors.Add($"A request parameter name ('{name}') is empty or holds ':'."); + } + + return errors; + } + + /// The extra scopes of a provider (split on spaces and semicolons, without duplicates). + public static IReadOnlyList ExtraScopes(OpenIdConnectProviderOptions options) + => (options.Scopes ?? string.Empty).Split(new[] { ' ', ';', ',', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Distinct(StringComparer.Ordinal).ToList(); + + /// The claim holding the user name, or the default. + public static string UserNameClaim(OpenIdConnectProviderOptions options) => OrDefault(options.UserNameClaim, DefaultUserNameClaim); + + /// The claim holding the email address, or the default. + public static string EmailClaim(OpenIdConnectProviderOptions options) => OrDefault(options.EmailClaim, DefaultEmailClaim); + + /// The claim saying the address is verified, or the default. + public static string EmailVerifiedClaim(OpenIdConnectProviderOptions options) => OrDefault(options.EmailVerifiedClaim, DefaultEmailVerifiedClaim); + + private static string OrDefault(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value.Trim(); +} diff --git a/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs b/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs index 01c68d7ff..0f6b45420 100644 --- a/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs +++ b/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs @@ -1,22 +1,21 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// How BaGet should interpret package deletion requests. +/// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package +/// +public enum PackageDeletionBehavior { /// - /// How BaGet should interpret package deletion requests. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package + /// Package "deletions" make the package undiscoverable. The package is still restorable + /// by consumers that know its id and version. This is the recommended behavior as it prevents + /// the "left pad" problem. /// - public enum PackageDeletionBehavior - { - /// - /// Package "deletions" make the package undiscoverable. The package is still restorable - /// by consumers that know its id and version. This is the recommended behavior as it prevents - /// the "left pad" problem. - /// - Unlist, + Unlist, - /// - /// Removes the package from the database and storage. Existing consumers will no longer - /// be able to restore the package. - /// - HardDelete, - } -} + /// + /// Removes the package from the database and storage. Existing consumers will no longer + /// be able to restore the package. + /// + HardDelete, +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/ProxyOptions.cs b/src/BaGet.Core/Configuration/ProxyOptions.cs new file mode 100644 index 000000000..af7766954 --- /dev/null +++ b/src/BaGet.Core/Configuration/ProxyOptions.cs @@ -0,0 +1,23 @@ +namespace BaGet.Core; + +/// +/// Which reverse proxies BaGet believes when they send X-Forwarded-For and X-Forwarded-Proto (Proxy:*). +/// By default only loopback proxies are trusted (the framework default), so a client that reaches BaGet directly cannot +/// spoof its address or the scheme. Behind a proxy on another address, list it; restores the +/// older "believe every sender" behaviour and must be an explicit choice. +/// +[RestartRequired] +public class ProxyOptions +{ + /// Addresses of trusted proxies, separated by semicolons (10.0.0.5;fd00::1), added to the loopback ones. + public string? TrustedProxies { get; set; } + + /// Trusted proxy networks in CIDR form, separated by semicolons (10.0.0.0/8;172.16.0.0/12). + public string? TrustedNetworks { get; set; } + + /// + /// Believe the forwarded headers of every sender. Only safe when BaGet is reachable through the proxy alone (no direct + /// route from clients): otherwise any client can forge its address (defeating the rate limits) and the scheme. + /// + public bool TrustAnyProxy { get; set; } +} diff --git a/src/BaGet.Core/Configuration/RemoteOptions.cs b/src/BaGet.Core/Configuration/RemoteOptions.cs new file mode 100644 index 000000000..cf4973fb8 --- /dev/null +++ b/src/BaGet.Core/Configuration/RemoteOptions.cs @@ -0,0 +1,18 @@ +namespace BaGet.Core; + +/// +/// How remote repositories may reach their upstreams (Remote:*). +/// +public class RemoteOptions +{ + /// + /// Whether an upstream may not be a loopback, private (RFC 1918, unique-local), link-local (including the cloud + /// metadata address 169.254.169.254), carrier-grade NAT or other non-public address. Off by default because an + /// internal feed is the normal use of a remote repository; turn it on when the administrators who may create + /// remote repositories are less trusted than the host, since otherwise an upstream URL (and Test connection) + /// reaches whatever this server can reach. Checked when a repository is created or saved, when Test connection runs, + /// and on every connection a V3 upstream client opens (so also after a DNS change or a redirect). A V2 upstream + /// is contacted by NuGet's own HTTP stack and only the address in the URL is checked. + /// + public bool BlockPrivateAddresses { get; set; } +} diff --git a/src/BaGet.Core/Configuration/ScanningOptions.cs b/src/BaGet.Core/Configuration/ScanningOptions.cs new file mode 100644 index 000000000..ae634aa77 --- /dev/null +++ b/src/BaGet.Core/Configuration/ScanningOptions.cs @@ -0,0 +1,84 @@ +using System; + +namespace BaGet.Core; + +/// +/// Vulnerability scanning (Scanning:*; user docs docs/vulnerability-scanning.md). NuGet, npm and Maven artifacts are +/// checked against OSV.dev (online API, or an offline copy of its data); Docker images by an optional Trivy. Everything is read +/// on each use, so a change applies without a restart. Off by default: scanning contacts the internet. +/// +public class ScanningOptions +{ + /// + /// Whether artifacts are scanned (on deploy, on the schedule and by Scan now). Off: nothing is scanned, no + /// policy blocks anything and the UI says so. + /// + public bool Enabled { get; set; } + + /// + /// Whether a version is queued for a scan as soon as it is stored (published, deployed, pushed, or cached by a remote + /// repository). Default on. Off: versions are scanned by the schedule and by Scan now only (a download that finds a + /// version unscanned under a policy still queues it). + /// + public bool ScanOnDeploy { get; set; } = true; + + /// + /// The OSV API root. Default https://api.osv.dev. Data served by OSV.dev is licensed per source (mostly CC-BY 4.0, + /// GitHub Advisory Database CC-BY 4.0); advisories shown in the UI carry their identifier and a link to the source. + /// + public string OsvUrl { get; set; } = "https://api.osv.dev"; + + /// + /// A directory (searched recursively for *.json) or a .zip of OSV records, e.g. the per-ecosystem + /// all.zip from https://osv-vulnerabilities.storage.googleapis.com/<ecosystem>/all.zip. When set the + /// scanner uses it instead of the online API and never contacts the internet. Reloaded when the file or directory changes. + /// + public string? OsvOfflinePath { get; set; } + + /// Timeout of one OSV request. Default 30 seconds. + public TimeSpan OsvTimeout { get; set; } = TimeSpan.FromSeconds(30); + + /// How long an OSV answer for a component is reused before it is asked again. Default 1 hour. + public TimeSpan OsvCacheLifetime { get; set; } = TimeSpan.FromHours(1); + + /// + /// The age after which the background worker scans an artifact again, to learn of advisories published after the first scan. + /// Zero or negative: artifacts are scanned on deploy and on demand only. Default 24 hours. + /// + public TimeSpan RescanInterval { get; set; } = TimeSpan.FromHours(24); + + /// + /// The path of the trivy executable used for Docker images. Without it Docker images are not scanned and the UI marks + /// them as unscanned. + /// + public string? TrivyPath { get; set; } + + /// + /// A Trivy server (trivy server), passed as --server so the vulnerability database and the analysis live + /// there; the executable in is still what is run. + /// + public string? TrivyServerUrl { get; set; } + + /// + /// The registry host (and port) Trivy pulls images from: this server as the Docker client sees it, e.g. + /// registry.example.com. Required for Docker scanning; images are named {host}/{repository}/{image}@{digest}. + /// + public string? TrivyRegistryHost { get; set; } + + /// Pull over plain HTTP (--insecure), for a registry without TLS. + public bool TrivyInsecure { get; set; } + + /// + /// The user name Trivy logs in with when the registry needs credentials (accounts enabled). Also what identifies the scanner's own + /// pull to the scan gate: without it the pull is recognised from the scans running in this process only, so a deployment with several + /// nodes must set it. + /// + public string? TrivyRegistryUser { get; set; } + + /// The API key Trivy logs in with (passed through the environment, never on the command line). + [SensitiveSetting] + public string? TrivyRegistryPassword { get; set; } + + /// The longest a Trivy run may take. Default 10 minutes. + public TimeSpan TrivyTimeout { get; set; } = TimeSpan.FromMinutes(10); +} diff --git a/src/BaGet.Core/Configuration/SearchOptions.cs b/src/BaGet.Core/Configuration/SearchOptions.cs index 52f430cb8..136ece3bb 100644 --- a/src/BaGet.Core/Configuration/SearchOptions.cs +++ b/src/BaGet.Core/Configuration/SearchOptions.cs @@ -1,7 +1,11 @@ -namespace BaGet.Core +namespace BaGet.Core; + +[RestartRequired] +public class SearchOptions { - public class SearchOptions - { - public string Type { get; set; } - } -} + /// + /// The search backend. + /// + [AllowedSettingValues("AzureSearch", "Database", "Null")] + public string? Type { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/SerilogOptions.cs b/src/BaGet.Core/Configuration/SerilogOptions.cs new file mode 100644 index 000000000..3fb4dc48c --- /dev/null +++ b/src/BaGet.Core/Configuration/SerilogOptions.cs @@ -0,0 +1,41 @@ +namespace BaGet.Core; + +/// +/// The operator-facing keys of the host's Serilog section (see "Logging" in docs/configuration.md), so the +/// Settings page can edit them. The section holds more: the Override levels per namespace are edited by +/// the page's "Log levels per source" panel (), while the +/// WriteTo sinks and their arguments are arrays the Settings page cannot show, so they stay in the +/// configuration file or the environment. The host reads the levels through Serilog's own configuration reload, which +/// is why applies without a restart and the event log keys do not. +/// +public class SerilogOptions +{ + /// The lowest level logged. + public MinimumLevelOptions MinimumLevel { get; set; } = new(); + + /// The Windows Application event log sink (Windows only). + public EventLogOptions EventLog { get; set; } = new(); +} + +/// The level keys of the Serilog:MinimumLevel section. +public class MinimumLevelOptions +{ + /// + /// The lowest level logged for sources without an Override: Verbose, Debug, Information, Warning, Error or + /// Fatal. Applies live. Leave empty for the host's built-in levels (Information; Microsoft and the request + /// diagnostics at Warning). + /// + [AllowedSettingValues("Verbose", "Debug", "Information", "Warning", "Error", "Fatal")] + public string? Default { get; set; } +} + +/// The keys of the Serilog:EventLog section. +[RestartRequired] +public class EventLogOptions +{ + /// Write Warning and up to the Windows Application event log. Windows only; off elsewhere whatever this says. + public bool Enabled { get; set; } = true; + + /// The event source, which must already be registered; empty uses ".NET Runtime", which exists on every Windows. + public string? Source { get; set; } +} diff --git a/src/BaGet.Core/Configuration/Settings/LogLevelOverrides.cs b/src/BaGet.Core/Configuration/Settings/LogLevelOverrides.cs new file mode 100644 index 000000000..c8efc5899 --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/LogLevelOverrides.cs @@ -0,0 +1,53 @@ +using System; +using System.Linq; + +namespace BaGet.Core; + +/// +/// One Serilog:MinimumLevel:Override:{Source} entry: the lowest level logged for a source (a namespace or type +/// name prefix such as Microsoft.AspNetCore). +/// +/// The namespace or type name prefix. +/// Verbose, Debug, Information, Warning, Error or Fatal. +/// True when the Settings overrides file holds it, so it can be removed from here; false when only a configuration file or the environment sets it. +public sealed record LogLevelOverride(string Source, string Level, bool InOverridesFile); + +/// +/// The rules for a per-source log level, shared by the Settings page and (the one place that validates them). +/// +public static class LogLevelOverrides +{ + /// The configuration key whose children are the overrides. + public const string SectionKey = "Serilog:MinimumLevel:Override"; + + /// The longest source name accepted. + public const int MaxSourceLength = 200; + + /// The level names Serilog reads, in order of severity. + public static readonly string[] Levels = { "Verbose", "Debug", "Information", "Warning", "Error", "Fatal" }; + + /// The configuration key of . + public static string KeyOf(string source) => SectionKey + ":" + source; + + /// + /// The canonical spelling of (case-insensitive), or null when it is not a Serilog level. + /// + public static string? NormalizeLevel(string? level) + => Levels.FirstOrDefault(l => string.Equals(l, level?.Trim(), StringComparison.OrdinalIgnoreCase)); + + /// + /// Why cannot name a source, or null. Letters, digits, ., _, -, + /// ` and + only: no : (the configuration separator), no spaces. + /// + public static string? ValidateSource(string? source) + { + if (string.IsNullOrWhiteSpace(source)) return "Name the source: a namespace or type name prefix such as Microsoft.AspNetCore."; + if (source.Length > MaxSourceLength) return $"The source is longer than {MaxSourceLength} characters."; + if (source.Any(c => !(char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-' or '`' or '+'))) + { + return "A source holds letters, digits and . _ - ` + only."; + } + + return null; + } +} diff --git a/src/BaGet.Core/Configuration/Settings/SettingPresentation.cs b/src/BaGet.Core/Configuration/Settings/SettingPresentation.cs new file mode 100644 index 000000000..c03537e7d --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/SettingPresentation.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace BaGet.Core; + +/// +/// One entry of a drop-down setting. +/// +/// The value posted back. +/// The text shown. +/// The entry is the current value. +public sealed record SettingChoice(string Value, string Label, bool Selected); + +/// +/// What the Settings page shows for a setting beyond its raw value: drop-down entries and +/// examples. Kept out of the Razor view so that it is unit tested. +/// +public static class SettingPresentation +{ + /// The mask shown in place of a stored secret. + public const string Mask = "••••"; + + /// + /// The entries of a drop-down: the allowed names, with the one equal to + /// (case-insensitive) selected. A current value that is empty or not + /// in the list is added, selected and labelled, so that saving the section never changes it. + /// + public static IReadOnlyList Choices(SettingDescriptor descriptor, string? current) + { + if (descriptor == null) throw new ArgumentNullException(nameof(descriptor)); + + var list = new List(); + var matched = false; + foreach (var value in descriptor.EnumValues) + { + var selected = !matched && string.Equals(value, current, StringComparison.OrdinalIgnoreCase); + matched |= selected; + list.Add(new SettingChoice(value, value, selected)); + } + + if (!matched) + { + var text = current ?? string.Empty; + list.Add(new SettingChoice(text, text.Length == 0 ? "(not set)" : text + " (current, not in the list)", true)); + } + + return list; + } + + /// + /// The example of for (case-insensitive), or null. + /// + public static string? ExampleFor(SettingDescriptor descriptor, string? dependsValue) + { + if (descriptor == null) throw new ArgumentNullException(nameof(descriptor)); + if (descriptor.Examples == null || dependsValue == null) return null; + + foreach (var pair in descriptor.Examples) + { + if (string.Equals(pair.Key, dependsValue, StringComparison.OrdinalIgnoreCase)) return pair.Value; + } + + return null; + } + + /// + /// The current value of the setting that selects 's example, read from the + /// settings of the same form, or null. + /// + public static string? DependsValue(SettingDescriptor descriptor, IEnumerable siblings) + { + if (descriptor == null) throw new ArgumentNullException(nameof(descriptor)); + if (descriptor.ExampleDependsOnKey == null || siblings == null) return null; + + foreach (var sibling in siblings) + { + if (string.Equals(sibling.Descriptor.Key, descriptor.ExampleDependsOnKey, StringComparison.OrdinalIgnoreCase)) + { + return sibling.EffectiveValue; + } + } + + return null; + } + + /// + /// The placeholder of a sensitive text input: "•••• unchanged" when a value is stored, otherwise the example + /// ("e.g. ...") when there is one, otherwise "not set". The example is never the input's value. + /// + public static string Placeholder(SettingState state, string? dependsValue) + { + if (state == null) throw new ArgumentNullException(nameof(state)); + if (state.HasValue) return Mask + " unchanged"; + + var example = ExampleFor(state.Descriptor, dependsValue); + return example == null ? "not set" : "e.g. " + example; + } + + /// + /// The value of the data-examples attribute: a JSON object of the examples keyed by the + /// lower-cased dependsOn value (any characters, so no value can collide with another data attribute). + /// The page script lower-cases the selected value to look it up. Encode it as an attribute value. + /// + public static string ExamplesJson(IReadOnlyDictionary examples) + { + if (examples == null) throw new ArgumentNullException(nameof(examples)); + + var map = new Dictionary(StringComparer.Ordinal); + foreach (var pair in examples) map[(pair.Key ?? string.Empty).ToLowerInvariant()] = pair.Value; + + return JsonSerializer.Serialize(map); + } +} diff --git a/src/BaGet.Core/Configuration/Settings/SettingsAttributes.cs b/src/BaGet.Core/Configuration/Settings/SettingsAttributes.cs new file mode 100644 index 000000000..3a9428337 --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/SettingsAttributes.cs @@ -0,0 +1,105 @@ +using System; +using System.Reflection; + +namespace BaGet.Core; + +/// +/// Marks a setting whose value is a credential: the Settings page shows it masked, never +/// echoes it back, and the service never logs it. +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class SensitiveSettingAttribute : Attribute +{ +} + +/// +/// Marks a setting, or every setting of an options type, that is read once at startup +/// (at registration, in the pipeline setup, or through the singleton +/// IOptions<T>), so a change takes effect after a restart. A setting without it +/// is read through IOptionsSnapshot<T> and applies to the next request. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] +public sealed class RestartRequiredAttribute : Attribute +{ +} + +/// +/// Keeps a public settable property out of the Settings page: it is internal state that +/// the application sets itself, not something an operator configures. +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class HiddenSettingAttribute : Attribute +{ +} + +/// +/// Restricts a string setting to a fixed set of names. The Settings page shows it as a +/// drop-down (matching the current value case-insensitively), the form refuses any other +/// value, and startup validation reads the same , so the list lives in +/// one place. Comparison is case-insensitive. +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class AllowedSettingValuesAttribute : Attribute +{ + /// + /// Creates the attribute. + /// + /// The allowed names, in display order. + public AllowedSettingValuesAttribute(params string[] values) + { + Values = values ?? throw new ArgumentNullException(nameof(values)); + } + + /// The allowed names, in display order. + public string[] Values { get; } + + /// + /// The allowed names declared on a property. + /// + /// The options type. + /// The property name, such as nameof(DatabaseOptions.Type). + public static string[] ValuesOf(string property) + => typeof(TOptions).GetProperty(property)?.GetCustomAttribute()?.Values + ?? Array.Empty(); +} + +/// +/// Gives a setting an example value that depends on another setting of the same options +/// type, such as a connection string per database type. The Settings page shows it as a +/// placeholder and a help line, and updates both when the other setting's drop-down changes. +/// The example is never written into the field's value. Repeat the attribute once per value; every one on a property must depend on the same property and name each value once, or the catalog throws . +/// +[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] +public sealed class SettingExampleAttribute : Attribute +{ + /// + /// Creates the attribute. + /// + /// The name of the property of the same type that selects the example. + /// The value of that property (case-insensitive) this example is for. + /// The example value. + public SettingExampleAttribute(string dependsOn, string whenValue, string example) + { + DependsOn = dependsOn ?? throw new ArgumentNullException(nameof(dependsOn)); + WhenValue = whenValue ?? throw new ArgumentNullException(nameof(whenValue)); + Example = example ?? throw new ArgumentNullException(nameof(example)); + } + + /// The property that selects the example. + public string DependsOn { get; } + + /// The value of this example is for. + public string WhenValue { get; } + + /// The example value. + public string Example { get; } +} + +/// +/// An options type bound to a configuration section. Recorded by +/// so that the +/// lists every options type, provider-specific ones included. +/// +/// The options type. +/// The configuration section it is bound to, or null for the root. +public sealed record SettingsSchemaRegistration(Type OptionsType, string? Section); diff --git a/src/BaGet.Core/Configuration/Settings/SettingsCatalog.cs b/src/BaGet.Core/Configuration/Settings/SettingsCatalog.cs new file mode 100644 index 000000000..c46e2639b --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/SettingsCatalog.cs @@ -0,0 +1,330 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.Json.Serialization; + +namespace BaGet.Core; + +/// +/// The editable type of a setting. +/// +public enum SettingKind +{ + /// A true or false value. + Boolean, + + /// A whole number. + Integer, + + /// A number with a fraction. + Number, + + /// Free text. + String, + + /// + /// One of a fixed set of names, see : an enum, or a + /// string property carrying . + /// + Enum, + + /// A duration such as "00:10:00". + TimeSpan, + + /// A list of text entries. + StringList, + + /// Shown but not editable here (a dictionary or other unsupported type). + ReadOnly, +} + +/// +/// One configuration key the Settings page can show. +/// +/// The full key, such as "Email:Smtp:Host". +/// The first segment of the key, or an empty string for a top-level key. +/// The options type's name without "Options", such as "AzureBlobStorage". +/// How the value is edited. +/// The property's type, without (not serialised: a has no JSON form). +/// The allowed names of an , otherwise empty. +/// The value is a credential: masked and write-only. +/// A change applies after a restart. +/// The property's XML documentation summary, or an empty string. +/// +/// The full key of the setting that selects (see +/// ), or null. +/// +/// +/// Example values by the value of (case-insensitive), or null. +/// +public sealed record SettingDescriptor( + string Key, + string Section, + string Group, + SettingKind Kind, + [property: JsonIgnore] Type ClrType, + string[] EnumValues, + bool IsSensitive, + bool RequiresRestart, + string Description, + string? ExampleDependsOnKey = null, + IReadOnlyDictionary? Examples = null); + +/// +/// Every setting of every registered options type, found by reflection over the types +/// recorded as . +/// +public class SettingsCatalog +{ + private const string DocsBaseUrl = "https://pieroviano.github.io/BaGet/configuration/"; + private const int MaxDepth = 4; + + private static readonly Dictionary DocsAnchors = new(StringComparer.OrdinalIgnoreCase) + { + ["Accounts"] = "accounts-package-owners-and-api-keys", + ["Email"] = "email-optional", + ["Site"] = "legal-pages", + ["Feeds"] = "nuget-v2-feed", + ["Validation"] = "validate-packages-before-serving-them", + ["Serilog"] = "logging", + ["Mirror"] = "enable-read-through-caching", + ["Storage"] = "storage", + ["Search"] = "search", + ["Database"] = "database-configuration", + ["Ha"] = "high-availability", + ["IISServerOptions"] = "iis-server-options", + ["PathBase"] = "listening-address", + ["Urls"] = "listening-address", + ["AllowedHosts"] = "restrict-the-host-names-baget-extension-serves", + ["ApiKey"] = "require-an-api-key", + ["AllowPackageOverwrites"] = "enable-package-overwrites", + ["PackageDeletionBehavior"] = "enable-package-hard-deletions", + }; + + private readonly List _descriptors; + + /// + /// Builds the catalog. + /// + /// The options types recorded by AddBaGetOptions. + public SettingsCatalog(IEnumerable registrations) + { + if (registrations == null) throw new ArgumentNullException(nameof(registrations)); + + var byKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + var order = new List(); + + foreach (var registration in registrations) + { + Collect( + registration.OptionsType, + registration.Section, + scalarsOnly: registration.Section == null, + IsRestartOnly(registration.OptionsType), + depth: 0, + byKey, + order); + } + + _descriptors = order.Select(k => byKey[k]).ToList(); + } + + /// + /// The settings, in registration order. + /// + public IReadOnlyList Descriptors => _descriptors; + + /// + /// The settings of one section ("" for the top-level keys). + /// + public IEnumerable InSection(string? section) + => _descriptors.Where(d => string.Equals(d.Section, section ?? string.Empty, StringComparison.OrdinalIgnoreCase)); + + /// + /// The setting with this key, or null. + /// + public SettingDescriptor? Find(string key) + => _descriptors.FirstOrDefault(d => string.Equals(d.Key, key, StringComparison.OrdinalIgnoreCase)); + + /// + /// The documentation link for a section of the Settings page: the matching heading of + /// the configuration page, or the top of that page if the section has none. + /// + public static string DocsAnchor(string section) + => !string.IsNullOrEmpty(section) && DocsAnchors.TryGetValue(section, out var anchor) + ? DocsBaseUrl + "#" + anchor + : DocsBaseUrl; + + private static bool IsRestartOnly(Type type) + // A type outside BaGet (such as the framework's IISServerOptions) is read when the + // host is built, so unless it says otherwise a change needs a restart. + => type.GetCustomAttribute(inherit: true) != null + || !(type.Assembly.GetName().Name ?? string.Empty).StartsWith("BaGet", StringComparison.Ordinal); + + private static void Collect( + Type type, + string? prefix, + bool scalarsOnly, + bool inheritedRestart, + int depth, + Dictionary byKey, + List order) + { + foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.GetIndexParameters().Length > 0 + || !property.CanRead + || property.SetMethod == null + || !property.SetMethod.IsPublic + || property.GetCustomAttribute() != null) + { + continue; + } + + var key = string.IsNullOrEmpty(prefix) ? property.Name : prefix + ":" + property.Name; + var restart = inheritedRestart + || property.GetCustomAttribute() != null + || property.DeclaringType?.GetCustomAttribute(inherit: true) != null; + + var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; + + if (IsComplex(propertyType)) + { + // The root's nested objects are covered by their own registrations. + if (scalarsOnly || depth >= MaxDepth) continue; + + Collect(propertyType, key, false, restart, depth + 1, byKey, order); + continue; + } + + var allowed = property.GetCustomAttribute()?.Values; + var kind = allowed != null && propertyType == typeof(string) ? SettingKind.Enum : KindOf(propertyType); + var examples = property.GetCustomAttributes().ToList(); + var descriptor = new SettingDescriptor( + Key: key, + Section: key.Contains(':') ? key.Substring(0, key.IndexOf(':')) : (scalarsOnly ? string.Empty : key), + Group: scalarsOnly ? "BaGet" : GroupOf(property), + Kind: kind, + ClrType: propertyType, + EnumValues: kind != SettingKind.Enum ? Array.Empty() : allowed ?? Enum.GetNames(propertyType), + IsSensitive: property.GetCustomAttribute() != null, + RequiresRestart: restart, + Description: XmlDocumentation.GetSummary(property), + ExampleDependsOnKey: examples.Count == 0 + ? null + : string.IsNullOrEmpty(prefix) ? examples[0].DependsOn : prefix + ":" + examples[0].DependsOn, + Examples: ExamplesOf(property, key, examples)); + + if (byKey.TryGetValue(key, out var existing)) + { + // Two options types sharing a key (such as "Storage:Type") are one setting. + // The choices and examples of whichever type declares them survive the merge. + var choice = existing.Kind == SettingKind.Enum && existing.ClrType == typeof(string) + || descriptor.Kind != SettingKind.Enum || descriptor.ClrType != typeof(string) + ? existing + : descriptor; + byKey[key] = existing with + { + Kind = choice.Kind, + EnumValues = choice.EnumValues, + ExampleDependsOnKey = existing.ExampleDependsOnKey ?? descriptor.ExampleDependsOnKey, + Examples = existing.Examples ?? descriptor.Examples, + IsSensitive = existing.IsSensitive || descriptor.IsSensitive, + RequiresRestart = existing.RequiresRestart || descriptor.RequiresRestart, + Description = existing.Description.Length > 0 ? existing.Description : descriptor.Description, + }; + } + else + { + byKey[key] = descriptor; + order.Add(key); + } + } + } + + private static Dictionary? ExamplesOf( + PropertyInfo property, + string key, + List examples) + { + if (examples.Count == 0) return null; + + // The settings page selects an example by one other setting, so every example of a property + // must depend on the same one and name each value once (case-insensitively). + var dependsOn = examples[0].DependsOn; + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var example in examples) + { + if (!string.Equals(example.DependsOn, dependsOn, StringComparison.Ordinal)) + { + throw new InvalidOperationException( + $"Setting '{key}' ({property.DeclaringType?.Name}.{property.Name}) has [SettingExample] attributes " + + $"that depend on different properties ('{dependsOn}' and '{example.DependsOn}'); only one is supported."); + } + + if (!result.TryAdd(example.WhenValue, example.Example)) + { + throw new InvalidOperationException( + $"Setting '{key}' ({property.DeclaringType?.Name}.{property.Name}) has more than one [SettingExample] " + + $"for the value '{example.WhenValue}' of '{dependsOn}' (values are compared ignoring case)."); + } + } + + return result; + } + + private static string GroupOf(PropertyInfo property) + { + var name = property.DeclaringType?.Name ?? string.Empty; + return name.EndsWith("Options", StringComparison.Ordinal) && name.Length > "Options".Length + ? name.Substring(0, name.Length - "Options".Length) + : name; + } + + private static bool IsComplex(Type type) + => type.IsClass + && type != typeof(string) + && type != typeof(Uri) + && !typeof(IEnumerable).IsAssignableFrom(type); + + private static SettingKind KindOf(Type type) + { + if (type == typeof(bool)) return SettingKind.Boolean; + if (type == typeof(string) || type == typeof(Uri)) return SettingKind.String; + if (type.IsEnum) return SettingKind.Enum; + if (type == typeof(TimeSpan)) return SettingKind.TimeSpan; + if (type == typeof(double) || type == typeof(float) || type == typeof(decimal)) return SettingKind.Number; + + switch (Type.GetTypeCode(type)) + { + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.UInt16: + case TypeCode.Int32: + case TypeCode.UInt32: + case TypeCode.Int64: + case TypeCode.UInt64: + return SettingKind.Integer; + } + + return IsStringList(type) ? SettingKind.StringList : SettingKind.ReadOnly; + } + + private static bool IsStringList(Type type) + { + if (type == typeof(string[])) return true; + if (!type.IsGenericType) return false; + + var definition = type.GetGenericTypeDefinition(); + return type.GetGenericArguments()[0] == typeof(string) + && (definition == typeof(List<>) + || definition == typeof(IList<>) + || definition == typeof(IEnumerable<>) + || definition == typeof(ICollection<>) + || definition == typeof(IReadOnlyList<>) + || definition == typeof(IReadOnlyCollection<>)); + } +} diff --git a/src/BaGet.Core/Configuration/Settings/SettingsForm.cs b/src/BaGet.Core/Configuration/Settings/SettingsForm.cs new file mode 100644 index 000000000..9d9748f1a --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/SettingsForm.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Microsoft.Extensions.Primitives; + +namespace BaGet.Core; + +/// +/// Turns a submitted Settings form into the changes takes. +/// +/// +/// Form fields, per setting key: +/// +/// v:<key>, the value. A boolean is a checkbox "true" plus a hidden "false" (true +/// wins). Numbers and durations use the invariant culture. An enum must be one of the allowed +/// names. A list is one entry per line, blank lines dropped. +/// reset:<key>, removes the saved override. +/// clear:<key>, sensitive settings only: saves an empty value. A blank +/// v: for a sensitive setting means unchanged. +/// +/// Only values that differ from the effective value are returned. +/// +internal static class SettingsForm +{ + /// The field prefix of a value. + public const string ValuePrefix = "v:"; + + /// The field prefix of a reset to the default. + public const string ResetPrefix = "reset:"; + + /// The field prefix of an explicit clear of a sensitive value. + public const string ClearPrefix = "clear:"; + + /// + /// Parses the form against the settings it was rendered from. + /// + /// The submitted fields (an ASP.NET form collection enumerates as this). + /// The settings of the submitted section. + /// The changes, and one "key: reason" per field that failed to parse. + public static (IReadOnlyDictionary Changes, IReadOnlyList Errors) Parse( + IEnumerable> form, + IEnumerable states) + { + if (form == null) throw new ArgumentNullException(nameof(form)); + if (states == null) throw new ArgumentNullException(nameof(states)); + + var fields = new Dictionary(StringComparer.Ordinal); + foreach (var pair in form) fields[pair.Key] = pair.Value; + + var changes = new Dictionary(); + var errors = new List(); + + foreach (var state in states) + { + var descriptor = state.Descriptor; + if (descriptor.Kind == SettingKind.ReadOnly) continue; + + var key = descriptor.Key; + + if (fields.ContainsKey(ResetPrefix + key)) + { + #pragma warning disable CS8625 + if (state.IsOverridden) changes[descriptor] = null; + #pragma warning restore CS8625 + continue; + } + + if (descriptor.IsSensitive) + { + if (fields.ContainsKey(ClearPrefix + key)) + { + if (state.HasValue || state.IsOverridden) changes[descriptor] = string.Empty; + } + else if (fields.TryGetValue(ValuePrefix + key, out var secret) && !string.IsNullOrEmpty(secret.ToString())) + { + changes[descriptor] = secret.ToString(); + } + + continue; + } + + if (!fields.TryGetValue(ValuePrefix + key, out var raw)) continue; + + // A drop-down that listed a current value outside its list posts it back: not a change. + if (descriptor.Kind == SettingKind.Enum + && string.Equals(RawText(raw), state.EffectiveValue ?? string.Empty, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + try + { + var parsed = ParseValue(descriptor, raw); + if (parsed.HasValue && Normalize(descriptor, parsed.Value) != Normalize(descriptor, state.EffectiveValue)) + { + changes[descriptor] = parsed.Value; + } + } + catch (FormatException e) + { + errors.Add($"{key}: {e.Message}"); + } + } + + return (changes, errors); + } + + private static string RawText(StringValues raw) + => (raw.Count == 0 ? string.Empty : raw[raw.Count - 1] ?? string.Empty).Trim(); + + private static (bool HasValue, object Value) ParseValue(SettingDescriptor descriptor, StringValues raw) + { + // A checkbox posts "true" plus the hidden "false": true wins. + if (descriptor.Kind == SettingKind.Boolean) + { + return (true, raw.Any(v => string.Equals(v?.Trim(), "true", StringComparison.OrdinalIgnoreCase))); + } + + var text = (raw.Count == 0 ? string.Empty : raw[raw.Count - 1] ?? string.Empty).Trim(); + + switch (descriptor.Kind) + { + case SettingKind.StringList: + return (true, text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Trim()) + .Where(line => line.Length > 0) + .ToArray()); + + case SettingKind.String: + return (true, text); + } + + // A blank number, duration or name is left unchanged: "reset" is how to go back to the default. + #pragma warning disable CS8619 + if (text.Length == 0) return (false, null); + #pragma warning restore CS8619 + + switch (descriptor.Kind) + { + case SettingKind.Integer: + if (!long.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var whole) + || !FitsInteger(descriptor.ClrType, whole)) + { + throw new FormatException($"\"{text}\" is not a valid whole number."); + } + + return (true, whole); + + case SettingKind.Number: + if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) + || double.IsNaN(number) + || double.IsInfinity(number)) + { + throw new FormatException($"\"{text}\" is not a valid number."); + } + + return (true, number); + + case SettingKind.TimeSpan: + if (!TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var span)) + { + throw new FormatException($"\"{text}\" is not a valid duration (use hh:mm:ss)."); + } + + return (true, span); + + case SettingKind.Enum: + var name = descriptor.EnumValues.FirstOrDefault(v => string.Equals(v, text, StringComparison.OrdinalIgnoreCase)); + if (name == null) + { + throw new FormatException($"\"{text}\" is not one of: {string.Join(", ", descriptor.EnumValues)}."); + } + + return (true, name); + + default: + throw new FormatException("This setting cannot be edited here."); + } + } + + private static bool FitsInteger(Type type, long value) + { + try + { + Convert.ChangeType(value, type, CultureInfo.InvariantCulture); + return true; + } + catch (OverflowException) + { + return false; + } + } + + private static string? Normalize(SettingDescriptor descriptor, object value) + => value switch + { + null => string.Empty, + bool flag => flag ? "true" : "false", + string text => Normalize(descriptor, text), + string[] list => string.Join("\n", list), + TimeSpan span => span.ToString("c", CultureInfo.InvariantCulture), + IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString(), + }; + + private static string Normalize(SettingDescriptor descriptor, string? text) + { + text ??= string.Empty; + + switch (descriptor.Kind) + { + case SettingKind.Boolean: + return bool.TryParse(text, out var flag) && flag ? "true" : "false"; + case SettingKind.Integer: + return long.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var whole) + ? whole.ToString(CultureInfo.InvariantCulture) + : text; + case SettingKind.Number: + return double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) + ? number.ToString(CultureInfo.InvariantCulture) + : text; + case SettingKind.TimeSpan: + return TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var span) + ? span.ToString("c", CultureInfo.InvariantCulture) + : text; + case SettingKind.Enum: + return descriptor.EnumValues.FirstOrDefault(v => string.Equals(v, text, StringComparison.OrdinalIgnoreCase)) ?? text; + default: + return text; + } + } +} diff --git a/src/BaGet.Core/Configuration/Settings/SettingsOverridesStore.cs b/src/BaGet.Core/Configuration/Settings/SettingsOverridesStore.cs new file mode 100644 index 000000000..d627af8b6 --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/SettingsOverridesStore.cs @@ -0,0 +1,283 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; + +namespace BaGet.Core; + +/// +/// The JSON file the Settings page writes. It is loaded after appsettings*.json and before +/// environment variables and the command line, so those still win. +/// +public class SettingsOverridesStore +{ + /// + /// The configuration key that names the overrides file. + /// + public const string PathKey = "SettingsOverridesPath"; + + /// + /// The overrides file's name when is not set. + /// + public const string DefaultFileName = "appsettings.Overrides.json"; + + private static readonly JsonDocumentOptions ReadOptions = new() + { + CommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + }; + + private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true }; + + private readonly SemaphoreSlim _lock = new(1, 1); + + /// + /// Creates a store over a file, which need not exist yet. + /// + /// The overrides file's absolute path. + public SettingsOverridesStore(string filePath) + { + FilePath = filePath ?? throw new ArgumentNullException(nameof(filePath)); + } + + /// + /// The overrides file's absolute path. + /// + public string FilePath { get; } + + /// + /// The absolute path of the overrides file: the "SettingsOverridesPath" setting, otherwise + /// the default file, relative to . + /// + public static string ResolvePath(IConfiguration configuration, string basePath) + { + if (configuration == null) throw new ArgumentNullException(nameof(configuration)); + + var configured = configuration[PathKey]; + return Path.GetFullPath(string.IsNullOrEmpty(configured) ? DefaultFileName : configured, basePath); + } + + /// + /// The keys present in the file, flattened to "A:B" (an array's entries to "A:0", "A:1"). + /// Empty if the file does not exist. Keys compare case-insensitively, as configuration does. + /// + public IReadOnlyDictionary Read() + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + var root = Load(); + + Flatten(root, null, result); + + return result; + } + + /// + /// The configuration pairs a value stands for: one for a scalar, one per entry for a list + /// ("A:0", "A:1"), none for null. + /// + internal static IEnumerable> Flatten(string key, object value) + { + switch (value) + { + case null: + yield break; + case string text: + yield return new KeyValuePair(key, text); + break; + case IEnumerable list: + var index = 0; + foreach (var entry in list) + { + yield return new KeyValuePair(key + ":" + index++, entry); + } + + break; + default: + #pragma warning disable CS8619 + yield return new KeyValuePair(key, ScalarText(value)); + #pragma warning restore CS8619 + break; + } + } + + /// + /// Applies and writes the file atomically. A null value removes + /// the override; a list replaces the whole array. Values are written as typed JSON (boolean, + /// number, array), and parent objects left empty are removed. + /// + /// The new value of each changed setting. + /// Cancels the write. + public async Task WriteAsync(IReadOnlyDictionary changes, CancellationToken cancellationToken) + { + if (changes == null) throw new ArgumentNullException(nameof(changes)); + + await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var root = Load(); + + foreach (var change in changes) + { + var path = change.Key.Key.Split(':'); + if (change.Value == null) + { + Remove(root, path, 0); + } + else + { + Set(root, path, ToNode(change.Value)); + } + } + + var directory = Path.GetDirectoryName(FilePath); + #pragma warning disable CS8604 + Directory.CreateDirectory(directory); + #pragma warning restore CS8604 + + var temp = Path.Combine(directory, "." + Path.GetFileName(FilePath) + "." + Guid.NewGuid().ToString("N") + ".tmp"); + try + { + await File.WriteAllTextAsync(temp, root.ToJsonString(WriteOptions), cancellationToken).ConfigureAwait(false); + File.Move(temp, FilePath, overwrite: true); + } + finally + { + if (File.Exists(temp)) File.Delete(temp); + } + } + finally + { + _lock.Release(); + } + } + + private JsonObject Load() + { + if (!File.Exists(FilePath)) return new JsonObject(); + + string text; + using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + using (var reader = new StreamReader(stream)) + { + text = reader.ReadToEnd(); + } + + if (string.IsNullOrWhiteSpace(text)) return new JsonObject(); + + try + { + return JsonNode.Parse(text, documentOptions: ReadOptions) as JsonObject + ?? throw new InvalidOperationException($"The settings overrides file \"{FilePath}\" does not hold a JSON object."); + } + catch (JsonException e) + { + throw new InvalidOperationException($"The settings overrides file \"{FilePath}\" is not valid JSON: {e.Message}", e); + } + } + + private static void Flatten(JsonNode? node, string? path, Dictionary result) + { + switch (node) + { + case JsonObject obj: + foreach (var pair in obj) + { + Flatten(pair.Value, path == null ? pair.Key : path + ":" + pair.Key, result); + } + + break; + case JsonArray array: + for (var i = 0; i < array.Count; i++) + { + Flatten(array[i], path + ":" + i, result); + } + + break; + case JsonValue value when path != null: + result[path] = value.TryGetValue(out var text) + ? text + : value.ToJsonString().Trim('"'); + break; + } + } + + private static JsonNode? ToNode(object value) + => value switch + { + string text => JsonValue.Create(text), + bool flag => JsonValue.Create(flag), + IEnumerable list => new JsonArray(list.Select(e => (JsonNode)JsonValue.Create(e)).ToArray()), + _ => ScalarNode(value), + }; + + private static JsonNode? ScalarNode(object value) + => value switch + { + sbyte or byte or short or ushort or int or uint or long => JsonValue.Create(Convert.ToInt64(value, CultureInfo.InvariantCulture)), + ulong big => JsonValue.Create(big), + float or double => JsonValue.Create(Convert.ToDouble(value, CultureInfo.InvariantCulture)), + decimal number => JsonValue.Create(number), + _ => JsonValue.Create(ScalarText(value)), + }; + + private static string? ScalarText(object value) + => value switch + { + bool flag => flag ? "true" : "false", + TimeSpan span => span.ToString("c", CultureInfo.InvariantCulture), + IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString(), + }; + + private static string? FindKey(JsonObject obj, string name) + => obj.Select(p => p.Key).FirstOrDefault(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase)); + + private static void Set(JsonObject root, string[] path, JsonNode? value) + { + var current = root; + for (var i = 0; i < path.Length - 1; i++) + { + var existing = FindKey(current, path[i]); + if (existing != null && current[existing] is JsonObject child) + { + current = child; + continue; + } + + if (existing != null) current.Remove(existing); + + child = new JsonObject(); + current[path[i]] = child; + current = child; + } + + var leaf = FindKey(current, path[^1]); + if (leaf != null) current.Remove(leaf); + + current[path[^1]] = value; + } + + private static void Remove(JsonObject node, string[] path, int index) + { + var key = FindKey(node, path[index]); + if (key == null) return; + + if (index == path.Length - 1) + { + node.Remove(key); + return; + } + + if (node[key] is JsonObject child) + { + Remove(child, path, index + 1); + if (child.Count == 0) node.Remove(key); + } + } +} diff --git a/src/BaGet.Core/Configuration/Settings/SettingsService.cs b/src/BaGet.Core/Configuration/Settings/SettingsService.cs new file mode 100644 index 000000000..c1c2c450b --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/SettingsService.cs @@ -0,0 +1,586 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Primitives; + +namespace BaGet.Core; + +/// +/// A setting as the Settings page shows it. +/// +/// The setting. +/// +/// The value in effect, as text (a list one entry per line). Always null for a sensitive +/// setting: only says whether one is set. +/// +/// The setting has a non-empty value. +/// The setting is saved in the overrides file. +/// +/// What overrides the saved value ("environment variable", "command line", ...), or null. +/// While set, a saved value has no effect. +/// +/// A restart-only setting whose value changed since startup. +public sealed record SettingState( + SettingDescriptor Descriptor, + string? EffectiveValue, + bool HasValue, + bool IsOverridden, + string? ShadowedBy, + bool PendingRestart); + +/// +/// The outcome of . +/// +/// The settings were saved. +/// Why they were not. +public sealed record SettingsSaveResult(bool Succeeded, IReadOnlyList Errors) +{ + /// A successful result. + public static SettingsSaveResult Success { get; } = new(true, Array.Empty()); + + /// A failed result. + public static SettingsSaveResult Failed(IEnumerable errors) => new(false, errors.ToList()); +} + +/// +/// Reads the settings' effective state and saves changes to the overrides file. Register it +/// as a singleton and resolve it at startup, so that the startup snapshot, against which +/// "pending restart" is judged, is taken at boot. +/// +public class SettingsService +{ + private readonly IConfiguration _configuration; + private readonly SettingsCatalog _catalog; + private readonly IReadOnlyList _registrations; + private readonly IServiceProvider _services; + private readonly SettingsOverridesStore? _store; + private readonly ILogger _logger; + private readonly Dictionary _startup = new(StringComparer.OrdinalIgnoreCase); + private readonly SemaphoreSlim _saveLock = new(1, 1); + + /// + /// Creates the service and takes the startup snapshot of the restart-only settings. + /// + /// The application's configuration, which is an . + /// The settings. + /// The options types, bound again to validate a candidate. + /// Resolves the registered . + /// Receives the audit entry of each save. + /// The overrides file, or null when it is not available. + public SettingsService( + IConfiguration configuration, + SettingsCatalog catalog, + IEnumerable registrations, + IServiceProvider services, + ILogger logger, + SettingsOverridesStore? store = null) + { + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _registrations = (registrations ?? throw new ArgumentNullException(nameof(registrations))).ToList(); + _services = services ?? throw new ArgumentNullException(nameof(services)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _store = store; + + foreach (var descriptor in _catalog.Descriptors.Where(d => d.RequiresRestart)) + { + #pragma warning disable CS8601 + _startup[descriptor.Key] = ReadValue(descriptor); + #pragma warning restore CS8601 + } + } + + /// + /// Whether settings can be saved: the overrides store is registered. + /// + public bool IsAvailable => _store != null; + + /// + /// The overrides file's path, or null when is false. + /// + public string? OverridesPath => _store?.FilePath; + + /// + /// The catalog this service reports on. + /// + public SettingsCatalog Catalog => _catalog; + + /// + /// Why the overrides file could not be read by the last (it is + /// then treated as empty), or null. + /// + public string? OverridesError { get; private set; } + + /// + /// The state of every setting. + /// + public IReadOnlyList GetState() + { + IReadOnlyDictionary overrides = new Dictionary(); + OverridesError = null; + try + { + overrides = _store?.Read() ?? overrides; + } + catch (Exception e) when (IsStoreFailure(e)) + { + OverridesError = e.Message; + } + + var root = _configuration as IConfigurationRoot; + var overridesIndex = root == null ? -1 : FindOverridesProvider(root.Providers.ToList()); + + return _catalog.Descriptors.Select(d => StateOf(d, overrides, root, overridesIndex)).ToList(); + } + + /// + /// Validates and saves changes. Only failures the changes introduce are reported, so an + /// unused provider's incomplete options cannot block an unrelated save. + /// + /// + /// The token is observed only before the overrides file is replaced (the save lock, the write of the temporary file); + /// the replacement is one synchronous rename. An therefore means the file + /// was not changed. + /// + /// The new value of each changed setting; null removes the override. + /// Who is saving, for the audit log. + /// Cancels the save. + public async Task SaveAsync( + IReadOnlyDictionary changes, + string? actor, + CancellationToken cancellationToken) + { + if (changes == null) throw new ArgumentNullException(nameof(changes)); + if (_store == null) return SettingsSaveResult.Failed(new[] { "Saving settings is not available." }); + if (changes.Count == 0) return SettingsSaveResult.Success; + + await _saveLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + if (_configuration is not IConfigurationRoot root) + { + return SettingsSaveResult.Failed(new[] { "The configuration cannot be reloaded." }); + } + + var providers = root.Providers.ToList(); + IReadOnlyDictionary current; + try + { + current = _store.Read(); + } + catch (Exception e) when (IsStoreFailure(e)) + { + return SettingsSaveResult.Failed(new[] { e.Message }); + } + + var candidate = new Dictionary(current, StringComparer.OrdinalIgnoreCase); + foreach (var change in changes) + { + foreach (var key in candidate.Keys.Where(k => IsKeyOrChild(k, change.Key.Key)).ToList()) + { + candidate.Remove(key); + } + + foreach (var pair in SettingsOverridesStore.Flatten(change.Key.Key, change.Value)) + { + candidate[pair.Key] = pair.Value; + } + } + + var before = Validate(BuildRoot(providers, current)); + var introduced = Validate(BuildRoot(providers, candidate)).Where(f => !before.Contains(f)).ToList(); + if (introduced.Count > 0) return SettingsSaveResult.Failed(introduced); + + try + { + await _store.WriteAsync(changes, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (IsStoreFailure(e)) + { + _logger.LogError(e, "Saving settings to {Path} failed", _store.FilePath); + return SettingsSaveResult.Failed(new[] + { + $"The settings could not be saved to \"{_store.FilePath}\": {e.Message} " + + "Make that location writable, or set SettingsOverridesPath to a writable file.", + }); + } + + root.Reload(); + + // Keys only: a value may be a credential. + _logger.LogWarning( + "{Actor} changed settings {Keys}", + actor, + string.Join(", ", changes.Keys.Select(k => k.Key))); + + return SettingsSaveResult.Success; + } + finally + { + _saveLock.Release(); + } + } + + /// + /// The names of the children of (such as ) that the overrides file holds, + /// so a page can tell what it may edit or remove from what a configuration file or the environment sets. + /// + public IReadOnlyCollection GetSavedChildNames(string sectionKey) + { + try + { + var prefix = sectionKey + ":"; + + return (_store?.Read() ?? new Dictionary()) + .Keys.Where(k => k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .Select(k => k.Substring(prefix.Length).Split(':')[0]) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + } + catch (Exception e) when (IsStoreFailure(e)) + { + return Array.Empty(); + } + } + + /// + /// The per-source log levels now in effect (), by source name, and whether the + /// overrides file holds each. A level set by a configuration file or the environment is listed too. + /// + public IReadOnlyList GetLogLevelOverrides() + { + HashSet saved; + try + { + var prefix = LogLevelOverrides.SectionKey + ":"; + saved = (_store?.Read() ?? new Dictionary()) + .Keys.Where(k => k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .Select(k => k.Substring(prefix.Length)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + } + catch (Exception e) when (IsStoreFailure(e)) + { + saved = new HashSet(StringComparer.OrdinalIgnoreCase); + } + + return _configuration.GetSection(LogLevelOverrides.SectionKey).GetChildren() + .Where(c => !string.IsNullOrEmpty(c.Value)) + .Select(c => new LogLevelOverride(c.Key, c.Value!, saved.Contains(c.Key))) + .OrderBy(o => o.Source, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + /// + /// Sets the lowest level logged for (applies live) or, with a null , + /// removes the override this service saved. An override a configuration file or the environment sets cannot be removed + /// from here, only given another level (the overrides file ranks above the configuration files). + /// + /// A namespace or type name prefix, validated by . + /// A Serilog level name (any case), or null to remove. + /// Who is saving, for the audit log. + /// Cancels the save. + public Task SetLogLevelOverrideAsync(string? source, string? level, string? actor, CancellationToken cancellationToken) + { + var problem = LogLevelOverrides.ValidateSource(source); + if (problem != null) return Task.FromResult(SettingsSaveResult.Failed(new[] { problem })); + + var key = LogLevelOverrides.KeyOf(source!); + object value; + if (level == null) + { + var existing = GetLogLevelOverrides().FirstOrDefault(o => string.Equals(o.Source, source, StringComparison.OrdinalIgnoreCase)); + if (existing is { InOverridesFile: false }) + { + return Task.FromResult(SettingsSaveResult.Failed(new[] + { + $"The level of {existing.Source} is set outside the overrides file (a configuration file or the environment), so it cannot be removed here; change its level instead.", + })); + } + + value = null!; + } + else + { + var normalized = LogLevelOverrides.NormalizeLevel(level); + if (normalized == null) + { + return Task.FromResult(SettingsSaveResult.Failed(new[] { $"\"{level}\" is not a level; use one of {string.Join(", ", LogLevelOverrides.Levels)}." })); + } + + value = normalized; + } + + var descriptor = new SettingDescriptor(key, "Serilog", "Serilog", SettingKind.Enum, typeof(string), LogLevelOverrides.Levels, false, false, "The lowest level logged for one source."); + return SaveAsync(new Dictionary { [descriptor] = value }, actor, cancellationToken); + } + + private SettingState StateOf( + SettingDescriptor descriptor, + IReadOnlyDictionary overrides, + IConfigurationRoot? root, + int overridesIndex) + { + var configured = ReadConfigured(_configuration, descriptor); + var value = configured ?? DefaultValue(descriptor); + var isOverridden = overrides.Keys.Any(k => IsKeyOrChild(k, descriptor.Key)); + + string? shadowedBy = null; + if (root != null && overridesIndex >= 0) + { + var providers = root.Providers.ToList(); + for (var i = providers.Count - 1; i > overridesIndex; i--) + { + if (Has(providers[i], descriptor)) + { + shadowedBy = Describe(providers[i]); + break; + } + } + } + + var pending = descriptor.RequiresRestart + && _startup.TryGetValue(descriptor.Key, out var started) + && !string.Equals(started ?? string.Empty, value ?? string.Empty, StringComparison.Ordinal); + + return new SettingState( + descriptor, + descriptor.IsSensitive ? null : value, + !string.IsNullOrEmpty(configured), + isOverridden, + shadowedBy, + pending); + } + + private static bool Has(IConfigurationProvider provider, SettingDescriptor descriptor) + => provider.TryGet(descriptor.Key, out _) + || (descriptor.Kind == SettingKind.StringList && provider.TryGet(descriptor.Key + ":0", out _)); + + private static string Describe(IConfigurationProvider provider) + { + var name = provider.GetType().Name; + if (name.StartsWith("EnvironmentVariables", StringComparison.Ordinal)) return "environment variable"; + if (name.StartsWith("CommandLine", StringComparison.Ordinal)) return "command line"; + if (name.StartsWith("Chained", StringComparison.Ordinal)) return "host setting"; + if (name.StartsWith("Memory", StringComparison.Ordinal)) return "host setting"; + + return name.EndsWith("ConfigurationProvider", StringComparison.Ordinal) + ? name.Substring(0, name.Length - "ConfigurationProvider".Length) + : name; + } + + private int FindOverridesProvider(IReadOnlyList providers) + { + if (_store == null) return -1; + + var full = System.IO.Path.GetFullPath(_store.FilePath); + for (var i = 0; i < providers.Count; i++) + { + if (providers[i] is FileConfigurationProvider file + && file.Source.FileProvider?.GetFileInfo(file.Source.Path ?? string.Empty) is { PhysicalPath: { } physical } + && string.Equals(System.IO.Path.GetFullPath(physical), full, StringComparison.OrdinalIgnoreCase)) + { + return i; + } + } + + return -1; + } + + private static bool IsKeyOrChild(string candidate, string key) + => string.Equals(candidate, key, StringComparison.OrdinalIgnoreCase) + || candidate.StartsWith(key + ":", StringComparison.OrdinalIgnoreCase); + + private static bool IsStoreFailure(Exception e) + => e is System.IO.IOException or UnauthorizedAccessException or InvalidOperationException; + + /// + /// The value in effect: the configured one, or when no provider sets the key, the options + /// type's default (a default-true boolean is on although no file mentions it). + /// + private string? ReadValue(SettingDescriptor descriptor) + => ReadConfigured(_configuration, descriptor) ?? DefaultValue(descriptor); + + private string? DefaultValue(SettingDescriptor descriptor) + { + foreach (var registration in _registrations) + { + var path = descriptor.Key.Split(':'); + var skip = 0; + if (registration.Section != null) + { + var prefix = registration.Section.Split(':'); + if (path.Length <= prefix.Length + || !prefix.SequenceEqual(path.Take(prefix.Length), StringComparer.OrdinalIgnoreCase)) + { + continue; + } + + skip = prefix.Length; + } + + object? instance; + try + { + instance = Activator.CreateInstance(registration.OptionsType); + } + catch (Exception e) when (e is MissingMethodException or System.Reflection.TargetInvocationException) + { + continue; + } + + foreach (var segment in path.Skip(skip)) + { + if (instance == null) break; + + var property = instance.GetType().GetProperty( + segment, + System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase); + if (property == null || property.GetIndexParameters().Length > 0) + { + instance = null; + break; + } + + instance = property.GetValue(instance); + } + + if (instance == null) continue; + + return FormatDefault(instance); + } + + return null; + } + + private static string? FormatDefault(object value) + => value switch + { + bool flag => flag ? "true" : "false", + string text => text, + TimeSpan span => span.ToString("c", System.Globalization.CultureInfo.InvariantCulture), + IFormattable formattable => formattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture), + IDictionary => null, + IEnumerable list => FormatList(list), + _ => value.ToString(), + }; + + private static string? FormatList(IEnumerable list) + { + var entries = list.Cast().Where(o => o != null).Select(o => o.ToString()).ToList(); + return entries.Count == 0 ? null : string.Join("\n", entries); + } + + private static string? ReadConfigured(IConfiguration configuration, SettingDescriptor descriptor) + { + if (descriptor.Kind != SettingKind.StringList) return configuration[descriptor.Key]; + + var entries = configuration.GetSection(descriptor.Key).GetChildren() + .Where(c => c.Value != null) + .OrderBy(c => int.TryParse(c.Key, out var n) ? n : int.MaxValue) + .Select(c => c.Value) + .ToList(); + + return entries.Count == 0 ? null : string.Join("\n", entries); + } + + /// + /// A configuration with every provider as it is now, except the overrides file's, which is + /// replaced by . The real providers are wrapped, so building and + /// disposing it neither reloads nor disposes them. + /// + private IConfigurationRoot BuildRoot(IReadOnlyList providers, IReadOnlyDictionary overrides) + { + var overridesIndex = FindOverridesProvider(providers); + var wrapped = new List(); + for (var i = 0; i < providers.Count; i++) + { + wrapped.Add(i == overridesIndex + ? new MemorySnapshotProvider(overrides) + : new FrozenProvider(providers[i])); + } + + // A host that did not insert the overrides source: the candidate is added last. + if (overridesIndex < 0) wrapped.Add(new MemorySnapshotProvider(overrides)); + + return new ConfigurationRoot(wrapped); + } + + private HashSet Validate(IConfigurationRoot configuration) + { + var failures = new HashSet(StringComparer.Ordinal); + + foreach (var registration in _registrations) + { + object? instance; + try + { + instance = Activator.CreateInstance(registration.OptionsType); + var section = registration.Section == null ? (IConfiguration)configuration : configuration.GetSection(registration.Section); + section.Bind(instance); + } + catch (Exception e) when (e is InvalidOperationException or MissingMethodException or ArgumentException) + { + failures.Add($"{registration.Section ?? "(root)"}: {e.Message}"); + continue; + } + + var validatorType = typeof(IEnumerable<>).MakeGenericType(typeof(IValidateOptions<>).MakeGenericType(registration.OptionsType)); + var validators = (IEnumerable?)_services.GetService(validatorType); + if (validators == null) continue; + + foreach (var validator in validators) + { + var method = validator.GetType().GetInterfaces() + .First(i => i.IsGenericType + && i.GetGenericTypeDefinition() == typeof(IValidateOptions<>) + && i.GetGenericArguments()[0] == registration.OptionsType) + .GetMethod(nameof(IValidateOptions.Validate)); + + var result = (ValidateOptionsResult?)method?.Invoke(validator, new[] { Options.DefaultName, instance }); + #pragma warning disable CS8602 + if (result.Failed) + #pragma warning restore CS8602 + { + foreach (var failure in result.Failures) failures.Add(failure); + } + } + } + + return failures; + } + + private sealed class FrozenProvider : IConfigurationProvider + { + private readonly IConfigurationProvider _inner; + + public FrozenProvider(IConfigurationProvider inner) => _inner = inner; + + public bool TryGet(string key, out string? value) => _inner.TryGet(key, out value); + + public void Set(string key, string? value) + { + } + + public IChangeToken GetReloadToken() => new ConfigurationReloadToken(); + + public void Load() + { + } + + public IEnumerable GetChildKeys(IEnumerable earlierKeys, string? parentPath) + => _inner.GetChildKeys(earlierKeys, parentPath); + } + + private sealed class MemorySnapshotProvider : ConfigurationProvider + { + public MemorySnapshotProvider(IReadOnlyDictionary values) + { + foreach (var pair in values) Data[pair.Key] = pair.Value; + } + } +} diff --git a/src/BaGet.Core/Configuration/Settings/XmlDocumentation.cs b/src/BaGet.Core/Configuration/Settings/XmlDocumentation.cs new file mode 100644 index 000000000..1fb4ffb2d --- /dev/null +++ b/src/BaGet.Core/Configuration/Settings/XmlDocumentation.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml.Linq; + +namespace BaGet.Core; + +/// +/// Reads property summaries from the <assembly>.xml file that the compiler +/// writes beside the assembly, so the Settings page can show the same text as the code. +/// +public static class XmlDocumentation +{ + private static readonly ConcurrentDictionary> Cache = new(); + + /// + /// The summary of a property: whitespace collapsed, a see cref replaced by the last + /// segment of its target. An empty string if the file or the member is missing. + /// + public static string GetSummary(PropertyInfo? property) + { + if (property?.DeclaringType == null) return string.Empty; + + var summaries = Cache.GetOrAdd(property.DeclaringType.Assembly, Load); + var id = "P:" + property.DeclaringType.FullName?.Replace('+', '.') + "." + property.Name; + + return summaries.TryGetValue(id, out var summary) ? summary : string.Empty; + } + + private static IReadOnlyDictionary Load(Assembly assembly) + { + var result = new Dictionary(StringComparer.Ordinal); + + try + { + var name = assembly.GetName().Name + ".xml"; + var candidates = new List(); + if (!string.IsNullOrEmpty(assembly.Location)) + { + #pragma warning disable CS8604 + candidates.Add(Path.Combine(Path.GetDirectoryName(assembly.Location), name)); + #pragma warning restore CS8604 + } + + candidates.Add(Path.Combine(AppContext.BaseDirectory, name)); + + foreach (var path in candidates) + { + if (!File.Exists(path)) continue; + + var document = XDocument.Load(path); + foreach (var member in document.Descendants("member")) + { + var id = (string?)member.Attribute("name"); + var summary = member.Element("summary"); + if (id != null && id.StartsWith("P:", StringComparison.Ordinal) && summary != null) + { + result[id] = Collapse(Text(summary)); + } + } + + break; + } + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.Xml.XmlException) + { + // Descriptions are a convenience: without them the Settings page still works. + } + + return result; + } + + private static string Text(XElement element) + { + var text = new StringBuilder(); + foreach (var node in element.Nodes()) + { + switch (node) + { + case XText t: + text.Append(t.Value); + break; + case XElement e when e.Name == "see" || e.Name == "seealso": + var cref = (string?)e.Attribute("cref"); + var langword = (string?)e.Attribute("langword"); + if (cref != null) text.Append(LastSegment(cref)); + else if (langword != null) text.Append(langword); + else text.Append(Text(e)); + break; + case XElement e when e.Name == "paramref" || e.Name == "typeparamref": + text.Append((string?)e.Attribute("name")); + break; + case XElement e: + text.Append(Text(e)); + break; + } + } + + return text.ToString(); + } + + private static string LastSegment(string cref) + { + var target = cref; + var colon = target.IndexOf(':'); + if (colon >= 0) target = target.Substring(colon + 1); + + var paren = target.IndexOf('('); + if (paren >= 0) target = target.Substring(0, paren); + + var dot = target.LastIndexOf('.'); + return dot >= 0 ? target.Substring(dot + 1) : target; + } + + private static string Collapse(string text) => Regex.Replace(text, @"\s+", " ").Trim(); +} diff --git a/src/BaGet.Core/Configuration/SiteOptions.cs b/src/BaGet.Core/Configuration/SiteOptions.cs new file mode 100644 index 000000000..4788a6ee1 --- /dev/null +++ b/src/BaGet.Core/Configuration/SiteOptions.cs @@ -0,0 +1,78 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Linq; + +namespace BaGet.Core; + +/// +/// Accepts only a Markdown file path (*.md) without a ".." segment. The legal pages are public, +/// so a path to any other file (appsettings.json, the settings overrides file) would publish it. +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class MarkdownFilePathAttribute : ValidationAttribute +{ + /// Whether is empty or an allowed Markdown file path. + public static bool IsAllowed(string path) + { + if (string.IsNullOrWhiteSpace(path)) return true; + + if (!path.Trim().EndsWith(".md", StringComparison.OrdinalIgnoreCase)) return false; + + return !path.Split('/', (char)92).Any(segment => segment.Trim() == ".."); + } + + /// + #pragma warning disable CS8620 + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) + => value is not string path || IsAllowed(path) + ? ValidationResult.Success + : new ValidationResult( + $"{validationContext.MemberName} must be a Markdown file (.md) path without \"..\" segments.", + new[] { validationContext.MemberName }); + #pragma warning restore CS8620 +} + + +/// +/// Settings of the web site's chrome. BaGet ships no legal text: the operator supplies +/// the Terms of Use and Privacy Policy as Markdown files, and the footer links to them +/// only while they are set. +/// +public class SiteOptions +{ + /// + /// A Markdown file (.md), absolute or relative to the content root, served at /terms. + /// + [MarkdownFilePath] + public string? TermsOfUsePath { get; set; } + + /// + /// A Markdown file (.md), absolute or relative to the content root, served at /privacy. + /// + [MarkdownFilePath] + public string? PrivacyPolicyPath { get; set; } + + /// + /// The absolute http or https URL users reach this server at, for example + /// "https://packages.example.com" (a path is allowed when served under one). Links in + /// account emails are built only from it. Without it they can only be built from the + /// request host when "AllowedHosts" restricts the hosts; with the default "*" email is + /// switched off, because a forged Host header would otherwise decide where a password + /// reset link points. + /// + [RestartRequired] + public string? PublicUrl { get; set; } + + /// + /// Show Gravatar avatars. Each avatar is a request to gravatar.com carrying a hash of the + /// account's email, so a private feed can turn this off and get initial-letter placeholders. + /// + public bool UseGravatar { get; set; } = true; + + /// + /// Set by the host from Frontend:SpaLinks / Frontend:Mvc: the base path of the single-page application that account emails link to + /// (/app), or null for the server-rendered screens. Not a setting. + /// + [HiddenSetting] + public string? SpaLinkBase { get; set; } +} diff --git a/src/BaGet.Core/Configuration/StorageOptions.cs b/src/BaGet.Core/Configuration/StorageOptions.cs index be8c8a5db..5138fd2dc 100644 --- a/src/BaGet.Core/Configuration/StorageOptions.cs +++ b/src/BaGet.Core/Configuration/StorageOptions.cs @@ -1,7 +1,11 @@ -namespace BaGet.Core +namespace BaGet.Core; + +[RestartRequired] +public class StorageOptions { - public class StorageOptions - { - public string Type { get; set; } - } -} + /// + /// The package storage backend. + /// + [AllowedSettingValues("AliyunOss", "AwsS3", "AzureBlobStorage", "Filesystem", "GoogleCloud", "Null")] + public string? Type { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/TelemetryOptions.cs b/src/BaGet.Core/Configuration/TelemetryOptions.cs new file mode 100644 index 000000000..1d6fae44e --- /dev/null +++ b/src/BaGet.Core/Configuration/TelemetryOptions.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// OpenTelemetry export (traces, metrics, logs). Off by default. The libraries only emit +/// spans and metrics; the host exports them over OTLP. +/// The host reads these through IOptionsMonitor and applies a change live, except and +/// , which are read once when the exporter is built +/// (). +/// +public class TelemetryOptions +{ + /// The master switch. While false nothing is exported. + public bool Enabled { get; set; } + + /// The service.name resource attribute reported with every signal. + [RestartRequired] + public string ServiceName { get; set; } = "baget"; + + /// Where and how signals are sent ( is the traces endpoint; metrics and logs have their own endpoints and never fall back to it). + public OtlpOptions Otlp { get; set; } = new(); + + /// Distributed traces. + public TracesOptions Traces { get; set; } = new(); + + /// Metrics. + public MetricsOptions Metrics { get; set; } = new(); + + /// Logs. + public LogsOptions Logs { get; set; } = new(); + + /// + /// What is wrong with these options, one message per problem (empty when valid): an endpoint that is not an + /// absolute http(s) URL, an unknown protocol, a sampling ratio outside [0, 1], a non-positive timeout or export interval. + /// Empty endpoints are valid (that signal is simply not exported). + /// + public IReadOnlyList Validate() + { + var failures = new List(); + const string section = nameof(BaGetOptions.Telemetry); + + CheckEndpoint(failures, $"{section}:{nameof(Otlp)}:{nameof(OtlpOptions.Endpoint)}", Otlp?.Endpoint); + CheckEndpoint(failures, $"{section}:{nameof(Metrics)}:{nameof(MetricsOptions.Endpoint)}", Metrics?.Endpoint); + CheckEndpoint(failures, $"{section}:{nameof(Logs)}:{nameof(LogsOptions.Endpoint)}", Logs?.Endpoint); + + var protocols = AllowedSettingValuesAttribute.ValuesOf(nameof(OtlpOptions.Protocol)); + if (Otlp != null && !protocols.Contains(Otlp.Protocol, StringComparer.OrdinalIgnoreCase)) + { + failures.Add($"The '{section}:{nameof(Otlp)}:{nameof(OtlpOptions.Protocol)}' config is invalid. Allowed values: {string.Join(", ", protocols)}"); + } + + var levels = AllowedSettingValuesAttribute.ValuesOf(nameof(LogsOptions.MinimumLevel)); + if (Logs != null && !levels.Contains(Logs.MinimumLevel, StringComparer.OrdinalIgnoreCase)) + { + failures.Add($"The '{section}:{nameof(Logs)}:{nameof(LogsOptions.MinimumLevel)}' config is invalid. Allowed values: {string.Join(", ", levels)}"); + } + + if (Traces != null && !(Traces.SamplingRatio >= 0 && Traces.SamplingRatio <= 1)) + { + failures.Add($"The '{section}:{nameof(Traces)}:{nameof(TracesOptions.SamplingRatio)}' config must be between 0 and 1"); + } + + if (Otlp != null && Otlp.Timeout <= TimeSpan.Zero) + { + failures.Add($"The '{section}:{nameof(Otlp)}:{nameof(OtlpOptions.Timeout)}' config must be greater than zero"); + } + + if (Metrics != null && Metrics.ExportInterval <= TimeSpan.Zero) + { + failures.Add($"The '{section}:{nameof(Metrics)}:{nameof(MetricsOptions.ExportInterval)}' config must be greater than zero"); + } + + return failures; + } + + private static void CheckEndpoint(List failures, string key, string? endpoint) + { + if (string.IsNullOrWhiteSpace(endpoint)) return; + + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) + || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + { + // The value is not echoed: a collector URL may carry a token. + failures.Add($"The '{key}' config must be an absolute http or https URL"); + } + } +} + +/// The OTLP connection shared by all signals. +public class OtlpOptions +{ + /// + /// The collector's absolute http(s) URL, for example a Jaeger or OpenTelemetry Collector. + /// Empty means traces are not exported. + /// + [SettingExample(nameof(Protocol), "Grpc", "http://jaeger:4317")] + [SettingExample(nameof(Protocol), "HttpProtobuf", "http://jaeger:4318")] + public string? Endpoint { get; set; } + + /// The OTLP transport: gRPC (port 4317) or HTTP/protobuf (port 4318). + [AllowedSettingValues("Grpc", "HttpProtobuf")] + public string Protocol { get; set; } = "Grpc"; + + /// Extra request headers as key=value,key2=value2, such as an API key for a hosted collector. + [SensitiveSetting] + public string? Headers { get; set; } + + /// How long an export may take before it is abandoned. + public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(10); +} + +/// Trace settings. +public class TracesOptions +{ + /// Export traces (when and an endpoint are set). + public bool Enabled { get; set; } = true; + + /// The fraction of new traces recorded, from 0 (none) to 1 (all). A trace already sampled upstream is kept. + public double SamplingRatio { get; set; } = 1.0; + + /// Record database commands as spans. + public bool Database { get; set; } = true; +} + +/// Metric settings. +public class MetricsOptions +{ + /// The collector to send metrics to. It does not fall back to Otlp:Endpoint: empty means metrics are not exported (Jaeger accepts traces only). + public string? Endpoint { get; set; } + + /// How often metrics are exported. + [RestartRequired] + public TimeSpan ExportInterval { get; set; } = TimeSpan.FromSeconds(60); +} + +/// Log export settings. +public class LogsOptions +{ + /// The collector to send logs to. It does not fall back to Otlp:Endpoint: empty means logs are not exported (Jaeger accepts traces only). + public string? Endpoint { get; set; } + + /// The lowest Serilog level exported. + [AllowedSettingValues("Verbose", "Debug", "Information", "Warning", "Error", "Fatal")] + public string MinimumLevel { get; set; } = "Information"; +} diff --git a/src/BaGet.Core/Configuration/ValidationOptions.cs b/src/BaGet.Core/Configuration/ValidationOptions.cs new file mode 100644 index 000000000..031bcf28a --- /dev/null +++ b/src/BaGet.Core/Configuration/ValidationOptions.cs @@ -0,0 +1,37 @@ +namespace BaGet.Core; + +/// +/// Asynchronous validation of pushed packages. +/// +public class ValidationOptions +{ + /// + /// Off by default. With it off a push is indexed at once, exactly as before. + /// With it on, a push answers 202 Accepted and the package appears once every + /// validator has passed; a package that fails is quarantined, never served. + /// + public bool Enabled { get; set; } + + /// + /// Reject packages without a valid author or repository signature. + /// + public bool RequireSignedPackages { get; set; } + + /// + /// A PFX file whose certificate repository-signs every package that passes + /// validation. Unused unless set; the RepositorySignatures resource is only + /// advertised when it is. + /// + public string? RepositorySigningCertificatePath { get; set; } + + [SensitiveSetting] + public string? RepositorySigningCertificatePassword { get; set; } + + /// + /// This server's public service index URL, recorded in every repository signature; + /// a client checks it against the source it restored from. Required for signing, + /// since signing runs in the background, outside any request to read it from, and + /// it must be https: NuGet rejects a repository signature for any other scheme. + /// + public string? RepositorySigningServiceIndexUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Content/DefaultPackageContentService.cs b/src/BaGet.Core/Content/DefaultPackageContentService.cs index 8d0a76d13..6a34f353e 100644 --- a/src/BaGet.Core/Content/DefaultPackageContentService.cs +++ b/src/BaGet.Core/Content/DefaultPackageContentService.cs @@ -6,87 +6,114 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Implements the NuGet Package Content resource in NuGet's V3 protocol. +/// +public class DefaultPackageContentService : IPackageContentService { - /// - /// Implements the NuGet Package Content resource in NuGet's V3 protocol. - /// - public class DefaultPackageContentService : IPackageContentService + private readonly IPackageService _packages; + private readonly IPackageStorageService _storage; + + public DefaultPackageContentService( + IPackageService packages, + IPackageStorageService storage) { - private readonly IPackageService _packages; - private readonly IPackageStorageService _storage; + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + } - public DefaultPackageContentService( - IPackageService packages, - IPackageStorageService storage) + public async Task GetPackageVersionsOrNullAsync( + string id, + CancellationToken cancellationToken = default) + { + var versions = await _packages.FindPackageVersionsAsync(id, cancellationToken); + if (!versions.Any()) { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + return null; } - public async Task GetPackageVersionsOrNullAsync( - string id, - CancellationToken cancellationToken = default) + return new PackageVersionsResponse { - var versions = await _packages.FindPackageVersionsAsync(id, cancellationToken); - if (!versions.Any()) - { - return null; - } - - return new PackageVersionsResponse - { - Versions = versions - .Select(v => v.ToNormalizedString()) - .Select(v => v.ToLowerInvariant()) - .ToList() - }; - } + Versions = versions + .Select(v => v.ToNormalizedString()) + .Select(v => v.ToLowerInvariant()) + .ToList() + }; + } - public async Task GetPackageContentStreamOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken = default) - { - if (!await _packages.ExistsAsync(id, version, cancellationToken)) - { - return null; - } + public async Task GetPackageContentStreamOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken = default) + { + // A remote repository that stores nothing streams the upstream's file through. + var uncached = await _packages.OpenUncachedAsync(id, version, cancellationToken); + if (uncached != null) return uncached; - await _packages.AddDownloadAsync(id, version, cancellationToken); - return await _storage.GetPackageStreamAsync(id, version, cancellationToken); + if (!await _packages.ExistsAsync(id, version, cancellationToken)) + { + return null; } - public async Task GetPackageManifestStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) - { - if (!await _packages.ExistsAsync(id, version, cancellationToken)) - { - return null; - } + await _packages.AddDownloadAsync(id, version, cancellationToken); + return await _storage.GetPackageStreamAsync(id, version, cancellationToken); + } - return await _storage.GetNuspecStreamAsync(id, version, cancellationToken); + public async Task GetPackageManifestStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) + { + using (var uncached = await _packages.OpenUncachedAsync(id, version, cancellationToken)) + { + if (uncached != null) return ReadNuspec(uncached); } - public async Task GetPackageReadmeStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) + if (!await _packages.ExistsAsync(id, version, cancellationToken)) { - var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); - if (package == null || !package.HasReadme) - { - return null; - } + return null; + } - return await _storage.GetReadmeStreamAsync(id, version, cancellationToken); + return await _storage.GetNuspecStreamAsync(id, version, cancellationToken); + } + + public async Task GetPackageReadmeStreamOrNullAsync(string? id, NuGetVersion version, CancellationToken cancellationToken = default) + { + var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); + if (package == null || !package.HasReadme) + { + return null; } - public async Task GetPackageIconStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) + return await _storage.GetReadmeStreamAsync(id, version, cancellationToken); + } + + public async Task GetPackageIconStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) + { + var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); + if (package == null || !package.HasEmbeddedIcon) { - var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); - if (package == null || !package.HasEmbeddedIcon) - { - return null; - } + return null; + } - return await _storage.GetIconStreamAsync(id, version, cancellationToken); + return await _storage.GetIconStreamAsync(id, version, cancellationToken); + } + + // The .nuspec at the root of a package, copied to memory so the package stream can be disposed. + private static Stream? ReadNuspec(Stream package) + { + using var archive = new System.IO.Compression.ZipArchive(package, System.IO.Compression.ZipArchiveMode.Read, leaveOpen: true); + var entry = archive.Entries.FirstOrDefault(e => + e.FullName.IndexOf('/') < 0 && e.FullName.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase)); + if (entry == null) return null; + + var copy = new MemoryStream(); + using (var source = entry.Open()) + { + source.CopyTo(copy); } + + copy.Position = 0; + + return copy; } } diff --git a/src/BaGet.Core/Content/IPackageContentService.cs b/src/BaGet.Core/Content/IPackageContentService.cs index 31abcafdd..1dbc8dc80 100644 --- a/src/BaGet.Core/Content/IPackageContentService.cs +++ b/src/BaGet.Core/Content/IPackageContentService.cs @@ -4,82 +4,81 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The Package Content resource, used to download NuGet packages and to fetch other metadata. +/// +/// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource +/// +public interface IPackageContentService { /// - /// The Package Content resource, used to download NuGet packages and to fetch other metadata. - /// - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// Get a package's versions, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions /// - public interface IPackageContentService - { - /// - /// Get a package's versions, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions - /// - /// The package ID. - /// A token to cancel the task. - /// The package's versions, or null if the package does not exist. - Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken); + /// The package ID. + /// A token to cancel the task. + /// The package's versions, or null if the package does not exist. + Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken); - /// - /// Download a package, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg - /// - /// The package ID. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's content stream, or null if the package does not exist. The stream may not be seekable. - /// - Task GetPackageContentStreamOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken); + /// + /// Download a package, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg + /// + /// The package ID. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's content stream, or null if the package does not exist. The stream may not be seekable. + /// + Task GetPackageContentStreamOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken); - /// - /// Download a package's manifest (nuspec), or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. - /// - Task GetPackageManifestStreamOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken); + /// + /// Download a package's manifest (nuspec), or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. + /// + Task GetPackageManifestStreamOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken); - /// - /// Download a package's readme, or null if the package or readme does not exist. - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's readme stream, or null if the package or readme does not exist. The stream may not be seekable. - /// - Task GetPackageReadmeStreamOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken); + /// + /// Download a package's readme, or null if the package or readme does not exist. + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's readme stream, or null if the package or readme does not exist. The stream may not be seekable. + /// + Task GetPackageReadmeStreamOrNullAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken); - /// - /// Download a package's icon, or null if the package or icon does not exist. - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's icon stream, or null if the package or icon does not exist. The stream may not be seekable. - /// - Task GetPackageIconStreamOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken); - } -} + /// + /// Download a package's icon, or null if the package or icon does not exist. + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's icon stream, or null if the package or icon does not exist. The stream may not be seekable. + /// + Task GetPackageIconStreamOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/AbstractContext.cs b/src/BaGet.Core/Entities/AbstractContext.cs index 7c8c2482d..efc85c92a 100644 --- a/src/BaGet.Core/Entities/AbstractContext.cs +++ b/src/BaGet.Core/Entities/AbstractContext.cs @@ -1,160 +1,990 @@ +using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Builders; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Identity's tables live in the same database as the packages, so a deployment keeps +/// one database. They are created by a migration whether or not accounts are enabled. +/// +public abstract class AbstractContext : IdentityDbContext, IContext, IRepositoryScopedContext where TContext : DbContext { - public abstract class AbstractContext : DbContext, IContext where TContext : DbContext + public const int DefaultMaxStringLength = 4000; + + public const int MaxPackageIdLength = 128; + public const int MaxPackageVersionLength = 64; + public const int MaxPackageMinClientVersionLength = 44; + public const int MaxPackageLanguageLength = 20; + public const int MaxPackageTitleLength = 256; + public const int MaxPackageTypeNameLength = 512; + public const int MaxPackageTypeVersionLength = 64; + public const int MaxRepositoryTypeLength = 100; + public const int MaxTargetFrameworkLength = 256; + + public const int MaxPackageDependencyVersionRangeLength = 256; + + public const int MaxCatalogCommitIdLength = 36; + public const int MaxCatalogTypeLength = 32; + + public const int MaxAccountNameLength = 256; + public const int MaxUserIdLength = 450; + public const int MaxApiKeyDescriptionLength = 256; + public const int MaxApiKeyHashLength = 64; + + public const int MaxRepositoryNameLength = RepositoryNames.MaxLength; + public const int MaxRepositoryFormatLength = 32; + + // npm's own limits: a package name (scope included) is at most 214 characters, a version and a dist-tag fit 256. + public const int MaxScanNameLength = ScanLimits.NameLength; + public const int MaxScanVersionLength = ScanLimits.VersionLength; + public const int MaxScanIdLength = ScanLimits.IdLength; + public const int MaxScanSummaryLength = ScanLimits.SummaryLength; + public const int MaxScanUrlLength = ScanLimits.UrlLength; + public const int MaxScanErrorLength = ScanLimits.ErrorLength; + public const int MaxScanScannerLength = ScanLimits.ScannerLength; + public const int MaxNpmNameLength = 214; + public const int MaxNpmVersionLength = 256; + public const int MaxNpmTagLength = 128; + public const int MaxNpmIntegrityLength = 256; + public const int MaxNpmShasumLength = 40; + // Maven's layout is folders, so the lengths keep the unique indexes (group, artifact; version, file) within SQL Server's and + // MySQL's key limits. + public const int MaxMavenGroupLength = 200; + public const int MaxMavenArtifactLength = 128; + public const int MaxMavenVersionLength = 128; + public const int MaxMavenFileNameLength = 256; + public const int MaxMavenClassifierLength = 64; + public const int MaxMavenExtensionLength = 64; + public const int MaxMavenNameLength = 512; + public const int MaxMavenDescriptionLength = 4000; + public const int MaxMavenPackagingLength = 64; + public const int MaxMavenSnapshotTimestampLength = 15; + public const int MaxMavenChecksumLength = 128; + // OCI: image names and tags are bounded by the specification (a tag by 128), digests by "sha256:" + 64 hex; the unique indexes + // (repository, image), (image, tag) stay within the key limits of SQL Server and MySQL. + public const int MaxOciImageLength = OciNames.MaxImageLength; + public const int MaxOciTagLength = OciNames.MaxTagLength; + public const int MaxOciDigestLength = OciNames.MaxDigestLength; + public const int MaxOciMediaTypeLength = OciNames.MaxMediaTypeLength; + public const int MaxOciUploadReferenceLength = 128; + public const int MaxOciStorageUploadIdLength = 512; + // Retention: the longest Maven group:artifact (200 + 1 + 128) fits; with the version the unique indexes stay within SQL Server's and MySQL's key limits. + public const int MaxRetentionNameLength = RetentionLimits.MaxNameLength; + public const int MaxRetentionVersionLength = RetentionLimits.MaxVersionLength; + public const int MaxRetentionReasonLength = RetentionLimits.MaxReasonLength; + public const int MaxRetentionPatternsLength = RetentionLimits.MaxPatternsLength; + public const int MaxRetentionResultLength = RetentionLimits.MaxResultLength; + public const int MaxProjectNameLength = 64; + public const int MaxProjectDisplayNameLength = 256; + + public const int MaxAccessNameLength = AccessNames.MaxLength; + public const int MaxAccessDescriptionLength = 256; + public const int MaxPrincipalTypeLength = 16; + public const int MaxAuditActionLength = 64; + + public const int MaxValidationTypeLength = 64; + + public const int MaxAbuseReasonLength = 128; + public const int MaxPdbFileNameLength = 255; + public const int MaxSymbolKeyLength = 64; + public const int MaxEmailLength = 256; + + private IRepositoryContext? _repository; + + public AbstractContext(DbContextOptions options) + : base(options) + { } + + /// + /// The repository this context reads and writes: every query is filtered on it + /// and new rows are stamped with it. Resolved from the application's DI scope on first use when the context + /// was created by DI; a context built by hand (a database copy's target, design time) works in the default + /// repository unless this is set. Not a security boundary on its own: IgnoreQueryFilters() sees all. + /// + public IRepositoryContext RepositoryScope + { + get => _repository ??= ResolveRepositoryScope() ?? DefaultRepositoryContext.Instance; + set => _repository = value ?? throw new ArgumentNullException(nameof(value)); + } + + // AddDbContext hands the context the application's provider (the request scope); a hand-built context has none. + private IRepositoryContext? ResolveRepositoryScope() + => this.GetService().FindExtension() + ?.ApplicationServiceProvider?.GetService(typeof(IRepositoryContext)) as IRepositoryContext; + + /// + /// The key the query filters compare against. Evaluated per query, so it follows + /// called after the context was created. + /// + protected int CurrentRepositoryKey => RepositoryScope.Current.Key; + + /// The repository this context works in now (what reports a deploy for). + public int ScopeRepositoryKey => CurrentRepositoryKey; + + public DbSet? Packages { get; set; } + public DbSet? PackageDependencies { get; set; } + public DbSet? PackageTypes { get; set; } + public DbSet? TargetFrameworks { get; set; } + public DbSet? PackageDeprecations { get; set; } + public DbSet? PackageVulnerabilities { get; set; } + public DbSet? CatalogLeafs { get; set; } + public DbSet? Organizations { get; set; } + public DbSet? OrganizationMembers { get; set; } + public DbSet? PackageOwners { get; set; } + public DbSet? ApiKeys { get; set; } + public DbSet? ApiKeyRepositories { get; set; } + public DbSet? PackageValidations { get; set; } + public DbSet? AbuseReports { get; set; } + public DbSet? PackageSymbols { get; set; } + public DbSet? ScanResults { get; set; } + public DbSet? ScanFindings { get; set; } + public DbSet? ScanPolicies { get; set; } + public DbSet? NpmPackages { get; set; } + public DbSet? NpmVersions { get; set; } + public DbSet? NpmDistTags { get; set; } + public DbSet? MavenArtifacts { get; set; } + public DbSet? MavenVersions { get; set; } + public DbSet? MavenFiles { get; set; } + public DbSet? OciRepositories { get; set; } + public DbSet? OciManifests { get; set; } + public DbSet? OciTags { get; set; } + public DbSet? OciBlobs { get; set; } + public DbSet? OciBlobLinks { get; set; } + public DbSet? OciUploads { get; set; } + public DbSet? Repositories { get; set; } + public DbSet? Projects { get; set; } + public DbSet? Groups { get; set; } + public DbSet? GroupMembers { get; set; } + public DbSet? PermissionTargets { get; set; } + public DbSet? PermissionGrants { get; set; } + public DbSet? ProjectMembers { get; set; } + public DbSet? AccessAuditEntries { get; set; } + public DbSet? RetentionPolicies { get; set; } + public DbSet? RetentionHolds { get; set; } + public DbSet? ArtifactUsages { get; set; } + public DbSet? ReplicationConfigs { get; set; } + public DbSet? ReplicationRuns { get; set; } + public DbSet? ReplicationItems { get; set; } + public DbSet? DataProtectionKeys { get; set; } + + public Task SaveChangesAsync() => SaveChangesAsync(default); + + public override int SaveChanges(bool acceptAllChangesOnSuccess) + { + StampRepository(); + return base.SaveChanges(acceptAllChangesOnSuccess); + } + + public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) + { + StampRepository(); + return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); + } + + // A new row without a repository belongs to the current one. A row that already names one (a database copy, + // an explicit move) is left alone. + private void StampRepository() { - public const int DefaultMaxStringLength = 4000; + foreach (var entry in ChangeTracker.Entries().Where(e => e.State == EntityState.Added)) + { + if (entry.Entity.RepositoryKey == 0) entry.Entity.RepositoryKey = CurrentRepositoryKey; + } + } - public const int MaxPackageIdLength = 128; - public const int MaxPackageVersionLength = 64; - public const int MaxPackageMinClientVersionLength = 44; - public const int MaxPackageLanguageLength = 20; - public const int MaxPackageTitleLength = 256; - public const int MaxPackageTypeNameLength = 512; - public const int MaxPackageTypeVersionLength = 64; - public const int MaxRepositoryTypeLength = 100; - public const int MaxTargetFrameworkLength = 256; + public virtual async Task RunMigrationsAsync(CancellationToken cancellationToken) + => await Database.MigrateAsync(cancellationToken); - public const int MaxPackageDependencyVersionRangeLength = 256; + /// + /// Does nothing by default: SQLite and MySQL advance their auto-increment counter from explicit keys. + public virtual Task BeginKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken) + => Task.CompletedTask; - public AbstractContext(DbContextOptions options) - : base(options) - { } + /// + /// Does nothing by default: SQLite and MySQL advance their auto-increment counter from explicit keys. + public virtual Task EndKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken) + => Task.CompletedTask; - public DbSet Packages { get; set; } - public DbSet PackageDependencies { get; set; } - public DbSet PackageTypes { get; set; } - public DbSet TargetFrameworks { get; set; } + public abstract bool IsUniqueConstraintViolationException(DbUpdateException exception); - public Task SaveChangesAsync() => SaveChangesAsync(default); + public virtual bool SupportsLimitInSubqueries => true; - public virtual async Task RunMigrationsAsync(CancellationToken cancellationToken) - => await Database.MigrateAsync(cancellationToken); + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + // Identity's tables lose the AspNet prefix (migration RenameAspNetTables). + builder.Entity().ToTable("Users"); + builder.Entity().ToTable("Roles"); + builder.Entity>().ToTable("UserRoles"); + builder.Entity>().ToTable("UserClaims"); + builder.Entity>().ToTable("UserLogins"); + builder.Entity>().ToTable("UserTokens"); + builder.Entity>().ToTable("RoleClaims"); + + builder.Entity(BuildPackageEntity); + builder.Entity(BuildPackageDependencyEntity); + builder.Entity(BuildPackageTypeEntity); + builder.Entity(BuildTargetFrameworkEntity); + builder.Entity(BuildPackageDeprecationEntity); + builder.Entity(BuildPackageVulnerabilityEntity); + builder.Entity(BuildCatalogEntryEntity); + builder.Entity(BuildOrganizationEntity); + builder.Entity(BuildOrganizationMemberEntity); + builder.Entity(BuildPackageOwnerEntity); + builder.Entity(BuildApiKeyEntity); + builder.Entity(BuildApiKeyRepositoryEntity); + builder.Entity(BuildPackageValidationEntity); + builder.Entity(BuildAbuseReportEntity); + builder.Entity(BuildPackageSymbolEntity); + builder.Entity(BuildScanResultEntity); + builder.Entity(BuildScanFindingEntity); + builder.Entity(BuildScanPolicyEntity); + builder.Entity(BuildNpmPackageEntity); + builder.Entity(BuildNpmVersionEntity); + builder.Entity(BuildNpmDistTagEntity); + builder.Entity(BuildMavenArtifactEntity); + builder.Entity(BuildMavenVersionEntity); + builder.Entity(BuildMavenFileEntity); + builder.Entity(BuildOciRepositoryEntity); + builder.Entity(BuildOciManifestEntity); + builder.Entity(BuildOciTagEntity); + builder.Entity(BuildOciBlobEntity); + builder.Entity(BuildOciBlobLinkEntity); + builder.Entity(BuildOciUploadEntity); + builder.Entity(BuildRepositoryEntity); + builder.Entity(BuildProjectEntity); + builder.Entity(BuildGroupEntity); + builder.Entity(BuildGroupMemberEntity); + builder.Entity(BuildPermissionTargetEntity); + builder.Entity(BuildPermissionGrantEntity); + builder.Entity(BuildProjectMemberEntity); + builder.Entity(BuildAccessAuditEntryEntity); + builder.Entity(BuildRetentionPolicyEntity); + builder.Entity(BuildRetentionHoldEntity); + builder.Entity(BuildArtifactUsageEntity); + builder.Entity(BuildReplicationConfigEntity); + builder.Entity(BuildReplicationRunEntity); + builder.Entity(BuildReplicationItemEntity); + builder.Entity(key => + { + key.HasKey(k => k.Key); + key.Property(k => k.FriendlyName).HasMaxLength(DataProtectionKeyEntry.MaxNameLength); + }); + + // Repository isolation: a query in one repository never sees another's rows. The filter reads the + // context's current repository per query. + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + builder.Entity().HasQueryFilter(e => e.RepositoryKey == CurrentRepositoryKey); + + // The column default is what the upgrade migration gives every row that predates repositories: they + // belong to the default repository. + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + builder.Entity().Property(e => e.RepositoryKey).HasDefaultValue(Repository.DefaultKey); + + BuildOwnershipForeignKeys(builder); + } - public abstract bool IsUniqueConstraintViolationException(DbUpdateException exception); + /// Entities whose RepositoryKey is a required foreign key to . + internal static readonly Type[] RepositoryOwned = + { + typeof(Package), typeof(PackageOwner), typeof(CatalogEntry), typeof(PackageValidation), typeof(AbuseReport), + typeof(PackageSymbol), typeof(NpmPackage), typeof(MavenArtifact), typeof(OciRepository), typeof(OciBlob), + typeof(ScanResult), typeof(RetentionHold), typeof(ArtifactUsage), typeof(ApiKeyRepository), typeof(ReplicationConfig), + }; + + /// Entities whose nullable RepositoryKey is an optional foreign key to . + internal static readonly Type[] RepositoryOptional = { typeof(RetentionPolicy), typeof(ScanPolicy) }; + + /// Entities whose nullable ProjectKey is an optional foreign key to . + internal static readonly Type[] ProjectOptional = { typeof(Repository), typeof(PermissionTarget), typeof(RetentionPolicy), typeof(ScanPolicy) }; + + /// Entities whose UserId is a required foreign key to the Identity users table. + internal static readonly Type[] UserOwned = { typeof(ApiKey), typeof(GroupMember), typeof(OrganizationMember) }; + + // The foreign keys that tie a row to its repository, project, user or replication configuration. They are all Restrict and + // have no navigation property (the entities are public API): the application deletes the owned rows itself, in order + // (RepositoryAdministration, AccountDeletionService, ...), and the database refuses a parent that still has children. + // The upgrade migration (AddOwnershipForeignKeys) deletes the rows that already pointed at nothing before adding them. + // PermissionGrant/ProjectMember.PrincipalId is polymorphic (user or group, by PrincipalType), so it has none. + private static void BuildOwnershipForeignKeys(ModelBuilder builder) + { + foreach (var type in RepositoryOwned) + { + builder.Entity(type).HasOne(typeof(Repository)).WithMany().HasForeignKey("RepositoryKey").IsRequired().OnDelete(DeleteBehavior.Restrict); + } - public virtual bool SupportsLimitInSubqueries => true; + foreach (var type in RepositoryOptional) + { + builder.Entity(type).HasOne(typeof(Repository)).WithMany().HasForeignKey("RepositoryKey").IsRequired(false).OnDelete(DeleteBehavior.Restrict); + } - protected override void OnModelCreating(ModelBuilder builder) + foreach (var type in ProjectOptional) { - builder.Entity(BuildPackageEntity); - builder.Entity(BuildPackageDependencyEntity); - builder.Entity(BuildPackageTypeEntity); - builder.Entity(BuildTargetFrameworkEntity); + builder.Entity(type).HasOne(typeof(Project)).WithMany().HasForeignKey("ProjectKey").IsRequired(false).OnDelete(DeleteBehavior.Restrict); } - private void BuildPackageEntity(EntityTypeBuilder package) + foreach (var type in UserOwned) { - package.HasKey(p => p.Key); - package.HasIndex(p => p.Id); - package.HasIndex(p => new { p.Id, p.NormalizedVersionString }) - .IsUnique(); + builder.Entity(type).HasOne(typeof(BaGetUser)).WithMany().HasForeignKey("UserId").IsRequired().OnDelete(DeleteBehavior.Restrict); + } + + builder.Entity().HasOne().WithMany().HasForeignKey(r => r.ConfigKey).IsRequired().OnDelete(DeleteBehavior.Restrict); + builder.Entity().HasOne().WithMany().HasForeignKey(i => i.ConfigKey).IsRequired().OnDelete(DeleteBehavior.Restrict); + // NoAction, not Restrict: deleting an image cascades to its manifests and from them to the tags, and a tag also points at the + // image, so the check has to wait for the end of the statement (PostgreSQL's RESTRICT is immediate). The code deletes the tags first anyway. + builder.Entity().HasOne().WithMany().HasForeignKey(t => t.ImageKey).IsRequired().OnDelete(DeleteBehavior.NoAction); + } - package.Property(p => p.Id) - .HasMaxLength(MaxPackageIdLength) - .IsRequired(); + private void BuildRetentionPolicyEntity(EntityTypeBuilder policy) + { + policy.HasKey(p => p.Key); + policy.HasIndex(p => p.Name).IsUnique(); + policy.HasIndex(p => p.RepositoryKey); + policy.HasIndex(p => p.ProjectKey); + + policy.Property(p => p.Name).HasMaxLength(MaxAccessNameLength).IsRequired(); + policy.Property(p => p.NamePatterns).HasMaxLength(MaxRetentionPatternsLength); + policy.Property(p => p.LastResult).HasMaxLength(MaxRetentionResultLength); + policy.Property(p => p.UnusedSince); + } - package.Property(p => p.NormalizedVersionString) - .HasColumnName("Version") - .HasMaxLength(MaxPackageVersionLength) - .IsRequired(); + private void BuildRetentionHoldEntity(EntityTypeBuilder hold) + { + hold.HasKey(h => h.Key); + hold.HasIndex(h => new { h.RepositoryKey, h.Name, h.Version }).IsUnique(); + + hold.Property(h => h.Name).HasMaxLength(MaxRetentionNameLength).IsRequired(); + // Empty = every version, so the column is never null (a unique index treats nulls as distinct on some engines). + hold.Property(h => h.Version).HasMaxLength(MaxRetentionVersionLength).IsRequired(); + hold.Property(h => h.Reason).HasMaxLength(MaxRetentionReasonLength); + hold.Property(h => h.CreatedBy).HasMaxLength(MaxAccountNameLength); + } - package.Property(p => p.OriginalVersionString) - .HasColumnName("OriginalVersion") - .HasMaxLength(MaxPackageVersionLength); + private void BuildReplicationConfigEntity(EntityTypeBuilder config) + { + config.HasKey(c => c.Key); + config.HasIndex(c => c.Name).IsUnique(); + config.HasIndex(c => c.RepositoryKey); + + config.Property(c => c.Name).HasMaxLength(MaxAccessNameLength).IsRequired(); + config.Property(c => c.PeerUrl).HasMaxLength(ReplicationLimits.MaxUrlLength).IsRequired(); + config.Property(c => c.PeerRepository).HasMaxLength(ReplicationLimits.MaxPartLength).IsRequired(); + config.Property(c => c.ProtectedApiKey).HasMaxLength(ReplicationLimits.MaxSecretLength); + config.Property(c => c.LastResult).HasMaxLength(ReplicationLimits.MaxResultLength); + config.Property(c => c.Direction).HasConversion(); + config.Property(c => c.Conflict).HasConversion(); + } - package.Property(p => p.ReleaseNotes) - .HasColumnName("ReleaseNotes"); + private void BuildReplicationRunEntity(EntityTypeBuilder run) + { + run.HasKey(r => r.Key); + run.HasIndex(r => new { r.ConfigKey, r.Started }); + + run.Property(r => r.Trigger).HasMaxLength(32); + run.Property(r => r.Actor).HasMaxLength(MaxAccountNameLength); + run.Property(r => r.Error).HasMaxLength(ReplicationLimits.MaxResultLength); + run.Property(r => r.Detail).HasMaxLength(ReplicationLimits.MaxDetailLength); + run.Property(r => r.Status).HasConversion(); + } - package.Property(p => p.Authors) - .HasMaxLength(DefaultMaxStringLength) - .HasConversion(StringArrayToJsonConverter.Instance) - .Metadata.SetValueComparer(StringArrayComparer.Instance); + private void BuildReplicationItemEntity(EntityTypeBuilder item) + { + item.HasKey(i => i.Key); + // Not unique: names compare differently per engine collation (a Docker tag is case-sensitive), the ledger is kept unique by the engine. + item.HasIndex(i => new { i.ConfigKey, i.Name, i.Version, i.Part }); + + item.Property(i => i.Name).HasMaxLength(ReplicationLimits.MaxNameLength).IsRequired(); + item.Property(i => i.Version).HasMaxLength(ReplicationLimits.MaxVersionLength).IsRequired(); + // Empty = not a Maven file, so the column is never null (a unique index treats nulls as distinct on some engines). + item.Property(i => i.Part).HasMaxLength(ReplicationLimits.MaxPartLength).IsRequired(); + item.Property(i => i.Digest).HasMaxLength(ReplicationLimits.MaxDigestLength); + } + + private void BuildArtifactUsageEntity(EntityTypeBuilder usage) + { + usage.HasKey(u => u.Key); + usage.HasIndex(u => new { u.RepositoryKey, u.Name, u.Version }).IsUnique(); + + usage.Property(u => u.Name).HasMaxLength(MaxRetentionNameLength).IsRequired(); + usage.Property(u => u.Version).HasMaxLength(MaxRetentionVersionLength).IsRequired(); + } + + private void BuildScanResultEntity(EntityTypeBuilder result) + { + result.HasKey(r => r.Key); + result.HasIndex(r => new { r.RepositoryKey, r.Name, r.Version }).IsUnique(); + + result.Property(r => r.Name).HasMaxLength(MaxScanNameLength).IsRequired(); + result.Property(r => r.Version).HasMaxLength(MaxScanVersionLength).IsRequired(); + result.Property(r => r.Scanner).HasMaxLength(MaxScanScannerLength).IsRequired(); + result.Property(r => r.Error).HasMaxLength(MaxScanErrorLength); + + result.HasMany(r => r.Findings).WithOne().HasForeignKey(f => f.ResultKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildScanFindingEntity(EntityTypeBuilder finding) + { + finding.HasKey(f => f.Key); + finding.HasIndex(f => f.ResultKey); + + finding.Property(f => f.VulnerabilityId).HasMaxLength(MaxScanIdLength).IsRequired(); + finding.Property(f => f.Component).HasMaxLength(MaxScanNameLength).IsRequired(); + finding.Property(f => f.ComponentVersion).HasMaxLength(MaxScanVersionLength).IsRequired(); + finding.Property(f => f.Summary).HasMaxLength(MaxScanSummaryLength); + finding.Property(f => f.AdvisoryUrl).HasMaxLength(MaxScanUrlLength); + finding.Property(f => f.FixedVersion).HasMaxLength(MaxScanVersionLength); + } + + private void BuildScanPolicyEntity(EntityTypeBuilder policy) + { + policy.HasKey(p => p.Key); + // One policy per repository and one per project; separate indexes because a unique index over two nullable columns + // would not constrain the rows where the other one is null on every provider. + policy.HasIndex(p => p.RepositoryKey).IsUnique(); + policy.HasIndex(p => p.ProjectKey).IsUnique(); + + policy.Property(p => p.ModifiedBy).HasMaxLength(MaxAccountNameLength); + } + + private void BuildNpmPackageEntity(EntityTypeBuilder package) + { + package.HasKey(p => p.Key); + package.HasIndex(p => new { p.RepositoryKey, p.Name }).IsUnique(); + + package.Property(p => p.Name).HasMaxLength(MaxNpmNameLength).IsRequired(); + } + + private void BuildNpmVersionEntity(EntityTypeBuilder version) + { + version.HasKey(v => v.Key); + version.HasIndex(v => new { v.PackageKey, v.Version }).IsUnique(); + + version.Property(v => v.Version).HasMaxLength(MaxNpmVersionLength).IsRequired(); + version.Property(v => v.Integrity).HasMaxLength(MaxNpmIntegrityLength).IsRequired(); + version.Property(v => v.Shasum).HasMaxLength(MaxNpmShasumLength).IsRequired(); + version.Property(v => v.Manifest).IsRequired(); + + // New tables, so the cascade is safe to declare here (unlike the older optional relationships). + version.HasOne().WithMany().HasForeignKey(v => v.PackageKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildNpmDistTagEntity(EntityTypeBuilder tag) + { + tag.HasKey(t => t.Key); + tag.HasIndex(t => new { t.PackageKey, t.Tag }).IsUnique(); + + tag.Property(t => t.Tag).HasMaxLength(MaxNpmTagLength).IsRequired(); + tag.Property(t => t.Version).HasMaxLength(MaxNpmVersionLength).IsRequired(); + + tag.HasOne().WithMany().HasForeignKey(t => t.PackageKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildMavenArtifactEntity(EntityTypeBuilder artifact) + { + artifact.HasKey(a => a.Key); + artifact.HasIndex(a => new { a.RepositoryKey, a.GroupId, a.ArtifactId }).IsUnique(); + + artifact.Property(a => a.GroupId).HasMaxLength(MaxMavenGroupLength).IsRequired(); + artifact.Property(a => a.ArtifactId).HasMaxLength(MaxMavenArtifactLength).IsRequired(); + } - package.Property(p => p.IconUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); + private void BuildMavenVersionEntity(EntityTypeBuilder version) + { + version.HasKey(v => v.Key); + version.HasIndex(v => new { v.ArtifactKey, v.Version }).IsUnique(); + + version.Property(v => v.Version).HasMaxLength(MaxMavenVersionLength).IsRequired(); + version.Property(v => v.Name).HasMaxLength(MaxMavenNameLength); + version.Property(v => v.Description).HasMaxLength(MaxMavenDescriptionLength); + version.Property(v => v.Packaging).HasMaxLength(MaxMavenPackagingLength); + + version.HasOne().WithMany().HasForeignKey(v => v.ArtifactKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildMavenFileEntity(EntityTypeBuilder file) + { + file.HasKey(f => f.Key); + file.HasIndex(f => new { f.VersionKey, f.FileName }).IsUnique(); + + file.Property(f => f.FileName).HasMaxLength(MaxMavenFileNameLength).IsRequired(); + file.Property(f => f.Classifier).HasMaxLength(MaxMavenClassifierLength); + file.Property(f => f.Extension).HasMaxLength(MaxMavenExtensionLength).IsRequired(); + file.Property(f => f.SnapshotTimestamp).HasMaxLength(MaxMavenSnapshotTimestampLength); + file.Property(f => f.Sha1).HasMaxLength(40).IsRequired(); + file.Property(f => f.Md5).HasMaxLength(32).IsRequired(); + file.Property(f => f.Sha256).HasMaxLength(64).IsRequired(); + file.Property(f => f.Sha512).HasMaxLength(MaxMavenChecksumLength).IsRequired(); + + file.HasOne().WithMany().HasForeignKey(f => f.VersionKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildOciRepositoryEntity(EntityTypeBuilder image) + { + image.HasKey(i => i.Key); + image.HasIndex(i => new { i.RepositoryKey, i.Name }).IsUnique(); + + image.Property(i => i.Name).HasMaxLength(MaxOciImageLength).IsRequired(); + } + + private void BuildOciManifestEntity(EntityTypeBuilder manifest) + { + manifest.HasKey(m => m.Key); + manifest.HasIndex(m => new { m.ImageKey, m.Digest }).IsUnique(); + manifest.HasIndex(m => new { m.ImageKey, m.SubjectDigest }); + + manifest.Property(m => m.Digest).HasMaxLength(MaxOciDigestLength).IsRequired(); + manifest.Property(m => m.MediaType).HasMaxLength(MaxOciMediaTypeLength).IsRequired(); + manifest.Property(m => m.ArtifactType).HasMaxLength(MaxOciMediaTypeLength); + manifest.Property(m => m.SubjectDigest).HasMaxLength(MaxOciDigestLength); + // The pushed bytes, unbounded text on every provider (a manifest is at most Oci:MaxManifestBytes). + manifest.Property(m => m.Content).IsRequired(); + + manifest.HasOne().WithMany().HasForeignKey(m => m.ImageKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildOciTagEntity(EntityTypeBuilder tag) + { + tag.HasKey(t => t.Key); + tag.HasIndex(t => new { t.ImageKey, t.Name }).IsUnique(); + tag.HasIndex(t => t.ManifestKey); + + tag.Property(t => t.Name).HasMaxLength(MaxOciTagLength).IsRequired(); + + // The image is a NoAction foreign key (BuildOwnershipForeignKeys): deleting an image reaches its tags through its manifests + // (one cascade path, which SQL Server requires). + tag.HasOne().WithMany().HasForeignKey(t => t.ManifestKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } - package.Property(p => p.LicenseUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); + private void BuildOciBlobEntity(EntityTypeBuilder blob) + { + blob.HasKey(b => b.Key); + blob.HasIndex(b => new { b.RepositoryKey, b.Digest }).IsUnique(); - package.Property(p => p.ProjectUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); + blob.Property(b => b.Digest).HasMaxLength(MaxOciDigestLength).IsRequired(); + } - package.Property(p => p.RepositoryUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); + private void BuildOciBlobLinkEntity(EntityTypeBuilder link) + { + link.HasKey(l => l.Key); + link.HasIndex(l => new { l.ImageKey, l.BlobKey }).IsUnique(); + link.HasIndex(l => l.BlobKey); + + // Deleting an image deletes its links; the blob side restricts (a blob row is removed only after its links, in code), + // since two cascade paths to one table are refused by SQL Server. + link.HasOne().WithMany().HasForeignKey(l => l.ImageKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + link.HasOne().WithMany().HasForeignKey(l => l.BlobKey).IsRequired().OnDelete(DeleteBehavior.Restrict); + } - package.Property(p => p.Tags) + private void BuildOciUploadEntity(EntityTypeBuilder upload) + { + upload.HasKey(u => u.Key); + upload.HasIndex(u => u.Reference).IsUnique(); + upload.HasIndex(u => u.ImageKey); + + upload.Property(u => u.Reference).HasMaxLength(MaxOciUploadReferenceLength).IsRequired(); + upload.Property(u => u.StorageUploadId).HasMaxLength(MaxOciStorageUploadIdLength).IsRequired(); + + upload.HasOne().WithMany().HasForeignKey(u => u.ImageKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildRepositoryEntity(EntityTypeBuilder repository) + { + repository.HasKey(r => r.Key); + repository.HasIndex(r => r.Name).IsUnique(); + + repository.Property(r => r.Name).HasMaxLength(MaxRepositoryNameLength).IsRequired(); + repository.Property(r => r.Format).HasConversion().HasMaxLength(MaxRepositoryFormatLength); + repository.Property(r => r.Kind).HasConversion().HasMaxLength(MaxRepositoryFormatLength); + } + + private void BuildGroupEntity(EntityTypeBuilder group) + { + group.HasKey(g => g.Key); + group.HasIndex(g => g.Name).IsUnique(); + + group.Property(g => g.Name).HasMaxLength(MaxAccessNameLength).IsRequired(); + group.Property(g => g.Description).HasMaxLength(MaxAccessDescriptionLength); + } + + private void BuildGroupMemberEntity(EntityTypeBuilder member) + { + member.HasKey(m => m.Key); + member.HasIndex(m => new { m.GroupKey, m.UserId }).IsUnique(); + member.HasIndex(m => m.UserId); + + member.Property(m => m.UserId).HasMaxLength(MaxUserIdLength).IsRequired(); + + // A new table, so the cascade is safe to declare here (unlike the older optional relationships). + member.HasOne(m => m.Group).WithMany().HasForeignKey(m => m.GroupKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildPermissionTargetEntity(EntityTypeBuilder target) + { + target.HasKey(t => t.Key); + target.HasIndex(t => t.Name).IsUnique(); + + target.Property(t => t.Name).HasMaxLength(MaxAccessNameLength).IsRequired(); + + #pragma warning disable CS8620 + foreach (var patterns in new[] { target.Property(t => t.RepositoryPatterns), target.Property(t => t.IncludePatterns), target.Property(t => t.ExcludePatterns) }) + { + patterns .HasMaxLength(DefaultMaxStringLength) .HasConversion(StringArrayToJsonConverter.Instance) .Metadata.SetValueComparer(StringArrayComparer.Instance); - - package.Property(p => p.Description).HasMaxLength(DefaultMaxStringLength); - package.Property(p => p.Language).HasMaxLength(MaxPackageLanguageLength); - package.Property(p => p.MinClientVersion).HasMaxLength(MaxPackageMinClientVersionLength); - package.Property(p => p.Summary).HasMaxLength(DefaultMaxStringLength); - package.Property(p => p.Title).HasMaxLength(MaxPackageTitleLength); - package.Property(p => p.RepositoryType).HasMaxLength(MaxRepositoryTypeLength); - - package.Ignore(p => p.Version); - package.Ignore(p => p.IconUrlString); - package.Ignore(p => p.LicenseUrlString); - package.Ignore(p => p.ProjectUrlString); - package.Ignore(p => p.RepositoryUrlString); - - // TODO: This is needed to make the dependency to package relationship required. - // Unfortunately, this would generate a migration that drops a foreign key, which - // isn't supported by SQLite. The migrations will be need to be recreated for this. - // Consumers will need to recreate their database and reindex all their packages. - // To make this transition easier, I'd like to finish this change: - // https://github.com/loic-sharma/BaGet/pull/174 - //package.HasMany(p => p.Dependencies) - // .WithOne(d => d.Package) - // .IsRequired(); - - package.HasMany(p => p.PackageTypes) - .WithOne(d => d.Package) - .IsRequired(); - - package.HasMany(p => p.TargetFrameworks) - .WithOne(d => d.Package) - .IsRequired(); - - package.Property(p => p.RowVersion).IsRowVersion(); } + #pragma warning restore CS8620 + } - private void BuildPackageDependencyEntity(EntityTypeBuilder dependency) - { - dependency.HasKey(d => d.Key); - dependency.HasIndex(d => d.Id); + private void BuildPermissionGrantEntity(EntityTypeBuilder grant) + { + grant.HasKey(g => g.Key); + grant.HasIndex(g => new { g.TargetKey, g.PrincipalType, g.PrincipalId }).IsUnique(); - dependency.Property(d => d.Id).HasMaxLength(MaxPackageIdLength); - dependency.Property(d => d.VersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); - dependency.Property(d => d.TargetFramework).HasMaxLength(MaxTargetFrameworkLength); - } + grant.Property(g => g.PrincipalType).HasConversion().HasMaxLength(MaxPrincipalTypeLength); + grant.Property(g => g.PrincipalId).HasMaxLength(MaxUserIdLength).IsRequired(); - private void BuildPackageTypeEntity(EntityTypeBuilder type) - { - type.HasKey(d => d.Key); - type.HasIndex(d => d.Name); + grant.HasOne(g => g.Target).WithMany().HasForeignKey(g => g.TargetKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } - type.Property(d => d.Name).HasMaxLength(MaxPackageTypeNameLength); - type.Property(d => d.Version).HasMaxLength(MaxPackageTypeVersionLength); - } + private void BuildProjectMemberEntity(EntityTypeBuilder member) + { + member.HasKey(m => m.Key); + member.HasIndex(m => new { m.ProjectKey, m.PrincipalType, m.PrincipalId }).IsUnique(); - private void BuildTargetFrameworkEntity(EntityTypeBuilder targetFramework) - { - targetFramework.HasKey(f => f.Key); - targetFramework.HasIndex(f => f.Moniker); + member.Property(m => m.PrincipalType).HasConversion().HasMaxLength(MaxPrincipalTypeLength); + member.Property(m => m.PrincipalId).HasMaxLength(MaxUserIdLength).IsRequired(); + member.Property(m => m.Role).HasConversion().HasMaxLength(MaxPrincipalTypeLength); - targetFramework.Property(f => f.Moniker).HasMaxLength(MaxTargetFrameworkLength); - } + member.HasOne(m => m.Project).WithMany().HasForeignKey(m => m.ProjectKey).IsRequired().OnDelete(DeleteBehavior.Cascade); + } + + private void BuildAccessAuditEntryEntity(EntityTypeBuilder entry) + { + entry.HasKey(e => e.Key); + entry.HasIndex(e => e.Created); + + entry.Property(e => e.Actor).HasMaxLength(MaxAccountNameLength); + entry.Property(e => e.Action).HasMaxLength(MaxAuditActionLength).IsRequired(); + entry.Property(e => e.Subject).HasMaxLength(MaxAccountNameLength); + entry.Property(e => e.Details).HasMaxLength(DefaultMaxStringLength); + } + + private void BuildProjectEntity(EntityTypeBuilder project) + { + project.HasKey(p => p.Key); + project.HasIndex(p => p.Name).IsUnique(); + + project.Property(p => p.Name).HasMaxLength(MaxProjectNameLength).IsRequired(); + project.Property(p => p.DisplayName).HasMaxLength(MaxProjectDisplayNameLength); + } + + private void BuildPackageEntity(EntityTypeBuilder package) + { + package.HasKey(p => p.Key); + package.HasIndex(p => p.Id); + package.HasIndex(p => new { p.RepositoryKey, p.Id, p.NormalizedVersionString }) + .IsUnique(); + + package.Property(p => p.Id) + .HasMaxLength(MaxPackageIdLength) + .IsRequired(); + + package.Property(p => p.NormalizedVersionString) + .HasColumnName("Version") + .HasMaxLength(MaxPackageVersionLength) + .IsRequired(); + + package.Property(p => p.OriginalVersionString) + .HasColumnName("OriginalVersion") + .HasMaxLength(MaxPackageVersionLength); + + package.Property(p => p.ReleaseNotes) + .HasColumnName("ReleaseNotes"); + + #pragma warning disable CS8620 + package.Property(p => p.Authors) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + #pragma warning restore CS8620 + + #pragma warning disable CS8620 + package.Property(p => p.IconUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + #pragma warning restore CS8620 + + #pragma warning disable CS8620 + package.Property(p => p.LicenseUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + #pragma warning restore CS8620 + + #pragma warning disable CS8620 + package.Property(p => p.ProjectUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + #pragma warning restore CS8620 + + #pragma warning disable CS8620 + package.Property(p => p.RepositoryUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + #pragma warning restore CS8620 + + #pragma warning disable CS8620 + package.Property(p => p.Tags) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + #pragma warning restore CS8620 + + package.Property(p => p.Description).HasMaxLength(DefaultMaxStringLength); + package.Property(p => p.Language).HasMaxLength(MaxPackageLanguageLength); + package.Property(p => p.MinClientVersion).HasMaxLength(MaxPackageMinClientVersionLength); + package.Property(p => p.Summary).HasMaxLength(DefaultMaxStringLength); + package.Property(p => p.Title).HasMaxLength(MaxPackageTitleLength); + package.Property(p => p.RepositoryType).HasMaxLength(MaxRepositoryTypeLength); + + package.Ignore(p => p.Version); + package.Ignore(p => p.IconUrlString); + package.Ignore(p => p.LicenseUrlString); + package.Ignore(p => p.ProjectUrlString); + package.Ignore(p => p.RepositoryUrlString); + + // The dependency to package relationship is deliberately left optional. Making it + // required, or giving it a cascade delete, changes the foreign key and so needs a + // migration; SQLite cannot alter a foreign key, so consumers would have to + // recreate their database and reindex every package. PackageDatabase therefore + // deletes a package's dependency rows itself, so that none are left orphaned. + // See: https://github.com/loic-sharma/BaGet/pull/174 + + package.HasMany(p => p.PackageTypes) + .WithOne(d => d.Package) + .IsRequired(); + + package.HasMany(p => p.TargetFrameworks) + .WithOne(d => d.Package) + .IsRequired(); + + package.Property(p => p.RowVersion).IsRowVersion(); + } + + private void BuildPackageDeprecationEntity(EntityTypeBuilder deprecation) + { + deprecation.HasKey(d => d.Key); + + #pragma warning disable CS8620 + deprecation + .Property(d => d.Reasons) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + #pragma warning restore CS8620 + + deprecation.Property(d => d.Message).HasMaxLength(DefaultMaxStringLength); + deprecation.Property(d => d.AlternatePackageId).HasMaxLength(MaxPackageIdLength); + deprecation.Property(d => d.AlternateVersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); + + // A version has at most one deprecation. The relationship is optional in the + // database for the same reason as the dependency one: a required relationship + // would need a foreign key change, which SQLite cannot make in place. + // The foreign key is declared explicitly: for a one to one relationship EF + // cannot otherwise tell which side is the dependent. + deprecation + .HasOne(d => d.Package) + .WithOne(p => p.Deprecation) + .HasForeignKey(d => d.PackageKey) + .IsRequired(false); + } + + private void BuildPackageVulnerabilityEntity(EntityTypeBuilder vulnerability) + { + vulnerability.HasKey(v => v.Key); + + vulnerability.Property(v => v.AdvisoryUrl).HasMaxLength(DefaultMaxStringLength); + vulnerability.Property(v => v.VersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); + vulnerability.Property(v => v.Source).HasMaxLength(MaxScanScannerLength); + + vulnerability + .HasOne(v => v.Package) + .WithMany(p => p.Vulnerabilities) + .HasForeignKey(v => v.PackageKey) + .IsRequired(false); + } + + private void BuildCatalogEntryEntity(EntityTypeBuilder entry) + { + entry.HasKey(e => e.Key); + entry.HasIndex(e => e.CommitId).IsUnique(); + entry.HasIndex(e => e.RepositoryKey); + + entry.Property(e => e.CommitId).HasMaxLength(MaxCatalogCommitIdLength).IsRequired(); + entry.Property(e => e.Type).HasMaxLength(MaxCatalogTypeLength).IsRequired(); + entry.Property(e => e.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + entry.Property(e => e.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + } + + private void BuildOrganizationEntity(EntityTypeBuilder organization) + { + organization.HasKey(o => o.Key); + organization.HasIndex(o => o.Name).IsUnique(); + + organization.Property(o => o.Name).HasMaxLength(MaxAccountNameLength).IsRequired(); + } + + private void BuildOrganizationMemberEntity(EntityTypeBuilder member) + { + member.HasKey(m => m.Key); + member.HasIndex(m => m.UserId); + + member.Property(m => m.UserId).HasMaxLength(MaxUserIdLength).IsRequired(); + + member + .HasOne(m => m.Organization) + .WithMany() + .HasForeignKey(m => m.OrganizationKey) + .IsRequired(false); + } + + private void BuildPackageOwnerEntity(EntityTypeBuilder owner) + { + owner.HasKey(o => o.Key); + owner.HasIndex(o => new { o.RepositoryKey, o.PackageId }); + owner.HasIndex(o => o.OwnerName); + + owner.Property(o => o.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + owner.Property(o => o.OwnerName).HasMaxLength(MaxAccountNameLength).IsRequired(); + } + + private void BuildApiKeyEntity(EntityTypeBuilder apiKey) + { + apiKey.HasKey(k => k.Key); + apiKey.HasIndex(k => k.HashedKey).IsUnique(); + apiKey.HasIndex(k => k.UserId); + + apiKey.Property(k => k.UserId).HasMaxLength(MaxUserIdLength).IsRequired(); + apiKey.Property(k => k.Description).HasMaxLength(MaxApiKeyDescriptionLength); + apiKey.Property(k => k.HashedKey).HasMaxLength(MaxApiKeyHashLength).IsRequired(); + apiKey.Property(k => k.PackageGlobPattern).HasMaxLength(MaxPackageIdLength); + + #pragma warning disable CS8620 + apiKey + .Property(k => k.Scopes) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + #pragma warning restore CS8620 + } + + private void BuildApiKeyRepositoryEntity(EntityTypeBuilder row) + { + row.HasKey(r => r.Key); + row.HasIndex(r => new { r.ApiKeyKey, r.RepositoryKey }).IsUnique(); + row.HasIndex(r => r.RepositoryKey); + + // A revoked or deleted key takes its rows with it, in the database too. + row.HasOne(r => r.ApiKey).WithMany().HasForeignKey(r => r.ApiKeyKey).OnDelete(DeleteBehavior.Cascade); + } + + private void BuildPackageValidationEntity(EntityTypeBuilder validation) + { + validation.HasKey(v => v.Key); + validation.HasIndex(v => v.SubmissionId); + validation.HasIndex(v => new { v.RepositoryKey, v.PackageId }); + + validation.Property(v => v.SubmissionId).HasMaxLength(MaxCatalogCommitIdLength).IsRequired(); + validation.Property(v => v.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + validation.Property(v => v.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + validation.Property(v => v.Type).HasMaxLength(MaxValidationTypeLength).IsRequired(); + validation.Property(v => v.Message).HasMaxLength(DefaultMaxStringLength); + + validation + .HasOne(v => v.Package) + .WithMany() + .HasForeignKey(v => v.PackageKey) + .IsRequired(false); + } + + private void BuildAbuseReportEntity(EntityTypeBuilder report) + { + report.HasKey(r => r.Key); + report.HasIndex(r => new { r.RepositoryKey, r.PackageId }); + + report.Property(r => r.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + report.Property(r => r.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + report.Property(r => r.Reason).HasMaxLength(MaxAbuseReasonLength).IsRequired(); + report.Property(r => r.Details).HasMaxLength(DefaultMaxStringLength).IsRequired(); + report.Property(r => r.ReporterEmail).HasMaxLength(MaxEmailLength); + } + + private void BuildPackageSymbolEntity(EntityTypeBuilder symbol) + { + symbol.HasKey(s => s.Key); + symbol.HasIndex(s => new { s.RepositoryKey, s.PackageId, s.PackageVersion }); + symbol.HasIndex(s => new { s.RepositoryKey, s.FileName, s.SymbolKey }); + + symbol.Property(s => s.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + symbol.Property(s => s.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + symbol.Property(s => s.FileName).HasMaxLength(MaxPdbFileNameLength).IsRequired(); + symbol.Property(s => s.SymbolKey).HasMaxLength(MaxSymbolKeyLength).IsRequired(); + } + + private void BuildPackageDependencyEntity(EntityTypeBuilder dependency) + { + dependency.HasKey(d => d.Key); + dependency.HasIndex(d => d.Id); + + dependency.Property(d => d.Id).HasMaxLength(MaxPackageIdLength); + dependency.Property(d => d.VersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); + dependency.Property(d => d.TargetFramework).HasMaxLength(MaxTargetFrameworkLength); + } + + private void BuildPackageTypeEntity(EntityTypeBuilder type) + { + type.HasKey(d => d.Key); + type.HasIndex(d => d.Name); + + type.Property(d => d.Name).HasMaxLength(MaxPackageTypeNameLength); + type.Property(d => d.Version).HasMaxLength(MaxPackageTypeVersionLength); + } + + private void BuildTargetFrameworkEntity(EntityTypeBuilder targetFramework) + { + targetFramework.HasKey(f => f.Key); + targetFramework.HasIndex(f => f.Moniker); + + targetFramework.Property(f => f.Moniker).HasMaxLength(MaxTargetFrameworkLength); } } diff --git a/src/BaGet.Core/Entities/AbuseReport.cs b/src/BaGet.Core/Entities/AbuseReport.cs new file mode 100644 index 000000000..987505646 --- /dev/null +++ b/src/BaGet.Core/Entities/AbuseReport.cs @@ -0,0 +1,45 @@ +using System; + +namespace BaGet.Core; + +/// +/// A report that a package version is abusive, for its owners and the server's +/// administrator to act on. +/// +public class AbuseReport : IRepositoryScoped +{ + /// + /// The reasons a report may give, as nuget.org offers them. + /// + public static readonly string[] Reasons = + { + "Contains malicious code", + "Violates a license or copyright", + "Contains private or confidential data", + "Other", + }; + + public int Key { get; set; } + + /// + /// The owning repository; see . + /// + public int RepositoryKey { get; set; } + + public string? PackageId { get; set; } + + public string? PackageVersion { get; set; } + + public string? Reason { get; set; } + + public string? Details { get; set; } + + /// + /// Where to reply, if the reporter gave an address. + /// + public string? ReporterEmail { get; set; } + + public DateTime Created { get; set; } + + public DateTime? Resolved { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Accounts.cs b/src/BaGet.Core/Entities/Accounts.cs new file mode 100644 index 000000000..b93c74858 --- /dev/null +++ b/src/BaGet.Core/Entities/Accounts.cs @@ -0,0 +1,176 @@ +using System; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Core; + +/// +/// A signed in user. User names and organization names share one namespace, since +/// either can own a package. +/// +public class BaGetUser : IdentityUser +{ + public DateTime Created { get; set; } + + /// + /// May change the server's settings and promote or demote administrators. Holds every action of the access + /// model in every repository () and skips package ownership, but not the limits of the + /// API key in use: its scopes and package glob still apply (OwnershipAuthorizationService). + /// + public bool IsAdministrator { get; set; } + + /// + /// A self-registered account (Accounts:RequireApproval) that no administrator has enabled yet. It cannot + /// sign in by any route until the Users page approves it. False for every other account, so existing rows + /// need no data change. + /// + public bool PendingApproval { get; set; } +} + +/// +/// An account that several users own packages through. +/// +public class Organization +{ + public int Key { get; set; } + + public string? Name { get; set; } + + public DateTime Created { get; set; } +} + +public class OrganizationMember +{ + public int Key { get; set; } + + /// + /// Nullable so that the relationship is additive; see . + /// + public int? OrganizationKey { get; set; } + + public Organization? Organization { get; set; } + + /// + /// The member's . + /// + public string? UserId { get; set; } + + /// + /// An administrator can add and remove members. + /// + public bool IsAdmin { get; set; } +} + +/// +/// An owner of every version of a package ID. +/// +/// +/// A package ID with no owners predates accounts, and only the server's global API key +/// may change it. +/// +public class PackageOwner : IRepositoryScoped +{ + public int Key { get; set; } + + /// + /// The owning repository; see . + /// + public int RepositoryKey { get; set; } + + public string? PackageId { get; set; } + + /// + /// A user name or an organization name. + /// + public string? OwnerName { get; set; } + + /// + /// Set by the server's administrator to mark the ID as reserved for this owner, + /// which search reports as "verified". + /// + public bool IsVerified { get; set; } +} + +/// +/// A user's API key. Only a hash of the key is kept. +/// +public class ApiKey +{ + public int Key { get; set; } + + public string? UserId { get; set; } + + public string? Description { get; set; } + + /// + /// The key's SHA-256 hash, as lowercase hex. + /// + public string? HashedKey { get; set; } + + /// + /// What the key may do; see . + /// + public string[]? Scopes { get; set; } + + /// + /// The package IDs the key applies to, with "*" as a wildcard. + /// + public string? PackageGlobPattern { get; set; } + + public DateTime Created { get; set; } + + public DateTime? Expires { get; set; } +} + +/// +/// Limits an to one repository. A key with no rows may be used in every repository (as every key +/// could before this table existed); a key with rows only in the listed ones: its effective rights are the key's scopes +/// and package glob, intersected with these repositories and with what its user may do there +/// (). Rows go with their key (cascade) and with their repository +/// (, which also deletes a key left scoped to nothing). +/// +public class ApiKeyRepository +{ + public int Key { get; set; } + + /// The this row limits. + public int ApiKeyKey { get; set; } + + public ApiKey? ApiKey { get; set; } + + /// The the key may be used in. A Restrict foreign key, like . + public int RepositoryKey { get; set; } +} + +/// +/// The scopes an may hold, named as nuget.org names them. +/// +public static class ApiKeyScopes +{ + /// + /// Push new package IDs and new versions of owned ones. + /// + public const string Push = "package:push"; + + /// + /// Push new versions of owned package IDs only. + /// + public const string PushVersion = "package:pushversion"; + + /// + /// Unlist and relist owned versions, and edit their deprecation and vulnerabilities. + /// + public const string Unlist = "package:unlist"; + + /// + /// Call the administration REST API (/api/v1). Only a key of an administrator can carry it (the service refuses it + /// for anyone else, and the API checks the owner is still an administrator on every call). It is deliberately not in + /// : sessions and npm tokens get , and must never administer the server. + /// + public const string Admin = "admin:api"; + + /// The package scopes: what a session, an npm token and an ordinary key carry. + public static readonly string[] All = { Push, PushVersion, Unlist }; + + /// Every scope a key can be created with: and (administrators only). + public static readonly string[] Assignable = { Push, PushVersion, Unlist, Admin }; +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/CatalogEntry.cs b/src/BaGet.Core/Entities/CatalogEntry.cs new file mode 100644 index 000000000..8389a90d7 --- /dev/null +++ b/src/BaGet.Core/Entities/CatalogEntry.cs @@ -0,0 +1,47 @@ +using System; + +namespace BaGet.Core; + +/// +/// One entry in the append-only catalog log: a package version was added or changed, +/// or was deleted. +/// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource +/// +/// +/// There is deliberately no foreign key to : the log outlives the +/// packages it records, and a delete entry refers to a package that no longer exists. +/// +public class CatalogEntry : IRepositoryScoped +{ + public const string PackageDetailsType = "PackageDetails"; + public const string PackageDeleteType = "PackageDelete"; + + public int Key { get; set; } + + /// + /// The owning repository; see . + /// + public int RepositoryKey { get; set; } + + /// + /// The commit's unique ID. It also names the leaf document in storage. + /// + public string? CommitId { get; set; } + + /// + /// When the entry was committed, in UTC. Strictly increasing in commit order. + /// + public DateTime CommitTimestamp { get; set; } + + /// + /// or . + /// + public string? Type { get; set; } + + public string? PackageId { get; set; } + + /// + /// The normalized version. + /// + public string? PackageVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs b/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs index e76bcc626..2dbf38e4a 100644 --- a/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs +++ b/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs @@ -2,18 +2,17 @@ using System.Linq; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace BaGet.Core +namespace BaGet.Core; + +public class StringArrayComparer : ValueComparer { - public class StringArrayComparer : ValueComparer - { - public static readonly StringArrayComparer Instance = new StringArrayComparer(); + public static readonly StringArrayComparer Instance = new(); - public StringArrayComparer() - : base( - (c1, c2) => c1.SequenceEqual(c2), - c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), - c => c.ToArray()) - { - } + public StringArrayComparer() + : base( + (c1, c2) => c1.SequenceEqual(c2), + c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), + c => c.ToArray()) + { } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs b/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs index 0991d1c3c..73a9256e5 100644 --- a/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs +++ b/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs @@ -1,17 +1,18 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Newtonsoft.Json; -namespace BaGet.Core +namespace BaGet.Core; + +public class StringArrayToJsonConverter : ValueConverter { - public class StringArrayToJsonConverter : ValueConverter - { - public static readonly StringArrayToJsonConverter Instance = new StringArrayToJsonConverter(); + public static readonly StringArrayToJsonConverter? Instance = new(); - public StringArrayToJsonConverter() - : base( - v => JsonConvert.SerializeObject(v), - v => (!string.IsNullOrEmpty(v)) ? JsonConvert.DeserializeObject(v) : new string[0]) - { - } + #pragma warning disable CS8603 + public StringArrayToJsonConverter() + : base( + v => JsonConvert.SerializeObject(v), + v => (!string.IsNullOrEmpty(v)) ? JsonConvert.DeserializeObject(v) : new string[0]) + #pragma warning restore CS8603 + { } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs b/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs index d8ace4a68..301fdd664 100644 --- a/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs +++ b/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs @@ -1,17 +1,16 @@ using System; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -namespace BaGet.Core +namespace BaGet.Core; + +public class UriToStringConverter : ValueConverter { - public class UriToStringConverter : ValueConverter - { - public static readonly UriToStringConverter Instance = new UriToStringConverter(); + public static readonly UriToStringConverter? Instance = new(); - public UriToStringConverter() - : base( - v => v.AbsoluteUri, - v => new Uri(v)) - { - } + public UriToStringConverter() + : base( + v => v.AbsoluteUri, + v => new Uri(v)) + { } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Copy/DatabaseCopyModels.cs b/src/BaGet.Core/Entities/Copy/DatabaseCopyModels.cs new file mode 100644 index 000000000..4bcdafd8c --- /dev/null +++ b/src/BaGet.Core/Entities/Copy/DatabaseCopyModels.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// What a database copy needs: the target and the settings to save once the copy is verified. +/// +/// The target's Database:Type (a relational one). +/// The target's connection string. Never logged or shown. +/// The target's Database:MySqlServerVersion, or null. +/// +/// The settings to save, through , after the copy is verified +/// (Database:Type, Database:ConnectionString and anything else posted with them). +/// +/// Who asked, for the audit log. +public sealed record DatabaseCopyRequest( + string TargetType, + string TargetConnectionString, + string? MySqlServerVersion, + IReadOnlyDictionary SettingChanges, + string? Actor); + +/// The stage a database copy is in. +public enum DatabaseCopyPhase +{ + /// No copy has been requested since startup. + Idle, + + /// Accepted, waiting for the worker. + Queued, + + /// Connecting to the target and checking the source. + Checking, + + /// Creating or upgrading the target's schema. + Migrating, + + /// Copying rows. + Copying, + + /// Comparing row counts and key checksums. + Verifying, + + /// Saving the new database settings. + SavingSettings, + + /// Removing the rows copied so far, after a failure. + RollingBack, + + /// Done; the settings are saved and a restart is needed. + Succeeded, + + /// Failed; the source is untouched, the target emptied, no settings saved. + Failed, +} + +/// +/// A snapshot of the copy's progress, as shown by the Settings page. Holds no connection string. +/// +/// The stage. +/// The table being copied, or null. +/// Rows of copied so far. +/// Rows of in the source. +/// Tables completed. +/// Tables to copy. +/// Rows copied over all tables. +/// Rows to copy over all tables. +/// Why the copy was refused or failed. +/// A one-line summary of the current state. +public sealed record DatabaseCopyStatus( + DatabaseCopyPhase Phase, + string? Table, + long TableRowsCopied, + long TableRowsTotal, + int TablesDone, + int TablesTotal, + long RowsCopied, + long RowsTotal, + IReadOnlyList Errors, + string? Message) +{ + /// The state before any copy. + public static DatabaseCopyStatus Idle { get; } = new( + DatabaseCopyPhase.Idle, null, 0, 0, 0, 0, 0, 0, Array.Empty(), null); + + /// A copy is queued or running. + public bool IsActive => Phase is not (DatabaseCopyPhase.Idle or DatabaseCopyPhase.Succeeded or DatabaseCopyPhase.Failed); + + /// The copy ended, either way. + public bool IsFinished => Phase is DatabaseCopyPhase.Succeeded or DatabaseCopyPhase.Failed; + + /// The copy succeeded: the settings are saved and the process must restart to use them. + public bool RestartRequired => Phase == DatabaseCopyPhase.Succeeded; +} diff --git a/src/BaGet.Core/Entities/Copy/DatabaseCopyPreflight.cs b/src/BaGet.Core/Entities/Copy/DatabaseCopyPreflight.cs new file mode 100644 index 000000000..5d04b6c9b --- /dev/null +++ b/src/BaGet.Core/Entities/Copy/DatabaseCopyPreflight.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace BaGet.Core; + +/// +/// Finds, in the rows of the source, what the target could not hold, so every problem is reported +/// before anything is copied. Feed it each table's rows (any number of batches), then call +/// . Each check applies only where the TARGET engine enforces it. +/// +/// +/// +/// A string longer than the model's maximum length: SQL Server, PostgreSQL and MySQL refuse it; SQLite stores +/// it (it does not enforce lengths), as does a citext column (no length). +/// Two values of a unique index or key (primary or alternate) that differ only by case, where the target column +/// compares case-insensitively: judged per column from the target model (a COLLATE NOCASE or citext +/// column type, or an explicit collation named *_ci/NOCASE), otherwise from the engine's default +/// (SQL Server and MySQL case-insensitive; PostgreSQL and SQLite case-sensitive). +/// A date: its offset is unknown, and PostgreSQL accepts UTC only. (Unspecified +/// ones, what SQLite and MySQL return, are stored as UTC, which is what BaGet writes.) +/// +/// +internal sealed class DatabaseCopyPreflight +{ + /// The most problems listed per table and kind; the rest is counted. + public const int MaxListedPerKind = 10; + + private readonly IModel? _designModel; + private readonly bool _checkLengths; + private readonly bool _caseInsensitiveByDefault; + private readonly bool _checkLocalDates; + private readonly List _problems = new(); + private readonly Dictionary _counts = new(); + private DatabaseTable? _table; + private List _sets = new(); + + /// The target's Database:Type. + /// + /// The target context's design-time model (GetService<IDesignTimeModel>().Model), which alone holds the + /// column types and collations; without it only the engine's defaults are known. + /// + public DatabaseCopyPreflight(string targetType, IModel? designModel = null) + { + _designModel = designModel; + bool Is(string name) => string.Equals(targetType, name, StringComparison.OrdinalIgnoreCase); + + _checkLengths = Is("SqlServer") || Is("PostgreSql") || Is("MySql"); + _caseInsensitiveByDefault = Is("SqlServer") || Is("MySql"); + _checkLocalDates = Is("PostgreSql"); + } + + /// The problems found, one line each. + public IReadOnlyList Problems => _problems; + + public void Inspect(DatabaseTable table, IEnumerable rows) + { + if (!ReferenceEquals(_table, table)) + { + _table = table; + _sets = UniqueSetsOf(table); + } + + var properties = table.EntityType.GetProperties().ToList(); + + foreach (var row in rows) + { + foreach (var property in properties) + { + var value = DatabaseTable.ValueOf(property, row); + if (value == null) continue; + + var max = property.GetMaxLength(); + if (_checkLengths && max != null && !IsCaseInsensitiveType(property, citextOnly: true)) + { + var stored = property.GetValueConverter() is { } converter ? converter.ConvertToProvider(value) : value; + if (stored is string text && text.Length > max) + { + Report(table, "length", $"{table.Name}.{property.Name} of row {table.KeyText(row)} has {text.Length} characters; the target allows {max}."); + } + } + + if (_checkLocalDates && value is DateTime date && date.Kind == DateTimeKind.Local) + { + Report(table, "date", $"{table.Name}.{property.Name} of row {table.KeyText(row)} is a local time, which PostgreSQL cannot store; only UTC is supported."); + } + } + + foreach (var set in _sets) + { + var composite = string.Join("|", set.Properties.Select(p => + { + var value = DatabaseTable.ValueOf(p, row); + return value is string s && IsCaseInsensitive(p) ? s.ToUpperInvariant() : DatabaseTable.Format(value); + })); + + var rowKey = table.KeyText(row); + if (set.Seen.TryGetValue(composite, out var other)) + { + var columns = string.Join(", ", set.Properties.Select(p => p.Name)); + Report(table, "case:" + columns, $"{table.Name} rows {other} and {rowKey} differ only by case in unique index or key ({columns}); the target compares case-insensitively."); + } + else + { + set.Seen[composite] = rowKey; + } + } + } + } + + /// Ends the table: releases what was kept to find collisions and adds the "and N more" lines. + public void EndTable() + { + foreach (var pair in _counts) + { + if (pair.Value > MaxListedPerKind) + { + _problems.Add($"... and {pair.Value - MaxListedPerKind} more of the same kind ({pair.Key})."); + } + } + + _counts.Clear(); + _sets = new List(); + _table = null; + } + + /// + /// The unique indexes and the keys (primary and alternate) of the table that hold a string compared + /// case-insensitively by the target; each distinct column list once. + /// + private List UniqueSetsOf(DatabaseTable table) + { + var sets = new List(); + var names = new HashSet(StringComparer.Ordinal); + var candidates = table.EntityType.GetIndexes().Where(i => i.IsUnique).Select(i => i.Properties) + .Concat(table.EntityType.GetKeys().Select(k => k.Properties)); + + foreach (var properties in candidates) + { + if (!properties.Any(p => p.ClrType == typeof(string) && IsCaseInsensitive(p))) continue; + if (names.Add(string.Join("|", properties.Select(p => p.Name)))) sets.Add(new UniqueSet(properties)); + } + + return sets; + } + + /// Whether the target compares the column's text case-insensitively. + private bool IsCaseInsensitive(IProperty property) + { + if (property.ClrType != typeof(string)) return false; + if (IsCaseInsensitiveType(property, citextOnly: false)) return true; + + var collation = DesignOf(property)?.GetCollation(); + if (!string.IsNullOrEmpty(collation)) + { + return collation.EndsWith("_ci", StringComparison.OrdinalIgnoreCase) + || collation.Contains("_ci_", StringComparison.OrdinalIgnoreCase) + || collation.Contains("nocase", StringComparison.OrdinalIgnoreCase); + } + + return _caseInsensitiveByDefault; + } + + /// + /// Whether the column type itself says so: citext (PostgreSQL; also unbounded, so no length applies) or + /// COLLATE NOCASE (SQLite; false). + /// + private bool IsCaseInsensitiveType(IProperty property, bool citextOnly) + { + var type = DesignOf(property)?.GetColumnType() ?? string.Empty; + if (type.Contains("citext", StringComparison.OrdinalIgnoreCase)) return true; + return !citextOnly && type.Contains("COLLATE NOCASE", StringComparison.OrdinalIgnoreCase); + } + + /// The design-time twin of a runtime property, which carries the relational annotations; null if unknown. + private IProperty? DesignOf(IProperty property) + => _designModel?.FindEntityType(property.DeclaringType.Name)?.FindProperty(property.Name); + + private sealed class UniqueSet + { + public UniqueSet(IReadOnlyList properties) => Properties = properties; + + public IReadOnlyList Properties { get; } + + public Dictionary Seen { get; } = new(StringComparer.Ordinal); + } + + private void Report(DatabaseTable table, string kind, string message) + { + var key = table.Name + ":" + kind; + _counts.TryGetValue(key, out var count); + _counts[key] = count + 1; + if (count < MaxListedPerKind) _problems.Add(message); + } +} diff --git a/src/BaGet.Core/Entities/Copy/DatabaseCopyService.cs b/src/BaGet.Core/Entities/Copy/DatabaseCopyService.cs new file mode 100644 index 000000000..39854bea6 --- /dev/null +++ b/src/BaGet.Core/Entities/Copy/DatabaseCopyService.cs @@ -0,0 +1,698 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// Copies every row of the running relational database into another relational database, then saves the +/// new Database settings. One copy at a time; runs the queued request. +/// +/// +/// +/// The closes when the request is accepted (). +/// Checks that need no access to the target run first, so a refusal leaves it as it was: the source has no +/// pending migrations, and nothing in it is something the target cannot hold (, +/// judged on the target's model). Then the target: reachable (a database that does not exist yet is created), its +/// schema migrated, every mapped table empty (the default repository row of the AddRepositories migration and the built-in groups, +/// targets and grants of AddAccessControl do not count; they are removed, the source's own rows replacing them). A target that is current and not empty is refused untouched; one +/// that needed migrating and is then found not empty keeps its updated schema, and the refusal says so. +/// Tables in foreign-key order, in batches of rows ordered by primary key, with +/// the provider's explicit-key hooks (). +/// Row counts and a checksum of the keys must match; only then the settings are saved and the gate stays +/// closed until the restart. +/// On a failure before the settings are written (including a cancellation before the file is replaced) the rows +/// copied are deleted from the target (never from the source), the gate reopens and no setting is saved. From the +/// moment the settings are being written the copy is never undone: a failure then (FailAfterSaveAsync) keeps the +/// verified target, leaves the gate closed until the restart and reports that the settings may need checking. +/// +/// Connection strings are never logged or put in the status; error text is scrubbed of them. +/// +public class DatabaseCopyService +{ + /// Rows read, inserted and saved at a time. + public const int BatchSize = 1000; + + /// The reason the gate shows while a copy runs. + public const string GateReason = "Copying the database"; + + /// Why a copy is refused on a node of a cluster (Ha:Enabled). + public const string ClusterRefusal = "The database cannot be copied while this node is part of a cluster (Ha:Enabled): the other nodes cannot be made read-only reliably. Stop the other nodes, turn Ha:Enabled off, copy, then re-enable it."; + + private static readonly string[] SecretKeys = { "password", "pwd", "user id", "uid", "user", "username", "accountkey", "sharedaccesssignature" }; + + private readonly IServiceScopeFactory _scopes; + private readonly IReadOnlyList _factories; + private readonly MaintenanceGate _gate; + private readonly SettingsService _settings; + private readonly IOptionsMonitor _current; + private readonly ILogger _logger; + private readonly ClusterRuntime? _cluster; + private readonly Channel _queue = Channel.CreateBounded(1); + private readonly object _lock = new(); + private DatabaseCopyStatus _status = DatabaseCopyStatus.Idle; + + public DatabaseCopyService( + IServiceScopeFactory scopes, + IEnumerable factories, + MaintenanceGate gate, + SettingsService settings, + IOptionsMonitor current, + ILogger logger, + ClusterRuntime? cluster = null) + { + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _factories = (factories ?? throw new ArgumentNullException(nameof(factories))).ToList(); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _current = current ?? throw new ArgumentNullException(nameof(current)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _cluster = cluster; + } + + /// The latest progress. In a cluster, the progress of a copy running on another node when this node has none of its own. + public DatabaseCopyStatus Status + { + get + { + lock (_lock) return _status != DatabaseCopyStatus.Idle ? _status : (RemoteStatus ?? _status); + } + } + + /// This node's own progress (what the cluster sync publishes). + internal DatabaseCopyStatus LocalStatus { get { lock (_lock) return _status; } } + + /// The progress another node published (set by ), or null. + internal DatabaseCopyStatus? RemoteStatus { get; set; } + + /// + /// Test seam: runs after each batch is saved, with the table and the rows of it copied so far. An + /// exception it throws fails the copy exactly as a failing insert would. + /// + internal Func? AfterBatch { get; set; } + + /// Whether a database of can be a copy's source or target (it is relational). + public bool IsRelational(string? type) => FactoryFor(type) != null; + + /// The running database's type, if it is relational (a copy can start from it); else null. + public string? CurrentRelationalType => FactoryFor(_current.CurrentValue.Type)?.DatabaseType; + + /// The Database:Type values a copy can use, for the Settings page. + public IReadOnlyList RelationalTypes => _factories.Select(f => f.DatabaseType).ToList(); + + /// + /// Whether and name the database the application is running on. + /// + public bool IsCurrentDatabase(string? type, string? connectionString) + { + var current = _current.CurrentValue; + return string.Equals(current.Type, type, StringComparison.OrdinalIgnoreCase) + && string.Equals(current.ConnectionString, connectionString, StringComparison.Ordinal); + } + + /// + /// Accepts a copy: closes the gate and queues it for . + /// + /// The copy. + /// Why it was refused, when it was. + /// False when another copy is active or the database is already read-only. + public bool TryQueue(DatabaseCopyRequest request, out string? refusal) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + + // The other nodes cannot be confirmed read-only before the copy reads, and after a success they would reopen + // and write to the old database; so a copy is refused in a cluster. + if (_cluster is { IsEnabled: true }) + { + refusal = ClusterRefusal; + return false; + } + + lock (_lock) + { + if (_status.IsActive || RemoteStatus is { IsActive: true }) + { + refusal = "Another database copy is already running."; + return false; + } + + if (_gate.IsClosed) + { + refusal = $"The database is read-only: {_gate.Reason}."; + return false; + } + + if (!_queue.Writer.TryWrite(request)) + { + refusal = "Another database copy is already queued."; + return false; + } + + _gate.Close(GateReason); + _status = DatabaseCopyStatus.Idle with { Phase = DatabaseCopyPhase.Queued, Message = "Waiting to start." }; + } + + refusal = null; + return true; + } + + /// Test seam: runs after the copy is verified, just before the settings are saved. + internal Func? BeforeSettingsSaved { get; set; } + + /// Test seam: runs after the settings were saved, before the gate closes until restart. + internal Func? AfterSettingsSaved { get; set; } + + /// The queued requests, for the worker. + internal IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken) + => _queue.Reader.ReadAllAsync(cancellationToken); + + /// + /// Runs one copy to the end and reports it through ; never throws. The gate must be + /// closed (). + /// + public async Task RunAsync(DatabaseCopyRequest request, CancellationToken cancellationToken) + { + IContext? target = null; + IReadOnlyList tables = Array.Empty(); + var touchedTarget = false; + var pastPointOfNoReturn = false; + IReadOnlyList errors; + + // Costs nothing without a listener. Tags: engine names only, never the connection string. + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.DatabaseCopy); + activity?.SetTag(BaGetDiagnostics.Tags.TargetType, request.TargetType); + + try + { + Update(s => s with { Phase = DatabaseCopyPhase.Checking, Message = "Connecting to the target." }); + + using var scope = _scopes.CreateScope(); + var source = AsDbContext(scope.ServiceProvider.GetRequiredService()); + var sourceFactory = FactoryFor(_current.CurrentValue.Type) + ?? throw new CopyRefusedException("The running database is not relational, so it cannot be copied."); + activity?.SetTag(BaGetDiagnostics.Tags.SourceType, sourceFactory.DatabaseType); + var factory = FactoryFor(request.TargetType) + ?? throw new CopyRefusedException($"\"{request.TargetType}\" is not a relational database type, so it cannot be a copy's target."); + if (IsCurrentDatabase(request.TargetType, request.TargetConnectionString)) + { + throw new CopyRefusedException("The target is the database BaGet is running on."); + } + + target = factory.Create( + request.TargetConnectionString, + new DatabaseOptions { MySqlServerVersion = request.MySqlServerVersion }, + builder => MaintenanceGate.AllowWrites(builder)); + var targetDb = AsDbContext(target); + + var pendingSource = (await source.Database.GetPendingMigrationsAsync(cancellationToken).ConfigureAwait(false)).ToList(); + if (pendingSource.Count > 0) + { + throw new CopyRefusedException( + $"The running database has {pendingSource.Count} pending migration(s) ({string.Join(", ", pendingSource)}); apply them (restart with RunMigrationsAtStartup) before copying."); + } + + tables = DatabaseTable.InDependencyOrder(targetDb.Model); + + // Everything the target cannot hold is reported at once, before the target is created, migrated or changed. + var preflight = new DatabaseCopyPreflight(request.TargetType, targetDb.GetService().Model); + foreach (var table in tables) + { + Update(s => s with { Table = table.Name, Message = $"Checking {table.Name}." }); + await ForEachBatchAsync(source, table, rows => + { + preflight.Inspect(table, rows.Select(r => r.Entity)); + return Task.CompletedTask; + }, cancellationToken).ConfigureAwait(false); + preflight.EndTable(); + } + + if (preflight.Problems.Count > 0) + { + throw new CopyRefusedException(preflight.Problems.ToArray()); + } + + // The first access to the target. A database that does not exist yet (a new SQLite file, a SQL Server database the login may create) cannot be + // connected to, but creating it is what BaGet's own migrations do; an unreachable one fails there. + if (!await targetDb.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false)) + { + try + { + await target.RunMigrationsAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + throw new CopyRefusedException( + "Cannot connect to the target database; it must be reachable with the given connection string (" + Describe(e, request) + ")."); + } + } + + // A target that is already current and holds rows is refused before anything, even its schema, changes. + var pendingTarget = await targetDb.Database.GetPendingMigrationsAsync(cancellationToken).ConfigureAwait(false); + if (!pendingTarget.Any()) + { + await EnsureEmptyAsync(targetDb, tables, schemaUpdated: false, cancellationToken).ConfigureAwait(false); + } + + Update(s => s with { Phase = DatabaseCopyPhase.Migrating, Table = null, Message = "Preparing the target's schema." }); + await target.RunMigrationsAsync(cancellationToken).ConfigureAwait(false); + await EnsureEmptyAsync(targetDb, tables, schemaUpdated: true, cancellationToken).ConfigureAwait(false); + await RemoveSeededRowsAsync(targetDb, cancellationToken).ConfigureAwait(false); + + var totals = new Dictionary(); + foreach (var table in tables) totals[table] = await table.CountAsync(source, cancellationToken).ConfigureAwait(false); + + Update(s => s with + { + Phase = DatabaseCopyPhase.Copying, + TablesTotal = tables.Count, + RowsTotal = totals.Values.Sum(), + Message = "Copying rows.", + }); + + touchedTarget = true; + var checksums = new Dictionary(); + var done = 0; + foreach (var table in tables) + { + checksums[table] = await CopyTableAsync(source, target, targetDb, table, totals[table], cancellationToken).ConfigureAwait(false); + done++; + var doneNow = done; + Update(s => s with { TablesDone = doneNow }); + } + + Update(s => s with { Phase = DatabaseCopyPhase.Verifying, Table = null, Message = "Comparing the copy with the source." }); + await VerifyAsync(targetDb, tables, totals, checksums, cancellationToken).ConfigureAwait(false); + + Update(s => s with { Phase = DatabaseCopyPhase.SavingSettings, Message = "Saving the database settings." }); + if (BeforeSettingsSaved != null) await BeforeSettingsSaved().ConfigureAwait(false); + + // From here the settings may be on disk (and the next start use the target): the copy is never undone. Except + // for a cancellation: the file is replaced by one synchronous rename after the last point that observes the token + // (the save lock, the temporary file's write), so a cancelled save never replaced it. + pastPointOfNoReturn = true; + SettingsSaveResult saved; + try + { + saved = await _settings.SaveAsync(request.SettingChanges, request.Actor, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + pastPointOfNoReturn = false; + throw; + } + + if (!saved.Succeeded) + { + // A refusal means nothing was written, so the copy can still be undone. + pastPointOfNoReturn = false; + throw new CopyRefusedException(saved.Errors.Select(e => "The settings were not saved: " + e).ToArray()); + } + + if (AfterSettingsSaved != null) await AfterSettingsSaved().ConfigureAwait(false); + + activity?.SetTag(BaGetDiagnostics.Tags.Result, "Succeeded"); + activity?.SetTag(BaGetDiagnostics.Tags.Tables, tables.Count); + activity?.SetTag(BaGetDiagnostics.Tags.Rows, totals.Values.Sum()); + + _gate.CloseUntilRestart("The database was copied; restart BaGet to use the new database"); + Update(s => s with + { + Phase = DatabaseCopyPhase.Succeeded, + Table = null, + Message = "The data was copied and the settings saved. Restart BaGet to use the new database.", + }); + _logger.LogWarning( + "{Actor} copied the {SourceType} database to a {TargetType} database ({Rows} rows in {Tables} tables)", + request.Actor, sourceFactory.DatabaseType, request.TargetType, totals.Values.Sum(), tables.Count); + + try + { + await AsDbContext(target).DisposeAsync().ConfigureAwait(false); + } + catch (Exception e) + { + _logger.LogWarning(e, "Disposing the copy's target context failed after a successful copy"); + } + + return; + } + catch (CopyRefusedException e) + { + errors = e.Problems; + } + catch (Exception e) + { + errors = new[] { Describe(e, request) }; + } + + activity?.SetTag(BaGetDiagnostics.Tags.Result, "Failed"); + activity?.SetStatus(ActivityStatusCode.Error); + + if (pastPointOfNoReturn) + { + await FailAfterSaveAsync(request, target, errors).ConfigureAwait(false); + return; + } + + await FailAsync(request, target, tables, touchedTarget, errors).ConfigureAwait(false); + } + + /// + /// A failure once the settings were being saved: the target holds the verified copy and the saved settings (if any) + /// point at it, so it is kept, the gate stays closed until the restart (writes to the source would be lost) and the + /// error is reported. + /// + private async Task FailAfterSaveAsync(DatabaseCopyRequest request, IContext? target, IReadOnlyList errors) + { + if (target != null) + { + try + { + await AsDbContext(target).DisposeAsync().ConfigureAwait(false); + } + catch (Exception) + { + // Nothing left to clean up. + } + } + + _gate.CloseUntilRestart("The database was copied but the settings may not have been saved; check them and restart BaGet"); + _logger.LogError("Database copy to {TargetType} failed while saving the settings: {Errors}", request.TargetType, string.Join(" | ", errors)); + Update(s => s with + { + Phase = DatabaseCopyPhase.Failed, + Table = null, + Errors = errors, + Message = "The data was copied and verified, but saving the settings failed. The target was kept; check the database settings, then restart BaGet.", + }); + } + + private async Task FailAsync( + DatabaseCopyRequest request, + IContext? target, + IReadOnlyList tables, + bool touchedTarget, + IReadOnlyList errors) + { + var all = errors.ToList(); + if (target != null) + { + if (touchedTarget) + { + Update(s => s with { Phase = DatabaseCopyPhase.RollingBack, Table = null, Message = "Removing the copied rows from the target." }); + try + { + // Only ever the target, which was empty when the copy began. + var db = AsDbContext(target); + db.ChangeTracker.Clear(); + foreach (var table in tables.Reverse()) + { + await table.DeleteAllAsync(db, CancellationToken.None).ConfigureAwait(false); + } + } + catch (Exception e) + { + all.Add("The rows copied so far could not be removed from the target; empty it before trying again. " + Describe(e, request)); + } + } + + try + { + await AsDbContext(target).DisposeAsync().ConfigureAwait(false); + } + catch (Exception) + { + // Nothing left to clean up. + } + } + + _gate.Open(); + _logger.LogError("Database copy to {TargetType} failed: {Errors}", request.TargetType, string.Join(" | ", all)); + Update(s => s with + { + Phase = DatabaseCopyPhase.Failed, + Table = null, + Errors = all, + Message = "The copy failed. The running database is unchanged and no setting was saved.", + }); + } + + private async Task CopyTableAsync( + DbContext source, + IContext target, + DbContext targetDb, + DatabaseTable table, + long total, + CancellationToken cancellationToken) + { + var dateProperties = table.EntityType.GetProperties() + .Where(p => p.ClrType == typeof(DateTime) || p.ClrType == typeof(DateTime?)) + .ToList(); + var computed = table.EntityType.GetProperties() + .Where(p => !p.IsKey() && p.ValueGenerated == ValueGenerated.OnAddOrUpdate) + .ToList(); + + long copied = 0; + using var checksum = new DatabaseTable.Checksum(); + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.DatabaseCopyTable); + activity?.SetTag(BaGetDiagnostics.Tags.Table, table.Name); + activity?.SetTag(BaGetDiagnostics.Tags.Rows, total); + + Update(s => s with { Table = table.Name, TableRowsCopied = 0, TableRowsTotal = total, Message = $"Copying {table.Name}." }); + var rowsBefore = Status.RowsCopied; + + await target.BeginKeyedInsertAsync(table.EntityType, cancellationToken).ConfigureAwait(false); + try + { + await ForEachBatchAsync(source, table, async rows => + { + foreach (var row in rows) + { + checksum.Add(table.KeyText(row.Entity)); + + var entry = targetDb.Add(row.Entity); + foreach (var shadow in row.Shadow) entry.Property(shadow.Key).CurrentValue = shadow.Value; + + // SQLite, SQL Server and MySQL return dates of unspecified kind; BaGet stores UTC, and PostgreSQL accepts + // nothing else. EF compares DateTimes without their kind, so assigning the same instant with another kind + // is ignored as "no change": move off it first. The entry reads the mapped field, so a property whose + // getter already forces UTC (Package.Published) is fixed too. + foreach (var property in dateProperties) + { + var member = entry.Property(property.Name); + if (member.CurrentValue is DateTime { Kind: DateTimeKind.Unspecified } date) + { + member.CurrentValue = DateTime.MinValue; + member.CurrentValue = DateTime.SpecifyKind(date, DateTimeKind.Utc); + } + } + + // Values the database generates itself (row versions) are not inserted. + foreach (var property in computed) + { + entry.Property(property.Name).CurrentValue = property.ClrType.IsValueType && Nullable.GetUnderlyingType(property.ClrType) == null + ? Activator.CreateInstance(property.ClrType) + : null; + } + } + + try + { + await targetDb.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException e) + { + throw new CopyRefusedException( + $"Inserting into {table.Name} failed (rows {table.KeyText(rows[0].Entity)} to {table.KeyText(rows[rows.Count - 1].Entity)}): {e.GetBaseException().Message}"); + } + + targetDb.ChangeTracker.Clear(); + copied += rows.Count; + var copiedNow = copied; + Update(s => s with { TableRowsCopied = copiedNow, RowsCopied = rowsBefore + copiedNow }); + + if (AfterBatch != null) await AfterBatch(table.Name, copiedNow, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + catch + { + activity?.SetTag(BaGetDiagnostics.Tags.Result, "Failed"); + activity?.SetStatus(ActivityStatusCode.Error); + + try + { + await target.EndKeyedInsertAsync(table.EntityType, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception) + { + // The original failure is the one to report. + } + + throw; + } + + await target.EndKeyedInsertAsync(table.EntityType, cancellationToken).ConfigureAwait(false); + activity?.SetTag(BaGetDiagnostics.Tags.Result, "Succeeded"); + return checksum.Finish(); + } + + private static async Task VerifyAsync( + DbContext target, + IReadOnlyList tables, + IReadOnlyDictionary totals, + IReadOnlyDictionary checksums, + CancellationToken cancellationToken) + { + var problems = new List(); + foreach (var table in tables) + { + var count = await table.CountAsync(target, cancellationToken).ConfigureAwait(false); + if (count != totals[table]) + { + problems.Add($"{table.Name}: the source has {totals[table]} rows, the target {count}."); + continue; + } + + using var checksum = new DatabaseTable.Checksum(); + await ForEachBatchAsync(target, table, rows => + { + foreach (var row in rows) checksum.Add(table.KeyText(row.Entity)); + return Task.CompletedTask; + }, cancellationToken).ConfigureAwait(false); + + if (checksum.Finish() != checksums[table]) + { + problems.Add($"{table.Name}: the keys of the target differ from the source's."); + } + } + + if (problems.Count > 0) throw new CopyRefusedException(problems.ToArray()); + } + + // The rows the AddRepositories and AddAccessControl migrations create: what a fresh target holds, so not "data". + // The source's own copies of them (edited or not) replace them. + private static readonly System.Linq.Expressions.Expression> SeededDefault + = r => r.Key == Repository.DefaultKey && r.Name == Repository.DefaultName; + + // The grants of the seeded targets go with their target (cascade); the built-in groups' members do too. + private static async Task RemoveSeededRowsAsync(DbContext target, CancellationToken cancellationToken) + { + await target.Set().Where(t => t.IsBuiltIn).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + await target.Set().Where(g => g.IsBuiltIn).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + await target.Set().Where(SeededDefault).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + } + + // How many rows of a table the migrations seeded (they are not data), or 0 for a table nothing seeds. + private static async Task SeededCountAsync(DbContext target, Type clrType, CancellationToken cancellationToken) + { + if (clrType == typeof(Repository)) return await target.Set().CountAsync(SeededDefault, cancellationToken).ConfigureAwait(false); + if (clrType == typeof(Group)) return await target.Set().CountAsync(g => g.IsBuiltIn, cancellationToken).ConfigureAwait(false); + if (clrType == typeof(PermissionTarget)) return await target.Set().CountAsync(t => t.IsBuiltIn, cancellationToken).ConfigureAwait(false); + if (clrType == typeof(PermissionGrant)) + { + return await target.Set() + .CountAsync(g => target.Set().Any(t => t.Key == g.TargetKey && t.IsBuiltIn), cancellationToken).ConfigureAwait(false); + } + + return 0; + } + + private static async Task EnsureEmptyAsync( + DbContext target, + IReadOnlyList tables, + bool schemaUpdated, + CancellationToken cancellationToken) + { + var problems = new List(); + foreach (var table in tables) + { + var count = await table.CountAsync(target, cancellationToken).ConfigureAwait(false) + - await SeededCountAsync(target, table.EntityType.ClrType, cancellationToken).ConfigureAwait(false); + if (count > 0) + { + problems.Add(schemaUpdated + ? $"The target is not empty: {table.Name} has {count} row(s). The target's schema was updated, but nothing was copied." + : $"The target is not empty: {table.Name} has {count} row(s). Nothing was changed."); + } + } + + if (problems.Count > 0) throw new CopyRefusedException(problems.ToArray()); + } + + private static async Task ForEachBatchAsync( + DbContext context, + DatabaseTable table, + Func, Task> action, + CancellationToken cancellationToken) + { + var skip = 0; + while (true) + { + var rows = await table.ReadBatchAsync(context, skip, BatchSize, cancellationToken).ConfigureAwait(false); + if (rows.Count == 0) return; + + await action(rows).ConfigureAwait(false); + skip += rows.Count; + if (rows.Count < BatchSize) return; + } + } + + private void Update(Func change) + { + lock (_lock) _status = change(_status); + } + + private IDatabaseContextFactory? FactoryFor(string? type) + => string.IsNullOrEmpty(type) + ? null + : _factories.FirstOrDefault(f => string.Equals(f.DatabaseType, type, StringComparison.OrdinalIgnoreCase)); + + private static DbContext AsDbContext(IContext context) + => context as DbContext ?? throw new InvalidOperationException("The database context is not an Entity Framework context."); + + /// An error as text safe to show: no connection string, no credential from it. + internal static string Describe(Exception exception, DatabaseCopyRequest request) + => Scrub(exception.GetBaseException().Message, request.TargetConnectionString); + + /// Removes the connection string, and the credentials inside it, from . + internal static string Scrub(string message, string connectionString) + { + if (string.IsNullOrEmpty(connectionString)) return message; + + message = message.Replace(connectionString, "[connection string]", StringComparison.Ordinal); + foreach (var part in connectionString.Split(';', StringSplitOptions.RemoveEmptyEntries)) + { + var separator = part.IndexOf('='); + if (separator <= 0) continue; + + var key = part.Substring(0, separator).Trim().ToLowerInvariant(); + var value = part.Substring(separator + 1).Trim().Trim('\'', '"'); + if (value.Length > 0 && SecretKeys.Contains(key)) + { + message = message.Replace(value, "[hidden]", StringComparison.Ordinal); + } + } + + return message; + } + + /// A failure that is the user's to fix: shown as is (it holds no connection string). + private sealed class CopyRefusedException : Exception + { + public CopyRefusedException(string problem) : this(new[] { problem }) { } + + public CopyRefusedException(string[] problems) : base(string.Join(" ", problems)) => Problems = problems; + + public string[] Problems { get; } + } +} diff --git a/src/BaGet.Core/Entities/Copy/DatabaseCopyWorker.cs b/src/BaGet.Core/Entities/Copy/DatabaseCopyWorker.cs new file mode 100644 index 000000000..fceb913f4 --- /dev/null +++ b/src/BaGet.Core/Entities/Copy/DatabaseCopyWorker.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; + +namespace BaGet.Core; + +/// +/// Runs the database copy accepted by ; one at a time, +/// because the service accepts one request at a time. +/// +public class DatabaseCopyWorker : BackgroundService +{ + private readonly DatabaseCopyService _service; + + public DatabaseCopyWorker(DatabaseCopyService service) + { + _service = service ?? throw new ArgumentNullException(nameof(service)); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await Task.Yield(); + + try + { + await foreach (var request in _service.DequeueAllAsync(stoppingToken)) + { + await _service.RunAsync(request, stoppingToken); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + } + } +} diff --git a/src/BaGet.Core/Entities/Copy/DatabaseTable.cs b/src/BaGet.Core/Entities/Copy/DatabaseTable.cs new file mode 100644 index 000000000..466b218a7 --- /dev/null +++ b/src/BaGet.Core/Entities/Copy/DatabaseTable.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace BaGet.Core; + +/// A row as read: the entity, and the values of its shadow properties (which the entity itself cannot hold). +/// The entity, detached. +/// Shadow property values by name, such as the foreign key to the package. +internal sealed record CopyRow(object Entity, IReadOnlyDictionary Shadow); + +/// +/// One mapped table of the model, read and emptied without knowing its CLR type at compile time, so a +/// table added to the model later is copied without touching the copy. +/// +internal sealed class DatabaseTable +{ + private static readonly MethodInfo CountMethod = typeof(DatabaseTable).GetMethod(nameof(CountAsync), BindingFlags.Static | BindingFlags.NonPublic)!; + private static readonly MethodInfo ReadMethod = typeof(DatabaseTable).GetMethod(nameof(ReadBatchAsync), BindingFlags.Static | BindingFlags.NonPublic)!; + private static readonly MethodInfo DeleteMethod = typeof(DatabaseTable).GetMethod(nameof(DeleteAllAsync), BindingFlags.Static | BindingFlags.NonPublic)!; + + public DatabaseTable(IEntityType entityType) + { + EntityType = entityType; + Key = entityType.FindPrimaryKey() + ?? throw new InvalidOperationException($"Table {entityType.GetTableName()} has no primary key, so it cannot be copied in a stable order."); + } + + /// The entity type, in the model of the context it was taken from. + public IEntityType EntityType { get; } + + /// The primary key, the order rows are read in. + public IKey Key { get; } + + /// The table's name, for messages. + public string Name => EntityType.GetTableName() ?? EntityType.DisplayName(); + + /// + /// The mapped tables of with every table after the ones it references + /// (a topological sort over the foreign keys), so rows can be inserted in this order and deleted in + /// the reverse one. Owned, keyless, shared-type and derived entity types have no table of their own. + /// + public static IReadOnlyList InDependencyOrder(IModel model) + { + var types = model.GetEntityTypes() + .Where(e => !e.IsOwned() && e.FindPrimaryKey() != null && !e.HasSharedClrType && e.BaseType == null && e.GetTableName() != null) + .OrderBy(e => e.GetTableName(), StringComparer.Ordinal) + .ToList(); + + var remaining = types.ToDictionary(t => t, t => new HashSet( + t.GetForeignKeys().Select(f => f.PrincipalEntityType.GetRootType()).Where(p => p != t && types.Contains(p)))); + var ordered = new List(); + + while (remaining.Count > 0) + { + var ready = remaining.Where(p => p.Value.Count == 0).Select(p => p.Key).ToList(); + if (ready.Count == 0) + { + throw new InvalidOperationException( + "The model's foreign keys form a cycle (" + string.Join(", ", remaining.Keys.Select(t => t.GetTableName())) + "), so no insert order exists."); + } + + foreach (var type in ready) + { + ordered.Add(new DatabaseTable(type)); + remaining.Remove(type); + } + + foreach (var dependencies in remaining.Values) dependencies.ExceptWith(ready); + } + + return ordered; + } + + public Task CountAsync(DbContext context, CancellationToken cancellationToken) + => (Task)CountMethod.MakeGenericMethod(EntityType.ClrType).Invoke(null, new object[] { context, cancellationToken })!; + + /// + /// Reads rows after , ordered by primary key. The rows are loaded + /// tracked, only so that the shadow properties (such as the foreign key to the package) can be captured with + /// them, and the context's tracker is cleared before returning, so the entities come back detached. + /// + public Task> ReadBatchAsync(DbContext context, int skip, int take, CancellationToken cancellationToken) + => (Task>)ReadMethod.MakeGenericMethod(EntityType.ClrType).Invoke(null, new object[] { context, Key, skip, take, cancellationToken })!; + + public Task DeleteAllAsync(DbContext context, CancellationToken cancellationToken) + => (Task)DeleteMethod.MakeGenericMethod(EntityType.ClrType).Invoke(null, new object[] { context, cancellationToken })!; + + /// The primary key of as one invariant string. + public string KeyText(object entity) + => string.Join("|", Key.Properties.Select(p => Format(ValueOf(p, entity)))); + + /// The value of a property of an entity, before any value conversion; null for a shadow property. + public static object? ValueOf(IProperty property, object entity) + { + if (property.PropertyInfo != null) return property.PropertyInfo.GetValue(entity); + return property.FieldInfo?.GetValue(entity); + } + + /// A value as invariant text, for keys and checksums. + public static string Format(object? value) + => value switch + { + null => "\u0000", + byte[] bytes => Convert.ToBase64String(bytes), + IFormattable formattable => formattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture), + _ => value.ToString() ?? string.Empty, + }; + + /// + /// Checksum of a table's keys that does not depend on the order they are added: each engine reads + /// ORDER BY in its own collation, so the same keys arrive in different orders. The SHA-256 of every key is + /// summed (mod 2^256); the row count is part of the result. + /// + public sealed class Checksum : IDisposable + { + private readonly byte[] _sum = new byte[32]; + private long _count; + + public void Add(string keyText) + { + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(keyText)); + var carry = 0; + for (var i = 0; i < _sum.Length; i++) + { + var value = _sum[i] + hash[i] + carry; + _sum[i] = (byte)value; + carry = value >> 8; + } + + _count++; + } + + public string Finish() + { + var result = Convert.ToHexString(_sum) + ":" + _count; + Array.Clear(_sum, 0, _sum.Length); + _count = 0; + return result; + } + + public void Dispose() + { + } + } + + private static async Task CountAsync(DbContext context, CancellationToken cancellationToken) + where T : class + => await context.Set().IgnoreQueryFilters().LongCountAsync(cancellationToken).ConfigureAwait(false); + + private static async Task DeleteAllAsync(DbContext context, CancellationToken cancellationToken) + where T : class + => await context.Set().IgnoreQueryFilters().ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + + private static async Task> ReadBatchAsync(DbContext context, IKey key, int skip, int take, CancellationToken cancellationToken) + where T : class + { + // A copy takes every repository's rows, not just the context's current one. + IQueryable query = context.Set().IgnoreQueryFilters().AsTracking(); + query = Order(query, key).Skip(skip).Take(take); + + var rows = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + var result = new List(rows.Count); + foreach (var row in rows) + { + var shadow = context.Entry(row).Properties + .Where(p => p.Metadata.IsShadowProperty()) + .ToDictionary(p => p.Metadata.Name, p => p.CurrentValue); + result.Add(new CopyRow(row, shadow)); + } + + context.ChangeTracker.Clear(); + return result; + } + + private static IQueryable Order(IQueryable query, IKey key) + { + var first = true; + foreach (var property in key.Properties) + { + var parameter = Expression.Parameter(typeof(T), "e"); + var access = Expression.Call( + typeof(EF), nameof(EF.Property), new[] { property.ClrType }, parameter, Expression.Constant(property.Name)); + var lambda = Expression.Lambda(access, parameter); + + var method = typeof(Queryable).GetMethods() + .Single(m => m.Name == (first ? nameof(Queryable.OrderBy) : nameof(Queryable.ThenBy)) && m.GetParameters().Length == 2) + .MakeGenericMethod(typeof(T), property.ClrType); + query = (IQueryable)method.Invoke(null, new object[] { query, lambda })!; + first = false; + } + + return query; + } +} diff --git a/src/BaGet.Core/Entities/IContext.cs b/src/BaGet.Core/Entities/IContext.cs index c110b59c2..e026721d9 100644 --- a/src/BaGet.Core/Entities/IContext.cs +++ b/src/BaGet.Core/Entities/IContext.cs @@ -2,35 +2,188 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IContext { - public interface IContext - { - DatabaseFacade Database { get; } - - DbSet Packages { get; set; } - - /// - /// Check whether a is due to a SQL unique constraint violation. - /// - /// The exception to inspect. - /// Whether the exception was caused to SQL unique constraint violation. - bool IsUniqueConstraintViolationException(DbUpdateException exception); - - /// - /// Whether this database engine supports LINQ "Take" in subqueries. - /// - bool SupportsLimitInSubqueries { get; } - - Task SaveChangesAsync(CancellationToken cancellationToken); - - /// - /// Applies any pending migrations for the context to the database. - /// Creates the database if it does not already exist. - /// - /// A token to cancel the task. - /// A task that completes once migrations are applied. - Task RunMigrationsAsync(CancellationToken cancellationToken); - } + DatabaseFacade Database { get; } + + DbSet? Packages { get; set; } + + /// + /// The dependencies declared by packages. A dependency belongs to the package that + /// declares it, but the relationship is optional in the database, so deleting a + /// package does not delete them. + /// + DbSet? PackageDependencies { get; set; } + + /// + /// The deprecations of package versions. + /// + DbSet? PackageDeprecations { get; set; } + + /// + /// The known vulnerabilities affecting package versions. + /// + DbSet? PackageVulnerabilities { get; set; } + + DbSet? CatalogLeafs { get; set; } + + DbSet? Organizations { get; set; } + + DbSet? OrganizationMembers { get; set; } + + DbSet? PackageOwners { get; set; } + + DbSet? ApiKeys { get; set; } + + /// The repositories an API key is limited to; see . + DbSet? ApiKeyRepositories { get; set; } + + DbSet? PackageValidations { get; set; } + + DbSet? AbuseReports { get; set; } + + /// + /// Which package version each indexed PDB came from; see . + /// + DbSet? PackageSymbols { get; set; } + + /// What vulnerability scans found per artifact version; see . Repository-scoped. + DbSet? ScanResults { get; set; } + + /// The findings of a . + DbSet? ScanFindings { get; set; } + + /// The scanning policies of repositories and projects; see . + DbSet? ScanPolicies { get; set; } + + /// npm packages (packuments); see . Repository-scoped. + DbSet? NpmPackages { get; set; } + + /// The published versions of npm packages; see . + DbSet? NpmVersions { get; set; } + + /// The dist-tags of npm packages; see . + DbSet? NpmDistTags { get; set; } + + /// Maven artifacts (group and artifact id); see . Repository-scoped. + DbSet? MavenArtifacts { get; set; } + + /// The versions of Maven artifacts; see . + DbSet? MavenVersions { get; set; } + + /// The files of Maven versions, with their checksums; see . + DbSet? MavenFiles { get; set; } + + /// The image repositories of Docker repositories; see . Repository-scoped. + DbSet? OciRepositories { get; set; } + + /// The manifests and indexes of images; see . + DbSet? OciManifests { get; set; } + + /// The tags of images; see . + DbSet? OciTags { get; set; } + + /// The blobs of a Docker repository, by digest; see . Repository-scoped. + DbSet? OciBlobs { get; set; } + + /// Which images hold which blobs; see . + DbSet? OciBlobLinks { get; set; } + + /// The open blob upload sessions; see . + DbSet? OciUploads { get; set; } + + /// + /// The repositories. Not repository-scoped: it lists them all. + /// + DbSet? Repositories { get; set; } + + DbSet? Projects { get; set; } + + /// The access model: groups, their members, permission targets and grants, project members and the audit log. + DbSet? Groups { get; set; } + + DbSet? GroupMembers { get; set; } + + DbSet? PermissionTargets { get; set; } + + DbSet? PermissionGrants { get; set; } + + DbSet? ProjectMembers { get; set; } + + DbSet? AccessAuditEntries { get; set; } + + /// The retention policies; see . Not repository-scoped. + DbSet? RetentionPolicies { get; set; } + + /// The legal holds; see . Repository-scoped. + DbSet? RetentionHolds { get; set; } + + /// When versions were last downloaded; see . Repository-scoped. + DbSet? ArtifactUsages { get; set; } + + /// The replication configurations; see . Not repository-scoped. + DbSet? ReplicationConfigs { get; set; } + + /// The replication log; see . Not repository-scoped. + DbSet? ReplicationRuns { get; set; } + + /// What replication copied; see . Not repository-scoped. + DbSet? ReplicationItems { get; set; } + + /// The ASP.NET Core data protection key ring when Ha:Enabled; see . Not repository-scoped. + DbSet? DataProtectionKeys { get; set; } + + /// + /// Identity's users. Declared here so that account services can query them through + /// the same context as everything else. + /// + DbSet Users { get; set; } + + /// + /// Check whether a is due to a SQL unique constraint violation. + /// + /// The exception to inspect. + /// Whether the exception was caused to SQL unique constraint violation. + bool IsUniqueConstraintViolationException(DbUpdateException exception); + + /// + /// Whether this database engine supports LINQ "Take" in subqueries. + /// + bool SupportsLimitInSubqueries { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken); + + /// + /// Applies any pending migrations for the context to the database. + /// Creates the database if it does not already exist. + /// + /// A token to cancel the task. + /// A task that completes once migrations are applied. + Task RunMigrationsAsync(CancellationToken cancellationToken); + + /// + /// Prepares the database for inserting rows of with explicit values for + /// their generated (identity/serial/auto-increment) key, as a data copy does. Call it before the + /// inserts and after them, for one table at a time. + /// + /// + /// Providers that need it (SQL Server) hold the context's connection open between the two calls, + /// because the setting is per connection; the caller must therefore call both, on the same context. + /// Providers whose engine needs nothing (SQLite, MySQL) do nothing. + /// + /// The EF entity type about to receive explicit keys. + /// A token to cancel the task. + Task BeginKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken); + + /// + /// Completes the explicit-key inserts started by , so that keys + /// generated afterwards continue after the highest copied key (PostgreSQL resets its sequence here). + /// + /// The EF entity type whose rows were inserted. + /// A token to cancel the task. + Task EndKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken); } diff --git a/src/BaGet.Core/Entities/IDatabaseContextFactory.cs b/src/BaGet.Core/Entities/IDatabaseContextFactory.cs new file mode 100644 index 000000000..b1ac22dfb --- /dev/null +++ b/src/BaGet.Core/Entities/IDatabaseContextFactory.cs @@ -0,0 +1,41 @@ +using System; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Opens an on an arbitrary connection string of one relational database +/// engine, independent of the Database options the application runs on. This is how a second +/// database (such as the target of a data copy) is reached. +/// +/// +/// Each relational provider registers one; resolve them as IEnumerable<IDatabaseContextFactory> +/// and pick by . AzureTable registers none (it is not relational). +/// +public interface IDatabaseContextFactory +{ + /// + /// The Database:Type value this factory serves ("Sqlite", "SqlServer", "PostgreSql", "MySql"). + /// + string DatabaseType { get; } + + /// + /// Creates a context for , configured exactly as the provider's + /// normal registration configures the application's context. Nothing is opened or migrated, except + /// that MySQL without a configured server version connects to detect it. + /// + /// The target database's connection string. + /// + /// Provider settings other than the connection string (currently MySqlServerVersion); + /// uses none. Its ConnectionString is ignored. + /// + /// Optional callback to customise the (for example to add an interceptor). + /// + /// A new context the caller owns. It is a , so dispose it + /// ( / ) when done. + /// + IContext Create( + string connectionString, + DatabaseOptions? options = null, + Action? configure = null); +} diff --git a/src/BaGet.Core/Entities/MaintenanceException.cs b/src/BaGet.Core/Entities/MaintenanceException.cs new file mode 100644 index 000000000..4753e8b38 --- /dev/null +++ b/src/BaGet.Core/Entities/MaintenanceException.cs @@ -0,0 +1,20 @@ +using System; + +namespace BaGet.Core; + +/// +/// Thrown when a database write is attempted while the is closed. +/// The web layer maps it to HTTP 503 with a Retry-After header; background services log it +/// and retry later. +/// +public class MaintenanceException : InvalidOperationException +{ + public MaintenanceException(string reason) + : base($"The server is read-only for maintenance: {reason}") + { + Reason = reason; + } + + /// Why the gate is closed, as given to . + public string Reason { get; } +} diff --git a/src/BaGet.Core/Entities/MaintenanceGate.cs b/src/BaGet.Core/Entities/MaintenanceGate.cs new file mode 100644 index 000000000..188f8ae56 --- /dev/null +++ b/src/BaGet.Core/Entities/MaintenanceGate.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Core; + +/// +/// An in-memory, process-wide read-only switch for the database. While it is closed, +/// refuses every SaveChanges with a +/// ; reads are unaffected. +/// +/// In a cluster (Ha:Enabled) a closure made by is published to the other nodes and theirs are applied here +/// (), so the whole cluster is read-only together; the closing node keeps it alive and a node that +/// dies stops holding it. stays on its own node. +/// +/// +/// A context built with is exempt, so the job that +/// holds the gate closed (for example a database copy) can still write to its own target. +/// +/// +/// closes the gate for good: then does nothing, +/// because the state is not persisted and a restart is the only thing that resets it. +/// +/// +public sealed class MaintenanceGate +{ + /// Seconds advertised in the Retry-After header of a 503 answered while the gate is closed. + public const int RetryAfterSeconds = 60; + + private readonly object _lock = new(); + private string? _reason; + private bool _untilRestart; + private bool _remote; + + /// Whether writes are currently refused. + public bool IsClosed { get { lock (_lock) return _reason != null; } } + + /// True when the gate was closed with and cannot be reopened. + public bool IsClosedUntilRestart { get { lock (_lock) return _untilRestart; } } + + /// Why the gate is closed, or null while it is open. + public string? Reason { get { lock (_lock) return _reason; } } + + /// + /// Called with the reason (or null when reopened) after this node closes or reopens the gate itself, to publish it to the cluster. + /// + internal Action? Publisher { get; set; } + + /// The reason of a closure this node made itself (to keep it published), or null. + internal string? LocalReason { get { lock (_lock) return _remote || _untilRestart ? null : _reason; } } + + /// Refuse writes until is called. + public void Close(string reason) + { + if (string.IsNullOrWhiteSpace(reason)) throw new ArgumentException("A reason is required.", nameof(reason)); + + var publish = false; + lock (_lock) + { + // A permanent closure keeps its own reason. + if (!_untilRestart) + { + _reason = reason; + _remote = false; + publish = true; + } + } + + if (publish) Publisher?.Invoke(reason); + } + + /// Applies the cluster's closure (null = no node holds the gate closed); never touches a closure this node made. + internal void ApplyRemote(string? reason) + { + lock (_lock) + { + if (_untilRestart) return; + if (reason != null) + { + if (_reason == null || _remote) + { + _reason = reason; + _remote = true; + } + } + else if (_remote) + { + _reason = null; + _remote = false; + } + } + } + + /// Refuse writes until the process restarts; no longer reopens. + public void CloseUntilRestart(string reason) + { + if (string.IsNullOrWhiteSpace(reason)) throw new ArgumentException("A reason is required.", nameof(reason)); + + lock (_lock) + { + _reason = reason; + _untilRestart = true; + } + } + + /// + /// Allow writes again. Returns false, leaving the gate closed, after or when another node of the + /// cluster holds it closed (only that node reopens it). + /// + public bool Open() + { + lock (_lock) + { + if (_untilRestart || _remote) return false; + _reason = null; + } + + Publisher?.Invoke(null); + return true; + } + + /// Throw while the gate is closed. + public void ThrowIfClosed() + { + var reason = Reason; + if (reason != null) throw new MaintenanceException(reason); + } + + /// + /// Mark a context's options as exempt from the gate. Use it only for a context that the job holding + /// the gate closed writes to itself, such as the target of a database copy. + /// + public static DbContextOptionsBuilder AllowWrites(DbContextOptionsBuilder optionsBuilder) + { + if (optionsBuilder == null) throw new ArgumentNullException(nameof(optionsBuilder)); + + var extension = optionsBuilder.Options.FindExtension() + ?? new AllowWritesOptionsExtension(); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + return optionsBuilder; + } + + /// Typed form of . + public static DbContextOptionsBuilder AllowWrites(DbContextOptionsBuilder optionsBuilder) + where TContext : DbContext + { + AllowWrites((DbContextOptionsBuilder)optionsBuilder); + return optionsBuilder; + } + + /// Whether a context was built with . + internal static bool AreWritesAllowed(DbContext? context) + { + return context?.GetService().FindExtension() != null; + } + + private sealed class AllowWritesOptionsExtension : IDbContextOptionsExtension + { + private DbContextOptionsExtensionInfo? _info; + + public DbContextOptionsExtensionInfo Info => _info ??= new ExtensionInfo(this); + + public void ApplyServices(IServiceCollection services) + { + } + + public void Validate(IDbContextOptions options) + { + } + + private sealed class ExtensionInfo : DbContextOptionsExtensionInfo + { + public ExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { } + + public override bool IsDatabaseProvider => false; + + public override string LogFragment => "AllowWrites "; + + public override int GetServiceProviderHashCode() => 0; + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is ExtensionInfo; + + public override void PopulateDebugInfo(IDictionary debugInfo) + { + debugInfo["BaGet:AllowWrites"] = "true"; + } + } + } +} diff --git a/src/BaGet.Core/Entities/MaintenanceSaveChangesInterceptor.cs b/src/BaGet.Core/Entities/MaintenanceSaveChangesInterceptor.cs new file mode 100644 index 000000000..576350b3b --- /dev/null +++ b/src/BaGet.Core/Entities/MaintenanceSaveChangesInterceptor.cs @@ -0,0 +1,47 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace BaGet.Core; + +/// +/// Refuses SaveChanges with a while the +/// is closed, except on a context built with +/// . Every database write in +/// BaGet goes through EF SaveChanges (there is no raw SQL outside migrations), so this is +/// the one place that makes the database read-only. +/// +public sealed class MaintenanceSaveChangesInterceptor : SaveChangesInterceptor +{ + private readonly MaintenanceGate _gate; + + public MaintenanceSaveChangesInterceptor(MaintenanceGate gate) + { + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + } + + public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + { + Check(eventData); + return result; + } + + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, + InterceptionResult result, + CancellationToken cancellationToken = default) + { + Check(eventData); + return new ValueTask>(result); + } + + private void Check(DbContextEventData eventData) + { + if (!_gate.IsClosed) return; + if (MaintenanceGate.AreWritesAllowed(eventData.Context)) return; + + _gate.ThrowIfClosed(); + } +} diff --git a/src/BaGet.Core/Entities/NullContext.cs b/src/BaGet.Core/Entities/NullContext.cs index 2f3170a83..357eca12a 100644 --- a/src/BaGet.Core/Entities/NullContext.cs +++ b/src/BaGet.Core/Entities/NullContext.cs @@ -3,30 +3,125 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; -namespace BaGet.Core +namespace BaGet.Core; + +public class NullContext : IContext { - public class NullContext : IContext - { - public DatabaseFacade Database => throw new NotImplementedException(); + public DatabaseFacade Database => throw new NotImplementedException(); + + public DbSet? Packages { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PackageDependencies { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PackageDeprecations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PackageVulnerabilities { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? CatalogLeafs { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? Organizations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? OrganizationMembers { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PackageOwners { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? ApiKeys { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet? ApiKeyRepositories { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PackageValidations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? AbuseReports { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PackageSymbols { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? ScanResults { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? ScanFindings { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? ScanPolicies { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? NpmPackages { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? NpmVersions { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? NpmDistTags { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? MavenArtifacts { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? MavenVersions { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? MavenFiles { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? OciRepositories { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? OciManifests { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? OciTags { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? OciBlobs { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? OciBlobLinks { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet Packages { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet? RetentionPolicies { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public bool SupportsLimitInSubqueries => throw new NotImplementedException(); + public DbSet? RetentionHolds { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - throw new NotImplementedException(); - } + public DbSet? ArtifactUsages { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public Task RunMigrationsAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public DbSet? ReplicationConfigs { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public Task SaveChangesAsync(CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } + public DbSet? ReplicationRuns { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? ReplicationItems { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? DataProtectionKeys { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? OciUploads { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? Repositories { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? Projects { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? Groups { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? GroupMembers { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PermissionTargets { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? PermissionGrants { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? ProjectMembers { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet? AccessAuditEntries { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public DbSet Users { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public bool SupportsLimitInSubqueries => throw new NotImplementedException(); + + public bool IsUniqueConstraintViolationException(DbUpdateException exception) + { + throw new NotImplementedException(); + } + + public Task RunMigrationsAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public Task SaveChangesAsync(CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } + + public Task BeginKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public Task EndKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken) + { + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/OwnershipOrphanCleanup.cs b/src/BaGet.Core/Entities/OwnershipOrphanCleanup.cs new file mode 100644 index 000000000..51e80fcdb --- /dev/null +++ b/src/BaGet.Core/Entities/OwnershipOrphanCleanup.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// The engines writes SQL for. +public enum OwnershipEngine +{ + Sqlite, + SqlServer, + PostgreSql, + MySql, +} + +/// +/// The SQL the AddOwnershipForeignKeys migration of every provider runs before it adds the foreign keys: rows that +/// already pointed at a repository, project, user or replication configuration that does not exist are removed (or, for an +/// optional reference, detached), children before parents, so the constraints can be created. The statements are ANSI +/// (DELETE ... WHERE ... IN (SELECT ...), never a subquery on the table being changed, which MySQL refuses); only the +/// identifier quoting differs by engine. +/// +/// +/// Frozen for that migration: it names the tables and columns as they were then, so it must not follow later schema changes. +/// Decisions: owned data of a missing repository is deleted with everything under it; an API key limited only to missing +/// repositories is deleted (its rows going would turn it unlimited); a policy whose only target is gone is deleted, one that +/// still has another target is detached from the missing one; a permission target administered by a missing project is deleted +/// (detaching would widen it to every repository); a repository of a missing project is detached from it. +/// +public static class OwnershipOrphanCleanup +{ + /// The engine the statements run on. + public static IReadOnlyList Statements(OwnershipEngine engine) + { + Func q = engine switch + { + OwnershipEngine.SqlServer => name => "[" + name + "]", + OwnershipEngine.MySql => name => "`" + name + "`", + _ => name => "\"" + name + "\"", + }; + var statements = new List(); + void Run(string sql) => statements.Add(sql); + + // The default repository (key 1) may be missing: a database migrated by an early AddRepositories (before the migration + // inserted the row) and not started since. Every row of key 1 belongs to it, so the row is created first, as + // AddRepositories and RepositoryService.EnsureDefaultAsync do, and key 1 is never treated as missing below. + var now = engine switch + { + OwnershipEngine.SqlServer => "SYSUTCDATETIME()", + OwnershipEngine.PostgreSql => "now()", + OwnershipEngine.MySql => "UTC_TIMESTAMP(6)", + _ => "CURRENT_TIMESTAMP", + }; + var yes = engine == OwnershipEngine.PostgreSql ? "TRUE" : "1"; + var dual = engine == OwnershipEngine.MySql ? " FROM DUAL" : string.Empty; + var insertDefault = + $"INSERT INTO {q("Repositories")} ({q("Key")}, {q("Name")}, {q("Format")}, {q("Kind")}, {q("AnonymousRead")}, {q("Created")}) " + + $"SELECT {Repository.DefaultKey}, '{Repository.DefaultName}', 'NuGet', 'Local', {yes}, {now}{dual} " + + $"WHERE NOT EXISTS (SELECT 1 FROM {q("Repositories")} WHERE {q("Key")} = {Repository.DefaultKey} OR {q("Name")} = '{Repository.DefaultName}')"; + if (engine == OwnershipEngine.SqlServer) Run($"SET IDENTITY_INSERT {q("Repositories")} ON"); + Run(insertDefault); + if (engine == OwnershipEngine.SqlServer) Run($"SET IDENTITY_INSERT {q("Repositories")} OFF"); + if (engine == OwnershipEngine.PostgreSql) + { + Run($"SELECT setval(pg_get_serial_sequence('\"Repositories\"', 'Key'), (SELECT MAX({q("Key")}) FROM {q("Repositories")}))"); + } + + string Repos = $"SELECT {q("Key")} FROM {q("Repositories")}"; + string Missing(string column) => $"({q(column)} <> {Repository.DefaultKey} AND {q(column)} NOT IN ({Repos}))"; + string Delete(string table, string where) => $"DELETE FROM {q(table)} WHERE {where}"; + + // Users: keys (their repository limits go with them), memberships. + var noUser = $"{q("UserId")} NOT IN (SELECT {q("Id")} FROM {q("AspNetUsers")})"; + Run(Delete("ApiKeys", noUser)); + Run(Delete("GroupMembers", noUser)); + Run(Delete("OrganizationMembers", noUser)); + // A membership of no organization (the key is optional) is nothing; the user's foreign key would otherwise be the only link. + Run(Delete("OrganizationMembers", $"{q("OrganizationKey")} IS NULL")); + + // API keys limited only to missing repositories would become unlimited: delete them (the limit rows cascade). + Run(Delete("ApiKeys", + $"{q("Key")} IN (SELECT {q("ApiKeyKey")} FROM {q("ApiKeyRepositories")} WHERE {Missing("RepositoryKey")}) " + + $"AND {q("Key")} NOT IN (SELECT {q("ApiKeyKey")} FROM {q("ApiKeyRepositories")} WHERE {q("RepositoryKey")} IN ({Repos}))")); + Run(Delete("ApiKeyRepositories", Missing("RepositoryKey"))); + + // NuGet: a missing repository's packages and what hangs from them. + var orphanPackages = $"SELECT {q("Key")} FROM {q("Packages")} WHERE {Missing("RepositoryKey")}"; + foreach (var child in new[] { "PackageDependencies", "PackageTypes", "TargetFrameworks", "PackageDeprecations", "PackageVulnerabilities" }) + { + Run(Delete(child, $"{q("PackageKey")} IN ({orphanPackages})")); + } + + Run(Delete("PackageValidations", $"{q("PackageKey")} IN ({orphanPackages}) OR {Missing("RepositoryKey")}")); + Run(Delete("Packages", Missing("RepositoryKey"))); + foreach (var table in new[] { "PackageOwners", "CatalogLeafs", "AbuseReports", "PackageSymbols" }) + { + Run(Delete(table, Missing("RepositoryKey"))); + } + + // npm. + var orphanNpm = $"SELECT {q("Key")} FROM {q("NpmPackages")} WHERE {Missing("RepositoryKey")}"; + Run(Delete("NpmVersions", $"{q("PackageKey")} IN ({orphanNpm})")); + Run(Delete("NpmDistTags", $"{q("PackageKey")} IN ({orphanNpm})")); + Run(Delete("NpmPackages", Missing("RepositoryKey"))); + + // Maven. + var orphanArtifacts = $"SELECT {q("Key")} FROM {q("MavenArtifacts")} WHERE {Missing("RepositoryKey")}"; + var orphanVersions = $"SELECT {q("Key")} FROM {q("MavenVersions")} WHERE {q("ArtifactKey")} IN ({orphanArtifacts})"; + Run(Delete("MavenFiles", $"{q("VersionKey")} IN ({orphanVersions})")); + Run(Delete("MavenVersions", $"{q("ArtifactKey")} IN ({orphanArtifacts})")); + Run(Delete("MavenArtifacts", Missing("RepositoryKey"))); + + // OCI: images of a missing repository (and tags of an image that does not exist, which had no constraint), their + // manifests, links, upload sessions; then blobs of a missing repository (links first: the blob side restricts). + var orphanImages = $"SELECT {q("Key")} FROM {q("OciRepositories")} WHERE {Missing("RepositoryKey")}"; + var noImage = $"{q("ImageKey")} NOT IN (SELECT {q("Key")} FROM {q("OciRepositories")})"; + var orphanBlobs = $"SELECT {q("Key")} FROM {q("OciBlobs")} WHERE {Missing("RepositoryKey")}"; + Run(Delete("OciTags", $"{noImage} OR {q("ImageKey")} IN ({orphanImages})")); + Run(Delete("OciBlobLinks", $"{q("ImageKey")} IN ({orphanImages}) OR {q("BlobKey")} IN ({orphanBlobs})")); + Run(Delete("OciUploads", $"{q("ImageKey")} IN ({orphanImages})")); + Run(Delete("OciManifests", $"{q("ImageKey")} IN ({orphanImages})")); + Run(Delete("OciRepositories", Missing("RepositoryKey"))); + Run(Delete("OciBlobs", Missing("RepositoryKey"))); + + // Scanning, retention, replication. + Run(Delete("ScanFindings", $"{q("ResultKey")} IN (SELECT {q("Key")} FROM {q("ScanResults")} WHERE {Missing("RepositoryKey")})")); + Run(Delete("ScanResults", Missing("RepositoryKey"))); + Run(Delete("RetentionHolds", Missing("RepositoryKey"))); + Run(Delete("ArtifactUsages", Missing("RepositoryKey"))); + + var orphanConfigs = $"SELECT {q("Key")} FROM {q("ReplicationConfigs")} WHERE {Missing("RepositoryKey")}"; + var noConfig = $"{q("ConfigKey")} NOT IN (SELECT {q("Key")} FROM {q("ReplicationConfigs")})"; + foreach (var table in new[] { "ReplicationRuns", "ReplicationItems" }) + { + Run(Delete(table, $"{noConfig} OR {q("ConfigKey")} IN ({orphanConfigs})")); + } + + Run(Delete("ReplicationConfigs", Missing("RepositoryKey"))); + + // Nullable references: a policy keeps meaning only while one of its targets exists. + var projects = $"SELECT {q("Key")} FROM {q("Projects")}"; + string RepoGone = $"({q("RepositoryKey")} IS NOT NULL AND {Missing("RepositoryKey")})"; + string ProjectGone = $"({q("ProjectKey")} IS NOT NULL AND {q("ProjectKey")} NOT IN ({projects}))"; + foreach (var table in new[] { "RetentionPolicies", "ScanPolicies" }) + { + Run(Delete(table, + $"({RepoGone} AND ({q("ProjectKey")} IS NULL OR {ProjectGone})) OR ({ProjectGone} AND {q("RepositoryKey")} IS NULL)")); + Run($"UPDATE {q(table)} SET {q("RepositoryKey")} = NULL WHERE {RepoGone}"); + Run($"UPDATE {q(table)} SET {q("ProjectKey")} = NULL WHERE {ProjectGone}"); + } + + Run(Delete("PermissionTargets", ProjectGone)); + Run($"UPDATE {q("Repositories")} SET {q("ProjectKey")} = NULL WHERE {ProjectGone}"); + + return statements; + } +} diff --git a/src/BaGet.Core/Entities/Package.cs b/src/BaGet.Core/Entities/Package.cs index f9d64cceb..5f69de379 100644 --- a/src/BaGet.Core/Entities/Package.cs +++ b/src/BaGet.Core/Entities/Package.cs @@ -1,76 +1,109 @@ -using System; +using System; using System.Collections.Generic; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +// See NuGetGallery's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/Package.cs +public class Package : IRepositoryScoped { - // See NuGetGallery's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/Package.cs - public class Package - { - public int Key { get; set; } + public int Key { get; set; } + + /// + /// The owning repository; see . + /// + public int RepositoryKey { get; set; } - public string Id { get; set; } + public string? Id { get; set; } - public NuGetVersion Version + public NuGetVersion Version + { + get { - get - { - // Favor the original version string as it contains more information. - // Packages uploaded with older versions of BaGet may not have the original version string. - return NuGetVersion.Parse( - OriginalVersionString != null - ? OriginalVersionString - : NormalizedVersionString); - } - - set - { - NormalizedVersionString = value.ToNormalizedString().ToLowerInvariant(); - OriginalVersionString = value.OriginalVersion; - } + // Favor the original version string as it contains more information. + // Packages uploaded with older versions of BaGet may not have the original version string. + #pragma warning disable CS8604 + return NuGetVersion.Parse( + OriginalVersionString != null + ? OriginalVersionString + : NormalizedVersionString); + #pragma warning restore CS8604 } - public string[] Authors { get; set; } - public string Description { get; set; } - public long Downloads { get; set; } - public bool HasReadme { get; set; } - public bool HasEmbeddedIcon { get; set; } - public bool IsPrerelease { get; set; } - public string ReleaseNotes { get; set; } - public string Language { get; set; } - public bool Listed { get; set; } - public string MinClientVersion { get; set; } - public DateTime Published { get; set; } - public bool RequireLicenseAcceptance { get; set; } - public SemVerLevel SemVerLevel { get; set; } - public string Summary { get; set; } - public string Title { get; set; } - - public Uri IconUrl { get; set; } - public Uri LicenseUrl { get; set; } - public Uri ProjectUrl { get; set; } - - public Uri RepositoryUrl { get; set; } - public string RepositoryType { get; set; } - - public string[] Tags { get; set; } - - /// - /// Used for optimistic concurrency. - /// - public byte[] RowVersion { get; set; } - - public List Dependencies { get; set; } - public List PackageTypes { get; set; } - public List TargetFrameworks { get; set; } - - public string NormalizedVersionString { get; set; } - public string OriginalVersionString { get; set; } - - - public string IconUrlString => IconUrl?.AbsoluteUri ?? string.Empty; - public string LicenseUrlString => LicenseUrl?.AbsoluteUri ?? string.Empty; - public string ProjectUrlString => ProjectUrl?.AbsoluteUri ?? string.Empty; - public string RepositoryUrlString => RepositoryUrl?.AbsoluteUri ?? string.Empty; + set + { + NormalizedVersionString = value.ToNormalizedString().ToLowerInvariant(); + OriginalVersionString = value.OriginalVersion; + } } -} + + public string[]? Authors { get; set; } + public string? Description { get; set; } + public long Downloads { get; set; } + public bool HasReadme { get; set; } + public bool HasEmbeddedIcon { get; set; } + public bool IsPrerelease { get; set; } + public string? ReleaseNotes { get; set; } + public string? Language { get; set; } + public bool Listed { get; set; } + public string? MinClientVersion { get; set; } + + /// + /// The time at which the package was published, in UTC. + /// + /// + /// Always stored as UTC. The database returns a whose + /// is , which would + /// otherwise be read as local time when converted to a , + /// shifting the published timestamp by the server's UTC offset. + /// + public DateTime Published + { + get => DateTime.SpecifyKind(_published, DateTimeKind.Utc); + set => _published = value; + } + + private DateTime _published; + + public bool RequireLicenseAcceptance { get; set; } + public SemVerLevel SemVerLevel { get; set; } + public string? Summary { get; set; } + public string? Title { get; set; } + + public Uri? IconUrl { get; set; } + public Uri? LicenseUrl { get; set; } + public Uri? ProjectUrl { get; set; } + + public Uri? RepositoryUrl { get; set; } + public string? RepositoryType { get; set; } + + public string[]? Tags { get; set; } + + /// + /// Used for optimistic concurrency. + /// + public byte[]? RowVersion { get; set; } + + public List? Dependencies { get; set; } + public List? PackageTypes { get; set; } + public List? TargetFrameworks { get; set; } + + /// + /// The deprecation of this version, or null if it is not deprecated. + /// + public PackageDeprecation? Deprecation { get; set; } + + /// + /// The known vulnerabilities affecting this version. + /// + public List? Vulnerabilities { get; set; } + + public string? NormalizedVersionString { get; set; } + public string? OriginalVersionString { get; set; } + + + public string IconUrlString => IconUrl?.AbsoluteUri ?? string.Empty; + public string LicenseUrlString => LicenseUrl?.AbsoluteUri ?? string.Empty; + public string ProjectUrlString => ProjectUrl?.AbsoluteUri ?? string.Empty; + public string RepositoryUrlString => RepositoryUrl?.AbsoluteUri ?? string.Empty; +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageDependency.cs b/src/BaGet.Core/Entities/PackageDependency.cs index 7ae6f61cd..b39b9ed0a 100644 --- a/src/BaGet.Core/Entities/PackageDependency.cs +++ b/src/BaGet.Core/Entities/PackageDependency.cs @@ -1,22 +1,21 @@ -namespace BaGet.Core +namespace BaGet.Core; + +// See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageDependency.cs +public class PackageDependency { - // See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageDependency.cs - public class PackageDependency - { - public int Key { get; set; } + public int Key { get; set; } - /// - /// The dependency's package ID. Null if this is a dependency group without any dependencies. - /// - public string Id { get; set; } + /// + /// The dependency's package ID. Null if this is a dependency group without any dependencies. + /// + public string? Id { get; set; } - /// - /// The dependency's package version. Null if this is a dependency group without any dependencies. - /// - public string VersionRange { get; set; } + /// + /// The dependency's package version. Null if this is a dependency group without any dependencies. + /// + public string? VersionRange { get; set; } - public string TargetFramework { get; set; } + public string? TargetFramework { get; set; } - public Package Package { get; set; } - } -} + public Package? Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageDeprecation.cs b/src/BaGet.Core/Entities/PackageDeprecation.cs new file mode 100644 index 000000000..a8be8169a --- /dev/null +++ b/src/BaGet.Core/Entities/PackageDeprecation.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// A package version marked as deprecated. +/// See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation +/// +public class PackageDeprecation +{ + /// + /// The deprecation reasons the protocol defines. + /// See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation + /// + public static readonly IReadOnlyList KnownReasons = new[] { "Legacy", "CriticalBugs", "Other" }; + + public int Key { get; set; } + + /// + /// Why the package was deprecated. The protocol defines "Legacy", "CriticalBugs" + /// and "Other"; a package may carry more than one. + /// + public string[]? Reasons { get; set; } + + /// + /// Free text explaining the deprecation. Optional. + /// + public string? Message { get; set; } + + /// + /// The ID of the package to use instead. Null if none was suggested. + /// + public string? AlternatePackageId { get; set; } + + /// + /// The versions of the alternate package that may be used, or "*" for any. + /// Null if no alternate package was suggested. + /// + public string? AlternateVersionRange { get; set; } + + /// + /// The key of the deprecated package version. Nullable so that the relationship + /// stays optional in the database: a required one would need a foreign key change, + /// which SQLite cannot make in place. + /// + public int? PackageKey { get; set; } + + public Package? Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageSymbol.cs b/src/BaGet.Core/Entities/PackageSymbol.cs new file mode 100644 index 000000000..121474951 --- /dev/null +++ b/src/BaGet.Core/Entities/PackageSymbol.cs @@ -0,0 +1,33 @@ +using System; + +namespace BaGet.Core; + +/// +/// Records that a portable PDB came from a package version's symbol package (.snupkg). Symbols are stored and +/// served by PDB (symbols/{file}/{key}), not by package, so without this row a version's symbols cannot +/// be listed or deleted. Written when the symbol package is indexed; PDBs indexed before this table existed +/// have no row and stay served but unlisted (see ). +/// +public class PackageSymbol : IRepositoryScoped +{ + public int Key { get; set; } + + /// + /// The owning repository; see . + /// + public int RepositoryKey { get; set; } + + /// The package ID, lower-cased. + public string? PackageId { get; set; } + + /// The normalized package version, lower-cased. + public string? PackageVersion { get; set; } + + /// The PDB's file name, lower-cased, as in its storage path and symbol request. + public string? FileName { get; set; } + + /// The PDB's symbol key: signature GUID plus the fixed age, as indexed. + public string? SymbolKey { get; set; } + + public DateTime Created { get; set; } +} diff --git a/src/BaGet.Core/Entities/PackageType.cs b/src/BaGet.Core/Entities/PackageType.cs index 4e67d694b..5cea8e245 100644 --- a/src/BaGet.Core/Entities/PackageType.cs +++ b/src/BaGet.Core/Entities/PackageType.cs @@ -1,13 +1,12 @@ -namespace BaGet.Core +namespace BaGet.Core; + +// See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageType.cs +public class PackageType { - // See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageType.cs - public class PackageType - { - public int Key { get; set; } + public int Key { get; set; } - public string Name { get; set; } - public string Version { get; set; } + public string? Name { get; set; } + public string? Version { get; set; } - public Package Package { get; set; } - } -} + public Package? Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageValidation.cs b/src/BaGet.Core/Entities/PackageValidation.cs new file mode 100644 index 000000000..de06b8744 --- /dev/null +++ b/src/BaGet.Core/Entities/PackageValidation.cs @@ -0,0 +1,67 @@ +using System; + +namespace BaGet.Core; + +public enum PackageValidationState +{ + Pending = 0, + Succeeded = 1, + Failed = 2, +} + +/// +/// One step of validating a pushed package: a validator's verdict, or the final +/// indexing step. A submission is every row sharing a . +/// +/// +/// The package does not exist while it is validated: it is staged in storage and only +/// indexed once every validator succeeds. So nothing that serves packages needs to +/// know about validation, and a package being validated cannot be downloaded. +/// +public class PackageValidation : IRepositoryScoped +{ + /// + /// The of the step that indexes the package once it is valid. + /// + public const string IndexType = "Index"; + + public int Key { get; set; } + + /// + /// The owning repository; see . + /// + public int RepositoryKey { get; set; } + + public string? SubmissionId { get; set; } + + public string? PackageId { get; set; } + + /// + /// The normalized version. + /// + public string? PackageVersion { get; set; } + + /// + /// The indexed package, once the submission succeeds. Nullable so that the + /// relationship is additive; see . + /// + public int? PackageKey { get; set; } + + public Package? Package { get; set; } + + /// + /// The validator's name, or . + /// + public string? Type { get; set; } + + public PackageValidationState State { get; set; } + + /// + /// Why the step failed, if it did. + /// + public string? Message { get; set; } + + public DateTime Created { get; set; } + + public DateTime? Completed { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageVulnerability.cs b/src/BaGet.Core/Entities/PackageVulnerability.cs new file mode 100644 index 000000000..b3104237e --- /dev/null +++ b/src/BaGet.Core/Entities/PackageVulnerability.cs @@ -0,0 +1,40 @@ +namespace BaGet.Core; + +/// +/// A known vulnerability affecting a package version. +/// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info +/// +public class PackageVulnerability +{ + public int Key { get; set; } + + /// + /// The URL of the advisory describing the vulnerability. + /// + public string? AdvisoryUrl { get; set; } + + /// + /// The severity, as the protocol numbers it: 0 low, 1 moderate, 2 high, 3 critical. + /// + public int Severity { get; set; } + + /// + /// The range of versions the advisory applies to. + /// + public string? VersionRange { get; set; } + + /// + /// Who recorded it: null for an entry set through the metadata API or the Manage page, osv for one the vulnerability + /// scanner wrote from a scan of this version. Setting the list by hand replaces the manual entries only; the next scan + /// replaces the scanner's. + /// + public string? Source { get; set; } + + /// + /// The key of the affected package version. Nullable for the same reason as on + /// . + /// + public int? PackageKey { get; set; } + + public Package? Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/SemVerLevel.cs b/src/BaGet.Core/Entities/SemVerLevel.cs index 29aa5ae41..50a98a20d 100644 --- a/src/BaGet.Core/Entities/SemVerLevel.cs +++ b/src/BaGet.Core/Entities/SemVerLevel.cs @@ -1,15 +1,14 @@ -namespace BaGet.Core +namespace BaGet.Core; + +public enum SemVerLevel { - public enum SemVerLevel - { - /// - /// Either an invalid semantic version or a semantic version v1.0.0 - /// - Unknown = 0, + /// + /// Either an invalid semantic version or a semantic version v1.0.0 + /// + Unknown = 0, - /// - /// A valid semantic version v2.0.0 - /// - SemVer2 = 2 - } -} + /// + /// A valid semantic version v2.0.0 + /// + SemVer2 = 2 +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/TargetFramework.cs b/src/BaGet.Core/Entities/TargetFramework.cs index a8e4a9a84..d0af5d4ae 100644 --- a/src/BaGet.Core/Entities/TargetFramework.cs +++ b/src/BaGet.Core/Entities/TargetFramework.cs @@ -1,11 +1,10 @@ -namespace BaGet.Core +namespace BaGet.Core; + +public class TargetFramework { - public class TargetFramework - { - public int Key { get; set; } + public int Key { get; set; } - public string Moniker { get; set; } + public string? Moniker { get; set; } - public Package Package { get; set; } - } -} + public Package? Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs b/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs index 7dc2967f3..e223c778a 100644 --- a/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs +++ b/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs @@ -3,36 +3,35 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet +namespace BaGet; + +public static class BaGetApplicationExtensions { - public static class BaGetApplicationExtensions + public static BaGetApplication AddFileStorage(this BaGetApplication app) { - public static BaGetApplication AddFileStorage(this BaGetApplication app) - { - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - return app; - } + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + return app; + } - public static BaGetApplication AddFileStorage( - this BaGetApplication app, - Action configure) - { - app.AddFileStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddFileStorage( + this BaGetApplication app, + Action configure) + { + app.AddFileStorage(); + app.Services.Configure(configure); + return app; + } - public static BaGetApplication AddNullStorage(this BaGetApplication app) - { - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - return app; - } + public static BaGetApplication AddNullStorage(this BaGetApplication app) + { + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + return app; + } - public static BaGetApplication AddNullSearch(this BaGetApplication app) - { - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - return app; - } + public static BaGetApplication AddNullSearch(this BaGetApplication app) + { + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs index 7981d7712..85e91ba3c 100644 --- a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs +++ b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs @@ -5,134 +5,161 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet.Core +namespace BaGet.Core; + +public static partial class DependencyInjectionExtensions { - public static partial class DependencyInjectionExtensions + private static readonly string DatabaseTypeKey = $"{nameof(BaGetOptions.Database)}:{nameof(DatabaseOptions.Type)}"; + private static readonly string SearchTypeKey = $"{nameof(BaGetOptions.Search)}:{nameof(SearchOptions.Type)}"; + private static readonly string StorageTypeKey = $"{nameof(BaGetOptions.Storage)}:{nameof(StorageOptions.Type)}"; + + private static readonly string DatabaseSearchType = "Database"; + + /// + /// Add a new provider to the dependency injection container. The provider may + /// provide an implementation of the service, or it may return null. + /// + /// The service that may be provided. + /// The dependency injection container. + /// A handler that provides the service, or null. + /// The dependency injection container. + public static IServiceCollection AddProvider( + this IServiceCollection services, + Func func) + where TService : class { - private static readonly string DatabaseTypeKey = $"{nameof(BaGetOptions.Database)}:{nameof(DatabaseOptions.Type)}"; - private static readonly string SearchTypeKey = $"{nameof(BaGetOptions.Search)}:{nameof(SearchOptions.Type)}"; - private static readonly string StorageTypeKey = $"{nameof(BaGetOptions.Storage)}:{nameof(StorageOptions.Type)}"; - - private static readonly string DatabaseSearchType = "Database"; - - /// - /// Add a new provider to the dependency injection container. The provider may - /// provide an implementation of the service, or it may return null. - /// - /// The service that may be provided. - /// The dependency injection container. - /// A handler that provides the service, or null. - /// The dependency injection container. - public static IServiceCollection AddProvider( - this IServiceCollection services, - Func func) - where TService : class - { - services.AddSingleton>(new DelegateProvider(func)); + services.AddSingleton>(new DelegateProvider(func)); - return services; - } + return services; + } - /// - /// Determine whether a database type is currently active. - /// - /// The application's configuration. - /// The database type that should be checked. - /// Whether the database type is active. - public static bool HasDatabaseType(this IConfiguration config, string value) - { - return config[DatabaseTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); - } + /// + /// Determine whether a database type is currently active. + /// + /// The application's configuration. + /// The database type that should be checked. + /// Whether the database type is active. + public static bool HasDatabaseType(this IConfiguration config, string value) + { + #pragma warning disable CS8602 + return config[DatabaseTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); + #pragma warning restore CS8602 + } - /// - /// Determine whether a search type is currently active. - /// - /// The application's configuration. - /// The search type that should be checked. - /// Whether the search type is active. - public static bool HasSearchType(this IConfiguration config, string value) - { - return config[SearchTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); - } + /// + /// Determine whether a search type is currently active. + /// + /// The application's configuration. + /// The search type that should be checked. + /// Whether the search type is active. + public static bool HasSearchType(this IConfiguration config, string value) + { + #pragma warning disable CS8602 + return config[SearchTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); + #pragma warning restore CS8602 + } - /// - /// Determine whether a storage type is currently active. - /// - /// The application's configuration. - /// The storage type that should be checked. - /// Whether the database type is active. - public static bool HasStorageType(this IConfiguration config, string value) - { - return config[StorageTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); - } + /// + /// Determine whether a storage type is currently active. + /// + /// The application's configuration. + /// The storage type that should be checked. + /// Whether the database type is active. + public static bool HasStorageType(this IConfiguration config, string value) + { + #pragma warning disable CS8602 + return config[StorageTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); + #pragma warning restore CS8602 + } - public static IServiceCollection AddBaGetDbContextProvider( - this IServiceCollection services, - string databaseType, - Action configureContext) - where TContext : DbContext, IContext - { - services.TryAddScoped(provider => provider.GetRequiredService()); - services.TryAddTransient(provider => provider.GetRequiredService()); + public static IServiceCollection AddBaGetDbContextProvider( + this IServiceCollection services, + string databaseType, + Action configureContext) + where TContext : DbContext, IContext + { + services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddTransient(provider => provider.GetRequiredService()); - services.AddDbContext(configureContext); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); - services.AddProvider((provider, config) => - { - if (!config.HasDatabaseType(databaseType)) return null; + services.AddDbContext((provider, options) => + { + configureContext(provider, options); + options.AddInterceptors( + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService()); + }); + + services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasDatabaseType(databaseType)) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - services.AddProvider((provider, config) => - { - if (!config.HasDatabaseType(databaseType)) return null; + services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasDatabaseType(databaseType)) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - services.AddProvider((provider, config) => - { - if (!config.HasSearchType(DatabaseSearchType)) return null; - if (!config.HasDatabaseType(databaseType)) return null; + services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasSearchType(DatabaseSearchType)) return null; + if (!config.HasDatabaseType(databaseType)) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - services.AddProvider((provider, config) => - { - if (!config.HasSearchType(DatabaseSearchType)) return null; - if (!config.HasDatabaseType(databaseType)) return null; + services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasSearchType(DatabaseSearchType)) return null; + if (!config.HasDatabaseType(databaseType)) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return services; - } + return services; + } - /// - /// Runs through all providers to resolve the . - /// - /// The service that will be resolved using providers. - /// The dependency injection container. - /// An instance of the service created by the providers. - public static TService GetServiceFromProviders(IServiceProvider services) - where TService : class - { - // Run through all the providers for the type. Find the first provider that results a non-null result. - var providers = services.GetRequiredService>>(); - var configuration = services.GetRequiredService(); + /// + /// Runs through all providers to resolve the . + /// + /// The service that will be resolved using providers. + /// The dependency injection container. + /// An instance of the service created by the providers. + public static TService? GetServiceFromProviders(IServiceProvider services) + where TService : class + { + // Run through all the providers for the type. Find the first provider that results a non-null result. + var providers = services.GetRequiredService>>(); + var configuration = services.GetRequiredService(); - foreach (var provider in providers) + foreach (var provider in providers) + { + var result = provider.GetOrNull(services, configuration); + if (result != null) { - var result = provider.GetOrNull(services, configuration); - if (result != null) - { - return result; - } + return result; } - - return null; } + + return null; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Virtual.cs b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Virtual.cs new file mode 100644 index 000000000..fc1c15a18 --- /dev/null +++ b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Virtual.cs @@ -0,0 +1,65 @@ +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace BaGet.Core; + +public static partial class DependencyInjectionExtensions +{ + /// + /// Makes the registered repository-aware: a virtual repository is searched through its + /// members (), any other repository by the registered service as before. The + /// last registration is the one wrapped, so a host that registers its search service after + /// AddBaGetApplication calls this again once it has done so; wrapping twice is harmless (an already wrapped + /// registration is left alone). + /// + public static IServiceCollection AddRepositoryAwareSearch(this IServiceCollection services) + { + if (services == null) throw new ArgumentNullException(nameof(services)); + + var original = services.LastOrDefault(d => d.ServiceType == typeof(ISearchService) && !d.IsKeyedService); + if (original == null || original.ImplementationFactory?.Target is RepositorySearchFactory) return services; + + var lifetime = original.Lifetime == ServiceLifetime.Singleton ? ServiceLifetime.Scoped : original.Lifetime; + services.Add(new ServiceDescriptor(typeof(ISearchService), new RepositorySearchFactory(original).Create, lifetime)); + + return services; + } + + private static void AddVirtualRepositoryServices(this IServiceCollection services) + { + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + // The virtual-aware services wrap the concrete implementations, which stay registered on their own so a + // member's scope can ask them directly. + services.TryAddTransient(); + services.TryAddTransient(); + } + + private sealed class RepositorySearchFactory + { + private readonly ServiceDescriptor _original; + + public RepositorySearchFactory(ServiceDescriptor original) + { + _original = original; + } + + public ISearchService Create(IServiceProvider provider) + { + var inner = _original.ImplementationInstance as ISearchService + ?? (_original.ImplementationFactory != null + ? (ISearchService)_original.ImplementationFactory(provider) + : (ISearchService)ActivatorUtilities.CreateInstance(provider, _original.ImplementationType!)); + + return new RepositorySearchService( + inner, + provider.GetRequiredService(), + provider.GetRequiredService()); + } + } +} diff --git a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs index a56c41eab..09926c173 100644 --- a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs +++ b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs @@ -6,214 +6,348 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +public static partial class DependencyInjectionExtensions { - public static partial class DependencyInjectionExtensions + public static IServiceCollection AddBaGetApplication( + this IServiceCollection services, + Action configureAction) { - public static IServiceCollection AddBaGetApplication( - this IServiceCollection services, - Action configureAction) - { - var app = new BaGetApplication(services); - - services.AddConfiguration(); - services.AddBaGetServices(); - services.AddDefaultProviders(); - - configureAction(app); - - services.AddFallbackServices(); - - return services; - } - - /// - /// Configures and validates options. - /// - /// The options type that should be added. - /// The dependency injection container to add options. - /// - /// The configuration key that should be used when configuring the options. - /// If null, the root configuration will be used to configure the options. - /// - /// The dependency injection container. - public static IServiceCollection AddBaGetOptions( - this IServiceCollection services, - string key = null) - where TOptions : class - { - services.AddSingleton>(new ValidateBaGetOptions(key)); - services.AddSingleton>(provider => - { - var config = provider.GetRequiredService(); - if (key != null) - { - config = config.GetSection(key); - } + var app = new BaGetApplication(services); - return new BindOptions(config); - }); + services.AddConfiguration(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddBaGetServices(); + services.AddDefaultProviders(); - return services; - } + configureAction(app); - private static void AddConfiguration(this IServiceCollection services) - { - services.AddBaGetOptions(); - services.AddBaGetOptions(nameof(BaGetOptions.Database)); - services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - services.AddBaGetOptions(nameof(BaGetOptions.Mirror)); - services.AddBaGetOptions(nameof(BaGetOptions.Search)); - services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - } - - private static void AddBaGetServices(this IServiceCollection services) - { - services.TryAddSingleton(); - services.TryAddSingleton(); - - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - - services.TryAddSingleton(HttpClientFactory); - services.TryAddSingleton(NuGetClientFactoryFactory); - - services.TryAddScoped(); - - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddSingleton(); - services.TryAddTransient(); - - services.TryAddTransient(UpstreamClientFactory); - } - - private static void AddDefaultProviders(this IServiceCollection services) - { - services.AddProvider((provider, configuration) => - { - if (!configuration.HasSearchType("null")) return null; + services.AddFallbackServices(); + + return services; + } - return provider.GetRequiredService(); - }); + /// + /// Configures and validates options. + /// + /// The options type that should be added. + /// The dependency injection container to add options. + /// + /// The configuration key that should be used when configuring the options. + /// If null, the root configuration will be used to configure the options. + /// + /// The dependency injection container. + public static IServiceCollection AddBaGetOptions( + this IServiceCollection services, + string? key = null) + where TOptions : class + { + services.AddSingleton>(new ValidateBaGetOptions(key)); - services.AddProvider((provider, configuration) => + // The Settings page lists every options type, provider-specific ones included. + services.AddSingleton(new SettingsSchemaRegistration(typeof(TOptions), key)); + services.AddSingleton>(provider => + { + var config = provider.GetRequiredService(); + if (key != null) { - if (!configuration.HasSearchType("null")) return null; + config = config.GetSection(key); + } - return provider.GetRequiredService(); - }); + return new BindOptions(config); + }); - services.AddProvider((provider, configuration) => - { - if (configuration.HasStorageType("filesystem")) - { - return provider.GetRequiredService(); - } + return services; + } - if (configuration.HasStorageType("null")) - { - return provider.GetRequiredService(); - } + private static void AddConfiguration(this IServiceCollection services) + { + services.AddBaGetOptions(); + services.AddBaGetOptions(nameof(BaGetOptions.Database)); + services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + services.AddBaGetOptions(nameof(BaGetOptions.Mirror)); + services.AddBaGetOptions(nameof(BaGetOptions.Remote)); + services.AddBaGetOptions(nameof(BaGetOptions.Npm)); + services.AddBaGetOptions(nameof(BaGetOptions.Maven)); + services.AddBaGetOptions(nameof(BaGetOptions.Oci)); + services.AddBaGetOptions(nameof(BaGetOptions.Scanning)); + services.AddBaGetOptions(nameof(BaGetOptions.Feeds)); + services.AddBaGetOptions(nameof(BaGetOptions.Accounts)); + services.AddBaGetOptions(nameof(BaGetOptions.Email)); + services.AddBaGetOptions(nameof(BaGetOptions.Site)); + services.AddBaGetOptions(nameof(BaGetOptions.Validation)); + services.AddBaGetOptions(nameof(BaGetOptions.Telemetry)); + services.AddBaGetOptions(nameof(BaGetOptions.Ha)); + services.AddBaGetOptions("Serilog"); + services.AddBaGetOptions(nameof(BaGetOptions.Search)); + services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + } - return null; - }); - } + private static void AddBaGetServices(this IServiceCollection services) + { + services.TryAddSingleton(); + services.TryAddSingleton(); + + services.TryAddSingleton(); + services.TryAddSingleton(); + // Cluster mode (Ha:Enabled): the startup check runs first, the rest only does something when a store is registered. + services.TryAddSingleton(); + services.AddHostedService(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddHostedService(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddHostedService(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + services.TryAddSingleton(HttpClientFactory); + services.TryAddSingleton(NuGetClientFactoryFactory); + + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddSingleton(provider => new FormatRegistry(provider.GetServices())); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.AddHostedService(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(provider => + { + // An explicitly registered protector wins; else the host's data protection (ASP.NET Core registers it); + // else none, and credentials are refused rather than stored in clear. + var protector = provider.GetService(); + var dataProtection = provider.GetService(); + + return new RemoteSettingsCodec(protector ?? (dataProtection == null ? null : new DataProtectionCredentialProtector(dataProtection))); + }); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + + services.TryAddScoped(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddScoped(); + + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddSingleton(); + services.AddHostedService(); + + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + // The in-process lease of a single node; with Ha:Enabled the host replaces it with ClusterJobLease (a lease in the shared store). + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddHostedService(); + services.TryAddScoped(); + + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddSingleton(); + services.TryAddTransient(); + + services.TryAddTransient(UpstreamClientFactory); + + services.AddVirtualRepositoryServices(); + } - private static void AddFallbackServices(this IServiceCollection services) + private static void AddDefaultProviders(this IServiceCollection services) + { + #pragma warning disable CS8621, CS8634 + services.AddProvider((provider, configuration) => + #pragma warning restore CS8621, CS8634 { - services.TryAddScoped(); - - // BaGet's services have multiple implementations that live side-by-side. - // The application will choose the implementation using one of two ways: - // - // 1. Using the first implementation that was registered in the dependency injection - // container. This is the strategy used by applications that embed BaGet. - // 2. Using "providers". The providers will examine the application's configuration to - // determine whether its service implementation is active. Thsi is the strategy used - // by the default BaGet application. - // - // BaGet has database and search services, but the database services are special - // in that they may also act as search services. If an application registers the - // database service first and the search service second, the application should - // use the search service even though it wasn't registered first. Furthermore, - // if an application registers a database service without a search service, the - // database service should be used for search. This effect is achieved by deferring - // the database search service's registration until the very end. - services.TryAddTransient(provider => provider.GetRequiredService()); - services.TryAddTransient(provider => provider.GetRequiredService()); - } - - private static HttpClient HttpClientFactory(IServiceProvider provider) + if (!configuration.HasSearchType("null")) return null; + + return provider.GetRequiredService(); + }); + + #pragma warning disable CS8621, CS8634 + services.AddProvider((provider, configuration) => + #pragma warning restore CS8621, CS8634 { - var options = provider.GetRequiredService>().Value; + if (!configuration.HasSearchType("null")) return null; - var assembly = Assembly.GetEntryAssembly(); - var assemblyName = assembly.GetName().Name; - var assemblyVersion = assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + return provider.GetRequiredService(); + }); - var client = new HttpClient(new HttpClientHandler + services.AddProvider((provider, configuration) => + { + if (configuration.HasStorageType("filesystem")) { - AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, - }); + return provider.GetRequiredService(); + } - client.DefaultRequestHeaders.Add("User-Agent", $"{assemblyName}/{assemblyVersion}"); - client.Timeout = TimeSpan.FromSeconds(options.PackageDownloadTimeoutSeconds); + if (configuration.HasStorageType("null")) + { + return provider.GetRequiredService(); + } - return client; - } + #pragma warning disable CS8603 + return null; + #pragma warning restore CS8603 + }); + } - private static NuGetClientFactory NuGetClientFactoryFactory(IServiceProvider provider) - { - var httpClient = provider.GetRequiredService(); - var options = provider.GetRequiredService>(); + private static void AddFallbackServices(this IServiceCollection services) + { + services.TryAddScoped(); + + // BaGet's services have multiple implementations that live side-by-side. + // The application will choose the implementation using one of two ways: + // + // 1. Using the first implementation that was registered in the dependency injection + // container. This is the strategy used by applications that embed BaGet. + // 2. Using "providers". The providers will examine the application's configuration to + // determine whether its service implementation is active. Thsi is the strategy used + // by the default BaGet application. + // + // BaGet has database and search services, but the database services are special + // in that they may also act as search services. If an application registers the + // database service first and the search service second, the application should + // use the search service even though it wasn't registered first. Furthermore, + // if an application registers a database service without a search service, the + // database service should be used for search. This effect is achieved by deferring + // the database search service's registration until the very end. + services.TryAddTransient(provider => provider.GetRequiredService()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); + services.TryAddTransient(provider => provider.GetRequiredService()); + + // A virtual repository is searched through its members; a host that registers its own search service after this + // calls AddRepositoryAwareSearch again (Program does). + services.AddRepositoryAwareSearch(); + } - return new NuGetClientFactory( - httpClient, - options.Value.PackageSource.ToString()); - } + private static HttpClient HttpClientFactory(IServiceProvider provider) + { + var options = provider.GetRequiredService>().Value; - private static IUpstreamClient UpstreamClientFactory(IServiceProvider provider) + var assembly = Assembly.GetEntryAssembly(); + var assemblyName = assembly?.GetName().Name; + var assemblyVersion = assembly?.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + + var client = new HttpClient(new HttpClientHandler { - var options = provider.GetRequiredService>(); + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + }); - // TODO: Convert to switch expression. - if (!options.Value.Enabled) - { - return provider.GetRequiredService(); - } + client.DefaultRequestHeaders.Add("User-Agent", $"{assemblyName}/{assemblyVersion}"); + client.Timeout = TimeSpan.FromSeconds(options.PackageDownloadTimeoutSeconds); - else if (options.Value.Legacy) - { - return provider.GetRequiredService(); - } + return client; + } - else - { - return provider.GetRequiredService(); - } - } + private static NuGetClientFactory NuGetClientFactoryFactory(IServiceProvider provider) + { + var httpClient = provider.GetRequiredService(); + var options = provider.GetRequiredService>(); + + return new NuGetClientFactory( + httpClient, + options.Value.PackageSource?.ToString()); + } + + private static IUpstreamClient UpstreamClientFactory(IServiceProvider provider) + { + // Every repository has the client of its own upstream: a remote repository's, the default repository's mirror + // (Mirror:* through the "mirror" remote repository), or none. See RemoteUpstreamClient. + return new RemoteUpstreamClient( + provider.GetService(), + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService()); } } diff --git a/src/BaGet.Core/Extensions/IProvider.cs b/src/BaGet.Core/Extensions/IProvider.cs index 1a7b5612d..8aa434906 100644 --- a/src/BaGet.Core/Extensions/IProvider.cs +++ b/src/BaGet.Core/Extensions/IProvider.cs @@ -1,47 +1,46 @@ using System; using Microsoft.Extensions.Configuration; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Attempts to provide the . +/// +/// The service that may be provided. +public interface IProvider { /// - /// Attempts to provide the . + /// Attempt to provide the . /// - /// The service that may be provided. - public interface IProvider - { - /// - /// Attempt to provide the . - /// - /// The dependency injection container. - /// The app's configuration. - /// - /// An instance of , or, null if the - /// provider is not currently active in the . - /// - TService GetOrNull(IServiceProvider provider, IConfiguration configuration); - } + /// The dependency injection container. + /// The app's configuration. + /// + /// An instance of , or, null if the + /// provider is not currently active in the . + /// + TService GetOrNull(IServiceProvider provider, IConfiguration configuration); +} + +/// +/// Implements as a delegate. +/// +internal class DelegateProvider : IProvider +{ + private readonly Func _func; /// - /// Implements as a delegate. + /// Create an using a delegate. /// - internal class DelegateProvider : IProvider + /// + /// A delegate that returns an instance of , or, + /// null if the provider is not currently active due to the app's configuration. + public DelegateProvider(Func func) { - private readonly Func _func; - - /// - /// Create an using a delegate. - /// - /// - /// A delegate that returns an instance of , or, - /// null if the provider is not currently active due to the app's configuration. - public DelegateProvider(Func func) - { - _func = func ?? throw new ArgumentNullException(nameof(func)); - } + _func = func ?? throw new ArgumentNullException(nameof(func)); + } - public TService GetOrNull(IServiceProvider provider, IConfiguration configuration) - { - return _func(provider, configuration); - } + public TService GetOrNull(IServiceProvider provider, IConfiguration configuration) + { + return _func(provider, configuration); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs b/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs index 3e01432bf..1caae7fef 100644 --- a/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs +++ b/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs @@ -7,216 +7,225 @@ using NuGet.Common; using NuGet.Packaging; -namespace BaGet.Core +namespace BaGet.Core; + +using NuGetPackageType = NuGet.Packaging.Core.PackageType; + +public static class PackageArchiveReaderExtensions { - using NuGetPackageType = NuGet.Packaging.Core.PackageType; + public static bool HasReadme(this PackageArchiveReader package) + => !string.IsNullOrEmpty(package.NuspecReader.GetReadme()); + + public static bool HasEmbeddedIcon(this PackageArchiveReader package) + => !string.IsNullOrEmpty(package.NuspecReader.GetIcon()); - public static class PackageArchiveReaderExtensions + public async static Task GetReadmeAsync( + this PackageArchiveReader package, + CancellationToken cancellationToken) { - public static bool HasReadme(this PackageArchiveReader package) - => !string.IsNullOrEmpty(package.NuspecReader.GetReadme()); + var readmePath = package.NuspecReader.GetReadme(); + if (readmePath == null) + { + throw new InvalidOperationException("Package does not have a readme!"); + } - public static bool HasEmbeddedIcon(this PackageArchiveReader package) - => !string.IsNullOrEmpty(package.NuspecReader.GetIcon()); + return await package.GetStreamAsync(readmePath, cancellationToken); + } - public async static Task GetReadmeAsync( - this PackageArchiveReader package, - CancellationToken cancellationToken) - { - var readmePath = package.NuspecReader.GetReadme(); - if (readmePath == null) - { - throw new InvalidOperationException("Package does not have a readme!"); - } + public async static Task GetIconAsync( + this PackageArchiveReader package, + CancellationToken cancellationToken) + { + return await package.GetStreamAsync( + PathUtility.StripLeadingDirectorySeparators(package.NuspecReader.GetIcon()), + cancellationToken); + } - return await package.GetStreamAsync(readmePath, cancellationToken); - } + public static Package GetPackageMetadata(this PackageArchiveReader packageReader) + { + var nuspec = packageReader.NuspecReader; - public async static Task GetIconAsync( - this PackageArchiveReader package, - CancellationToken cancellationToken) - { - return await package.GetStreamAsync( - PathUtility.StripLeadingDirectorySeparators(package.NuspecReader.GetIcon()), - cancellationToken); - } + (var repositoryUri, var repositoryType) = GetRepositoryMetadata(nuspec); - public static Package GetPackageMetadata(this PackageArchiveReader packageReader) + return new Package { - var nuspec = packageReader.NuspecReader; - - (var repositoryUri, var repositoryType) = GetRepositoryMetadata(nuspec); + Id = nuspec.GetId(), + Version = nuspec.GetVersion(), + Authors = ParseAuthors(nuspec.GetAuthors()), + Description = nuspec.GetDescription(), + HasReadme = packageReader.HasReadme(), + HasEmbeddedIcon = packageReader.HasEmbeddedIcon(), + IsPrerelease = nuspec.GetVersion().IsPrerelease, + Language = nuspec.GetLanguage() ?? string.Empty, + ReleaseNotes = nuspec.GetReleaseNotes() ?? string.Empty, + Listed = true, + MinClientVersion = nuspec.GetMinClientVersion()?.ToNormalizedString() ?? string.Empty, + Published = DateTime.UtcNow, + RequireLicenseAcceptance = nuspec.GetRequireLicenseAcceptance(), + SemVerLevel = GetSemVerLevel(nuspec), + Summary = nuspec.GetSummary(), + Title = nuspec.GetTitle(), + IconUrl = ParseUri(nuspec.GetIconUrl()), + LicenseUrl = ParseUri(nuspec.GetLicenseUrl()), + ProjectUrl = ParseUri(nuspec.GetProjectUrl()), + RepositoryUrl = repositoryUri, + RepositoryType = repositoryType, + Dependencies = GetDependencies(nuspec), + Tags = ParseTags(nuspec.GetTags()), + PackageTypes = GetPackageTypes(nuspec), + TargetFrameworks = GetTargetFrameworks(packageReader), + }; + } - return new Package - { - Id = nuspec.GetId(), - Version = nuspec.GetVersion(), - Authors = ParseAuthors(nuspec.GetAuthors()), - Description = nuspec.GetDescription(), - HasReadme = packageReader.HasReadme(), - HasEmbeddedIcon = packageReader.HasEmbeddedIcon(), - IsPrerelease = nuspec.GetVersion().IsPrerelease, - Language = nuspec.GetLanguage() ?? string.Empty, - ReleaseNotes = nuspec.GetReleaseNotes() ?? string.Empty, - Listed = true, - MinClientVersion = nuspec.GetMinClientVersion()?.ToNormalizedString() ?? string.Empty, - Published = DateTime.UtcNow, - RequireLicenseAcceptance = nuspec.GetRequireLicenseAcceptance(), - SemVerLevel = GetSemVerLevel(nuspec), - Summary = nuspec.GetSummary(), - Title = nuspec.GetTitle(), - IconUrl = ParseUri(nuspec.GetIconUrl()), - LicenseUrl = ParseUri(nuspec.GetLicenseUrl()), - ProjectUrl = ParseUri(nuspec.GetProjectUrl()), - RepositoryUrl = repositoryUri, - RepositoryType = repositoryType, - Dependencies = GetDependencies(nuspec), - Tags = ParseTags(nuspec.GetTags()), - PackageTypes = GetPackageTypes(nuspec), - TargetFrameworks = GetTargetFrameworks(packageReader), - }; + // Based off https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/SemVerLevelKey.cs + private static SemVerLevel GetSemVerLevel(NuspecReader nuspec) + { + if (nuspec.GetVersion().IsSemVer2) + { + return SemVerLevel.SemVer2; } - // Based off https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/SemVerLevelKey.cs - private static SemVerLevel GetSemVerLevel(NuspecReader nuspec) + foreach (var dependencyGroup in nuspec.GetDependencyGroups()) { - if (nuspec.GetVersion().IsSemVer2) + foreach (var dependency in dependencyGroup.Packages) { - return SemVerLevel.SemVer2; - } - - foreach (var dependencyGroup in nuspec.GetDependencyGroups()) - { - foreach (var dependency in dependencyGroup.Packages) + if ((dependency.VersionRange.MinVersion != null && dependency.VersionRange.MinVersion.IsSemVer2) + || (dependency.VersionRange.MaxVersion != null && dependency.VersionRange.MaxVersion.IsSemVer2)) { - if ((dependency.VersionRange.MinVersion != null && dependency.VersionRange.MinVersion.IsSemVer2) - || (dependency.VersionRange.MaxVersion != null && dependency.VersionRange.MaxVersion.IsSemVer2)) - { - return SemVerLevel.SemVer2; - } + return SemVerLevel.SemVer2; } } - - return SemVerLevel.Unknown; } - private static Uri ParseUri(string uriString) - { - if (string.IsNullOrEmpty(uriString)) return null; - - return new Uri(uriString); - } + return SemVerLevel.Unknown; + } - private static string[] ParseAuthors(string authors) - { - if (string.IsNullOrEmpty(authors)) return new string[0]; + private static Uri? ParseUri(string uriString) + { + if (string.IsNullOrEmpty(uriString)) return null; - return authors.Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - } + // These URLs are optional display metadata and are not validated when a package + // is built, so a package can carry a relative or malformed one. Ignore a URL that + // cannot be served rather than failing the whole package, which is how the + // repository URL below is already treated. + if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) return null; - private static string[] ParseTags(string tags) - { - if (string.IsNullOrEmpty(tags)) return new string[0]; + return uri; + } - return tags.Split(new[] { ',', ';', ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - } + private static string[] ParseAuthors(string authors) + { + if (string.IsNullOrEmpty(authors)) return new string[0]; - private static (Uri repositoryUrl, string repositoryType) GetRepositoryMetadata(NuspecReader nuspec) - { - var repository = nuspec.GetRepositoryMetadata(); + return authors.Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + } - if (string.IsNullOrEmpty(repository?.Url) || - !Uri.TryCreate(repository.Url, UriKind.Absolute, out var repositoryUri)) - { - return (null, null); - } + private static string[] ParseTags(string tags) + { + if (string.IsNullOrEmpty(tags)) return new string[0]; - if (repositoryUri.Scheme != Uri.UriSchemeHttps) - { - return (null, null); - } + return tags.Split(new[] { ',', ';', ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + } - if (repository.Type.Length > 100) - { - throw new InvalidOperationException("Repository type must be less than or equal 100 characters"); - } + private static (Uri repositoryUrl, string repositoryType) GetRepositoryMetadata(NuspecReader nuspec) + { + var repository = nuspec.GetRepositoryMetadata(); - return (repositoryUri, repository.Type); + if (string.IsNullOrEmpty(repository?.Url) || + !Uri.TryCreate(repository.Url, UriKind.Absolute, out var repositoryUri)) + { + #pragma warning disable CS8619 + return (null, null); + #pragma warning restore CS8619 } - private static List GetDependencies(NuspecReader nuspec) + if (repositoryUri.Scheme != Uri.UriSchemeHttps) { - var dependencies = new List(); - - foreach (var group in nuspec.GetDependencyGroups()) - { - var targetFramework = group.TargetFramework.GetShortFolderName(); + #pragma warning disable CS8619 + return (null, null); + #pragma warning restore CS8619 + } - if (!group.Packages.Any()) - { - dependencies.Add(new PackageDependency - { - Id = null, - VersionRange = null, - TargetFramework = targetFramework, - }); - } + if (repository.Type.Length > 100) + { + throw new InvalidOperationException("Repository type must be less than or equal 100 characters"); + } - foreach (var dependency in group.Packages) - { - dependencies.Add(new PackageDependency - { - Id = dependency.Id, - VersionRange = dependency.VersionRange?.ToString(), - TargetFramework = targetFramework, - }); - } - } + return (repositoryUri, repository.Type); + } - return dependencies; - } + private static List GetDependencies(NuspecReader nuspec) + { + var dependencies = new List(); - private static List GetPackageTypes(NuspecReader nuspec) + foreach (var group in nuspec.GetDependencyGroups()) { - var packageTypes = nuspec - .GetPackageTypes() - .Select(t => new PackageType - { - Name = t.Name, - Version = t.Version.ToString() - }) - .ToList(); + var targetFramework = group.TargetFramework.GetShortFolderName(); - // Default to the standard "dependency" package type if no types were found. - if (packageTypes.Count == 0) + if (!group.Packages.Any()) { - packageTypes.Add(new PackageType + dependencies.Add(new PackageDependency { - Name = NuGetPackageType.Dependency.Name, - Version = NuGetPackageType.Dependency.Version.ToString(), + Id = null, + VersionRange = null, + TargetFramework = targetFramework, }); } - return packageTypes; + foreach (var dependency in group.Packages) + { + dependencies.Add(new PackageDependency + { + Id = dependency.Id, + VersionRange = dependency.VersionRange?.ToString(), + TargetFramework = targetFramework, + }); + } } - private static List GetTargetFrameworks(PackageArchiveReader packageReader) + return dependencies; + } + + private static List GetPackageTypes(NuspecReader nuspec) + { + var packageTypes = nuspec + .GetPackageTypes() + .Select(t => new PackageType + { + Name = t.Name, + Version = t.Version.ToString() + }) + .ToList(); + + // Default to the standard "dependency" package type if no types were found. + if (packageTypes.Count == 0) { - var targetFrameworks = packageReader - .GetSupportedFrameworks() - .Select(f => new TargetFramework - { - Moniker = f.GetShortFolderName() - }) - .ToList(); + packageTypes.Add(new PackageType + { + Name = NuGetPackageType.Dependency.Name, + Version = NuGetPackageType.Dependency.Version.ToString(), + }); + } + + return packageTypes; + } - // Default to the "any" framework if no frameworks were found. - if (targetFrameworks.Count == 0) + private static List GetTargetFrameworks(PackageArchiveReader packageReader) + { + var targetFrameworks = packageReader + .GetSupportedFrameworks() + .Select(f => new TargetFramework { - targetFrameworks.Add(new TargetFramework { Moniker = "any" }); - } + Moniker = f.GetShortFolderName() + }) + .ToList(); - return targetFrameworks; + // Default to the "any" framework if no frameworks were found. + if (targetFrameworks.Count == 0) + { + targetFrameworks.Add(new TargetFramework { Moniker = "any" }); } + + return targetFrameworks; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/StreamExtensions.cs b/src/BaGet.Core/Extensions/StreamExtensions.cs index bfe9d840a..3a1567241 100644 --- a/src/BaGet.Core/Extensions/StreamExtensions.cs +++ b/src/BaGet.Core/Extensions/StreamExtensions.cs @@ -1,59 +1,57 @@ using System; using System.IO; -using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public static class StreamExtensions { - public static class StreamExtensions + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; + + /// + /// Copies a stream to a file, and returns that file as a stream. The underlying file will be + /// deleted when the resulting stream is disposed. + /// + /// The stream to be copied, at its current position. + /// + /// The copied stream, with its position reset to the beginning. + public static async Task AsTemporaryFileStreamAsync( + this Stream original, + CancellationToken cancellationToken = default) { - // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 - private const int DefaultCopyBufferSize = 81920; + var result = new FileStream( + Path.GetTempFileName(), + FileMode.Create, + FileAccess.ReadWrite, + FileShare.None, + DefaultCopyBufferSize, + FileOptions.DeleteOnClose); - /// - /// Copies a stream to a file, and returns that file as a stream. The underlying file will be - /// deleted when the resulting stream is disposed. - /// - /// The stream to be copied, at its current position. - /// - /// The copied stream, with its position reset to the beginning. - public static async Task AsTemporaryFileStreamAsync( - this Stream original, - CancellationToken cancellationToken = default) + try { - var result = new FileStream( - Path.GetTempFileName(), - FileMode.Create, - FileAccess.ReadWrite, - FileShare.None, - DefaultCopyBufferSize, - FileOptions.DeleteOnClose); - - try - { - await original.CopyToAsync(result, DefaultCopyBufferSize, cancellationToken); - result.Position = 0; - } - catch (Exception) - { - result.Dispose(); - throw; - } - - return result; + await original.CopyToAsync(result, DefaultCopyBufferSize, cancellationToken); + result.Position = 0; } + catch (Exception) + { + result.Dispose(); + throw; + } + + return result; + } - public static bool Matches(this Stream content, Stream target) + public static bool Matches(this Stream content, Stream target) + { + using (var sha256 = SHA256.Create()) { - using (var sha256 = SHA256.Create()) - { - var contentHash = sha256.ComputeHash(content); - var targetHash = sha256.ComputeHash(target); + var contentHash = sha256.ComputeHash(content); + var targetHash = sha256.ComputeHash(target); - return contentHash.SequenceEqual(targetHash); - } + return contentHash.SequenceEqual(targetHash); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/SystemTime.cs b/src/BaGet.Core/Extensions/SystemTime.cs index 4d8195fc8..d565908f4 100644 --- a/src/BaGet.Core/Extensions/SystemTime.cs +++ b/src/BaGet.Core/Extensions/SystemTime.cs @@ -1,12 +1,11 @@ using System; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A wrapper that allows for unit tests related to system time. +/// +public class SystemTime { - /// - /// A wrapper that allows for unit tests related to system time. - /// - public class SystemTime - { - public virtual DateTime UtcNow => DateTime.UtcNow; - } -} + public virtual DateTime UtcNow => DateTime.UtcNow; +} \ No newline at end of file diff --git a/src/BaGet.Core/Formats/Docker/DockerFormatModule.cs b/src/BaGet.Core/Formats/Docker/DockerFormatModule.cs new file mode 100644 index 000000000..a5fb0c044 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/DockerFormatModule.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Docker / OCI on the format layer: the Distribution Spec v1.1 at /v2/{repository}/{image}/… (the BaGet repository is the first +/// path segment, so docker push host/libs/team/app:1 pushes image team/app into repository libs), blobs by +/// digest under docker/ in storage. A local repository holds pushed images, a remote one caches an upstream registry +/// (), a virtual one merges members (). Needs a store that streams +/// (). See . +/// +public class DockerFormatModule : IFormatModule +{ + /// + public RepositoryFormat Format => RepositoryFormat.Docker; + + /// + public string DisplayName => "Docker"; + + /// + public string RoutePrefix => "v2"; + + /// + /// + /// A registry is addressed from the server root, not from the repository base, and the repository is part of the image + /// reference: {repo} stands for the repository's name, and the path is relative to the server's root (the NuGet + /// /r/{repo}/ prefix does not apply). + /// + public string FeedPath => "v2/{repo}/"; + + /// + public IReadOnlyCollection CreatableKinds { get; } = new[] { RepositoryKind.Local, RepositoryKind.Remote }; + + /// + public bool SupportsVirtual => true; + + /// + public bool RequiresStreamingStorage => true; + + /// + public IReadOnlyList StorageFolders { get; } = new[] { OciNames.StorageFolder }; + + /// + public IReadOnlyList CreateFields { get; } = Array.Empty(); + + /// + public string? CreateSettings(IReadOnlyDictionary fields) => null; + + /// + public IReadOnlyList RepositoryLinks(RepositoryInfo repository) => new[] + { + FormatLink.ToScreen("browse", "Browse", "DockerBrowse", "Images"), + }; + + /// + public async Task> CountArtifactsAsync(IContext context, CancellationToken cancellationToken) + => await context.OciRepositories! + .IgnoreQueryFilters() + .GroupBy(i => i.RepositoryKey) + .Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken) + .ConfigureAwait(false); + + /// + public async Task GetUsageAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + var images = await context.OciRepositories!.IgnoreQueryFilters().CountAsync(i => i.RepositoryKey == repositoryKey, cancellationToken).ConfigureAwait(false); + + return new FormatUsage(images, PendingWork: false); + } + + /// + /// + /// counts image rows, and a repository is deleted only when it has none, so the images and with them + /// the manifests, tags, links and upload sessions are already gone here; what can be left are blob rows nobody holds. + /// + public async Task StagePurgeAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + context.OciBlobs!.RemoveRange(await context.OciBlobs!.IgnoreQueryFilters().Where(b => b.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + } +} + +/// Docker's : images whose name contains the query. +public class DockerFormatSearchProvider : IFormatSearchProvider +{ + private readonly IOciRegistry _registry; + + /// The registry of the request. + public DockerFormatSearchProvider(IOciRegistry registry) + { + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Docker; + + /// + public async Task SearchAsync(FormatSearchQuery query, CancellationToken cancellationToken) + { + if (query == null) throw new ArgumentNullException(nameof(query)); + + var page = await _registry.ListImagesAsync(query.Query, query.Skip, query.Take, canRead: null, cancellationToken).ConfigureAwait(false); + + return new FormatSearchPage( + page.Total, + page.Images.Select(i => new FormatSearchHit(i.Name, null, $"{i.Tags} tag{(i.Tags == 1 ? string.Empty : "s")}", Downloads: 0)).ToList()); + } +} diff --git a/src/BaGet.Core/Formats/Docker/DockerFormatScanner.cs b/src/BaGet.Core/Formats/Docker/DockerFormatScanner.cs new file mode 100644 index 000000000..d26ead66e --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/DockerFormatScanner.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Docker's : container images are scanned by Trivy (), one result per +/// image manifest, named by image and manifest digest. Indexes (multi-platform lists), signatures and other artifacts that refer +/// to an image are not images and are not scanned; each platform's manifest is. +/// +public sealed class DockerFormatScanner : IFormatScanner +{ + private readonly IContext _context; + + public DockerFormatScanner(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Docker; + + /// + public ScanEngine Engine => ScanEngine.Image; + + /// + public Task> ListComponentsAsync(string name, string version, CancellationToken cancellationToken) + => Task.FromResult>(Array.Empty()); + + /// + public async Task GetImageReferenceAsync(string name, string version, CancellationToken cancellationToken) + { + if (_context is NullContext || !OciNames.IsValidDigest(version)) return null; + + // Only an image manifest is scannable (not an index, a signature or another artifact), so only it is "stored" for the gate. + var row = await _context.OciManifests! + .AsNoTracking() + .Join(_context.OciRepositories!.Where(r => r.Name == name), m => m.ImageKey, r => r.Key, (m, r) => new { m.Digest, m.MediaType, m.Content }) + .Where(m => m.Digest == version) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + return row != null && IsImage(row.MediaType, row.Content) ? name + "@" + version : null; + } + + /// + public async Task> ListArtifactsAsync(CancellationToken cancellationToken) + { + if (_context is NullContext) return Array.Empty(); + + // Indexes and other artifacts are cut in SQL, so their (large) content is never loaded. + var imageTypes = OciNames.ImageManifestTypes.ToArray(); + var rows = await _context.OciManifests! + .AsNoTracking() + .Where(m => imageTypes.Contains(m.MediaType!)) + .Join(_context.OciRepositories!, m => m.ImageKey, r => r.Key, (m, r) => new { r.Name, m.Digest, m.MediaType, m.Content }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + return rows + .Where(r => IsImage(r.MediaType, r.Content)) + .Select(r => new ScanArtifact(r.Name!, r.Digest!)) + .ToList(); + } + + /// + /// Whether a manifest is a container image (not an index, a signature or another artifact). Decided from the manifest's media type + /// and its config descriptor's media type only: artifactType and subject are self-declared and ignored by the + /// runtimes that run the image, so they must not take an image out of scanning. + /// + public static bool IsImage(string? mediaType, string? content) + { + if (mediaType == null || !OciNames.ImageManifestTypes.Contains(mediaType, StringComparer.Ordinal) || content == null) return false; + + try + { + using var document = JsonDocument.Parse(content); + if (document.RootElement.ValueKind != JsonValueKind.Object + || !document.RootElement.TryGetProperty("config", out var config) + || config.ValueKind != JsonValueKind.Object + || !config.TryGetProperty("mediaType", out var configType) + || configType.ValueKind != JsonValueKind.String) + { + return false; + } + + var type = configType.GetString(); + return string.Equals(type, "application/vnd.oci.image.config.v1+json", StringComparison.Ordinal) + || string.Equals(type, "application/vnd.docker.container.image.v1+json", StringComparison.Ordinal); + } + catch (JsonException) + { + return false; + } + } +} diff --git a/src/BaGet.Core/Formats/Docker/DockerRetentionHooks.cs b/src/BaGet.Core/Formats/Docker/DockerRetentionHooks.cs new file mode 100644 index 000000000..c0228aad3 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/DockerRetentionHooks.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Docker's : a version is a tag of an image (name = the image, version = the tag), deleting +/// it removes the tag only; the manifest it pointed at stays until it is untagged long enough for the untagged rule +/// (: manifests no tag, no index and no referrer relationship needs, version = digest), and the +/// blobs go with the garbage collection (, which a policy can run after its rules). A tag counts as +/// downloaded when it or its digest was pulled. +/// +public sealed class DockerRetentionHooks : IFormatRetentionHooks +{ + private readonly IContext _context; + private readonly OciRegistryService _registry; + + public DockerRetentionHooks(IContext context, OciRegistryService registry) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Docker; + + /// + public async Task> ListVersionsAsync(CancellationToken cancellationToken) + { + var usage = await ArtifactUsageMap.LoadAsync(_context, cancellationToken).ConfigureAwait(false); + var rows = await (from t in _context.OciTags!.AsNoTracking() + join m in _context.OciManifests!.AsNoTracking() on t.ManifestKey equals m.Key + join i in _context.OciRepositories!.AsNoTracking() on m.ImageKey equals i.Key + select new { Image = i.Name, Tag = t.Name, t.Updated, m.Digest }).ToListAsync(cancellationToken).ConfigureAwait(false); + + // A tag has no prerelease notion; its size (the layers it uses) is worked out by GetSizeAsync when a cache limit needs it. + return rows + .Select(r => new FormatVersion(r.Image!, r.Tag!, DateTime.SpecifyKind(r.Updated, DateTimeKind.Utc), usage.Latest(r.Image!, r.Tag!, r.Digest!), null, false)) + .ToList(); + } + + /// + public async Task> ListUnreferencedAsync(CancellationToken cancellationToken) + { + var usage = await ArtifactUsageMap.LoadAsync(_context, cancellationToken).ConfigureAwait(false); + var manifests = await (from m in _context.OciManifests!.AsNoTracking() + join i in _context.OciRepositories!.AsNoTracking() on m.ImageKey equals i.Key + select new { m.Key, m.ImageKey, Image = i.Name, m.Digest, m.MediaType, m.SubjectDigest, m.Created, m.Size }).ToListAsync(cancellationToken).ConfigureAwait(false); + var tagged = (await (from t in _context.OciTags!.AsNoTracking() + join m in _context.OciManifests!.AsNoTracking() on t.ManifestKey equals m.Key + join i in _context.OciRepositories!.AsNoTracking() on m.ImageKey equals i.Key + select t.ManifestKey).Distinct().ToListAsync(cancellationToken).ConfigureAwait(false)).ToHashSet(); + + // What an index names as a child is in use as long as the index is; an index is read to find them. + var indexKeys = manifests.Where(m => OciNames.IsIndex(m.MediaType)).Select(m => m.Key).ToList(); + var indexes = indexKeys.Count == 0 + ? new List<(int ImageKey, string Content, string? MediaType)>() + : (await _context.OciManifests!.AsNoTracking().Where(m => indexKeys.Contains(m.Key)).Select(m => new { m.ImageKey, m.Content, m.MediaType }).ToListAsync(cancellationToken).ConfigureAwait(false)) + .Select(m => (ImageKey: m.ImageKey, Content: m.Content!, MediaType: m.MediaType)).ToList(); + var children = new HashSet<(int, string)>(); + foreach (var index in indexes) + { + try + { + foreach (var child in OciManifestParser.Parse(index.MediaType, Encoding.UTF8.GetBytes(index.Content)).Children) children.Add((index.ImageKey, child.Descriptor.Digest)); + } + catch (OciException) + { + // A document that no longer parses names nothing. + } + } + + var digests = manifests.Select(m => (m.ImageKey, m.Digest!)).ToHashSet(); + + return manifests + .Where(m => !tagged.Contains(m.Key) + && !children.Contains((m.ImageKey, m.Digest!)) + && !(m.SubjectDigest != null && digests.Contains((m.ImageKey, m.SubjectDigest)))) + .Select(m => new FormatVersion(m.Image!, m.Digest!, DateTime.SpecifyKind(m.Created, DateTimeKind.Utc), usage.Get(m.Image!, m.Digest!), m.Size, false)) + .ToList(); + } + + /// + public async Task DeleteVersionAsync(string name, string version, CancellationToken cancellationToken) + { + if (OciNames.LooksLikeDigest(version)) await _registry.DeleteManifestAsync(name, version, cancellationToken).ConfigureAwait(false); + else await _registry.DeleteTagAsync(name, version, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task GetSizeAsync(string name, string version, CancellationToken cancellationToken) + { + var manifest = await (from t in _context.OciTags!.AsNoTracking() + join m in _context.OciManifests!.AsNoTracking() on t.ManifestKey equals m.Key + join i in _context.OciRepositories!.AsNoTracking() on m.ImageKey equals i.Key + where i.Name == name && t.Name == version + select new { m.ImageKey, m.Digest, m.MediaType, m.Content, m.Size }).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (manifest == null) return null; + + // The manifest, plus (for an index) the manifests it lists, plus each distinct blob they use once. + long total = manifest.Size; + var blobs = new HashSet(StringComparer.Ordinal); + var documents = new List<(string? MediaType, string Content)> { (manifest.MediaType, manifest.Content!) }; + for (var i = 0; i < documents.Count && i < 200; i++) + { + OciParsedManifest parsed; + try + { + parsed = OciManifestParser.Parse(documents[i].MediaType, Encoding.UTF8.GetBytes(documents[i].Content)); + } + catch (OciException) + { + continue; + } + + if (parsed.IsIndex) + { + var digests = parsed.Children.Select(c => c.Descriptor.Digest).ToList(); + var rows = await _context.OciManifests!.AsNoTracking().Where(m => m.ImageKey == manifest.ImageKey && digests.Contains(m.Digest!)) + .Select(m => new { m.MediaType, m.Content, m.Size }).ToListAsync(cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + total += row.Size; + documents.Add((row.MediaType, row.Content!)); + } + } + else + { + foreach (var digest in parsed.BlobDigests) blobs.Add(digest); + } + } + + if (blobs.Count > 0) + { + var list = blobs.ToList(); + total += await _context.OciBlobs!.AsNoTracking().Where(b => list.Contains(b.Digest!)).SumAsync(b => b.Size, cancellationToken).ConfigureAwait(false); + } + + return total; + } + + /// + public (string Name, string Version)? Canonical(string name, string? version) + { + var image = name?.Trim().ToLowerInvariant(); + if (!OciNames.IsValidImage(image)) return null; + if (string.IsNullOrWhiteSpace(version)) return (image!, string.Empty); + + var v = version.Trim(); + + return OciNames.IsValidDigest(v) || OciNames.IsValidTag(v) ? (image!, v) : null; + } +} diff --git a/src/BaGet.Core/Formats/Docker/IOciRegistry.cs b/src/BaGet.Core/Formats/Docker/IOciRegistry.cs new file mode 100644 index 000000000..4bd90dd95 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/IOciRegistry.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// The error codes of the OCI Distribution Spec (and the HTTP status each one is answered with). +public enum OciErrorCode +{ + /// The blob is unknown to the image (404). + BlobUnknown, + + /// The blob upload is invalid (400). + BlobUploadInvalid, + + /// The upload session is unknown (404). + BlobUploadUnknown, + + /// The provided digest did not match the uploaded content, or is not a digest this registry stores (400). + DigestInvalid, + + /// A manifest references a blob (or manifest) the image does not hold (400). + ManifestBlobUnknown, + + /// The manifest is not valid (400). + ManifestInvalid, + + /// The manifest is unknown to the image (404). + ManifestUnknown, + + /// The image name is not valid (400). + NameInvalid, + + /// The image (or the repository) is unknown (404). + NameUnknown, + + /// The content length does not match what was announced (400). + SizeInvalid, + + /// The tag is not valid (400). + TagInvalid, + + /// The operation is not supported, here or for this object (405). + Unsupported, + + /// The chunk does not start where the upload ends (416). + RangeInvalid, + + /// The pagination parameter is not valid (400). + PaginationNumberInvalid, + + /// The manifest is larger than (413). + ManifestTooLarge, + + /// The repository does not take this change (a remote repository caches an upstream, a virtual one has no deploy repository) (403). + Denied, + + /// The upstream registry of a remote repository could not be reached or sent something unusable, and nothing stored can answer (502). + UpstreamUnavailable, +} + +/// +/// A protocol-level refusal of the registry: what the client did wrong, with the code the Distribution Spec names for it. The +/// web layer answers it as the JSON error body; the pages show the message. Never thrown for the maintenance gate (that is +/// , answered 503 by the middleware). +/// +public sealed class OciException : Exception +{ + /// The code. + /// A sentence for the person or client. + /// A short machine-readable detail (a digest, a length), or null. + public OciException(OciErrorCode code, string message, string? detail = null) + : base(message) + { + Code = code; + Detail = detail; + } + + /// The code. + public OciErrorCode Code { get; } + + /// What the error is about (a digest, the length an upload holds), or null. + public string? Detail { get; } + + /// For : the number of bytes the upload holds. + public long? UploadLength { get; init; } +} + +/// A blob being served (whole or a range). Dispose it when the response is written. +public sealed class OciBlobContent : IDisposable +{ + internal OciBlobContent(Stream content, string digest, long totalSize, long offset, long length) + { + Content = content; + Digest = digest; + TotalSize = totalSize; + Offset = offset; + Length = length; + } + + /// The bytes of the range. + public Stream Content { get; } + + /// The blob's digest. + public string Digest { get; } + + /// The blob's size. + public long TotalSize { get; } + + /// Where the range starts. + public long Offset { get; } + + /// The number of bytes in the range. + public long Length { get; } + + /// + public void Dispose() + { + Content.Dispose(); + Owner?.Dispose(); + } + + /// + /// Something to release after (the scope of the virtual repository's member that serves the blob, whose + /// services a caching stream still uses while it is read). + /// + internal IDisposable? Owner { get; set; } +} + +/// A blob as a HEAD reports it. +/// The digest. +/// The size in bytes. +public sealed record OciBlobInfo(string Digest, long Size); + +/// A stored manifest or index. +/// Its digest. +/// Its media type. +/// The bytes exactly as pushed. +/// The digest it refers to (OCI 1.1), or null. +/// Its artifact type, or null. +/// When it was first pushed to the image (UTC). +public sealed record OciManifestContent(string Digest, string MediaType, byte[] Content, string? SubjectDigest, string? ArtifactType, DateTime Created); + +/// The result of storing a manifest. +/// The manifest's digest. +/// The digest of its subject, or null. +/// Whether the manifest was new to the image (a re-push of the same bytes is not). +/// The digest the pushed tag pointed to before this push (null for a push by digest or a new tag); lets a caller that refuses the push put the tag back. +public sealed record OciManifestPut(string Digest, string? SubjectDigest, bool Created, string? PreviousDigest = null); + +/// An open upload session. +/// The reference to put in the upload URL. +/// The bytes received so far. +public sealed record OciUploadState(string Reference, long Length); + +/// The result of finishing a blob upload. +/// The blob's digest. +/// The blob's size. +public sealed record OciBlobStored(string Digest, long Size); + +/// A page of tags (tags/list). +/// The image. +/// The tags, in ordinal order. +/// Whether more tags follow the last one. +public sealed record OciTagList(string Image, IReadOnlyList Tags, bool HasMore); + +/// A descriptor in a referrers index. +/// The referrer's media type. +/// Its digest. +/// Its size. +/// Its artifact type, or null. +/// Its annotations, or null. +public sealed record OciDescriptor(string MediaType, string Digest, long Size, string? ArtifactType, IReadOnlyDictionary? Annotations); + +/// An image as the browse page lists it. +/// The image name. +/// Number of tags. +/// Number of manifests (including indexes). +/// Bytes of the distinct blobs the image holds. +/// The last manifest or tag change (UTC). +public sealed record OciImageSummary(string Name, int Tags, int Manifests, long Size, DateTime Modified); + +/// A page of . +/// All images that matched and may be read. +/// The page. +public sealed record OciImagePage(int Total, IReadOnlyList Images); + +/// A layer, config or other blob a manifest lists. +/// The digest. +/// The size announced by the manifest. +/// The media type. +public sealed record OciLayerInfo(string Digest, long Size, string MediaType); + +/// A platform entry of an index. +/// The child manifest. +/// The child's media type. +/// The child's size. +/// The operating system, or null. +/// The architecture, or null. +/// The variant (v7), or null. +/// Whether the child manifest is in this image. +public sealed record OciPlatformInfo(string Digest, string MediaType, long Size, string? Os, string? Architecture, string? Variant, bool Present) +{ + /// The platform as one string: linux/arm64/v8 (or unknown for an entry with none). + public string Platform => Os == null && Architecture == null ? "unknown" : string.Join("/", new[] { Os, Architecture, Variant }.Where(v => !string.IsNullOrEmpty(v)).Select(v => v!)); +} + +/// A manifest as the image page lists it. +/// Its digest. +/// Its media type. +/// Bytes of the manifest document. +/// Whether it is an index of platform manifests. +/// When it was first pushed to the image (UTC). +/// The tags that point at it. +/// Its artifact type, or null. +/// The digest it refers to, or null. +/// For a single-image manifest, its platform when the config says so (linux/amd64); otherwise null. +/// Number of layers (0 for an index). +/// Bytes of the config and layers (the children are not summed for an index). +public sealed record OciManifestSummary( + string Digest, + string MediaType, + long Size, + bool IsIndex, + DateTime Created, + IReadOnlyList Tags, + string? ArtifactType, + string? SubjectDigest, + string? Platform, + int LayerCount, + long ContentSize); + +/// A tag of an image. +/// The tag. +/// The manifest it points at. +/// When it was created or moved (UTC). +public sealed record OciTagInfo(string Name, string Digest, DateTime Updated); + +/// An image with its tags and manifests (the image page). +/// The image name. +/// When the first upload arrived (UTC). +/// The last change (UTC). +/// The tags, by name. +/// The manifests, newest first. +/// Bytes of the distinct blobs the image holds. +/// Blobs held by the image that no manifest uses. +public sealed record OciImageInfo( + string Name, + DateTime Created, + DateTime Modified, + IReadOnlyList Tags, + IReadOnlyList Manifests, + long Size, + int UnreferencedBlobs); + +/// One manifest in full (the manifest page). +/// The summary. +/// The manifest document, pretty-printed for display (the stored bytes are unchanged). +/// The config blob, or null for an index. +/// The layers in order (empty for an index). +/// The entries of an index (empty for a single-image manifest). +/// The manifest's annotations. +public sealed record OciManifestDetail( + OciManifestSummary Summary, + string Json, + OciLayerInfo? Config, + IReadOnlyList Layers, + IReadOnlyList Platforms, + IReadOnlyDictionary Annotations); + +/// What a prune removed. +/// Layers removed from the image. +/// Their size. +public sealed record OciPruneResult(int Blobs, long Bytes); + +/// +/// The operations of a Docker / OCI repository, in : what the Distribution Spec routes and +/// the pages share. No method authorizes: the caller (the controller through , a page through its +/// gate) has already decided that the operation is allowed, because a registry token carries its own grants and there is no +/// principal here to ask. Protocol refusals are ; a closed maintenance gate is +/// . +/// +public interface IOciRegistry +{ + // ---- reads (pull) ------------------------------------------------------------------------------------------------ + + /// Whether the image exists. + Task ImageExistsAsync(string image, CancellationToken cancellationToken); + + /// A blob the image holds, for a HEAD; null when the image does not hold it. + Task GetBlobInfoAsync(string image, string digest, CancellationToken cancellationToken); + + /// A blob the image holds, from for bytes (to the end when null); null when absent. + Task OpenBlobAsync(string image, string digest, long offset, long? length, CancellationToken cancellationToken); + + /// A manifest by tag or digest; null when the image has none. + Task GetManifestAsync(string image, string reference, CancellationToken cancellationToken); + + /// The tags of an image after , at most ; null when the image is unknown. + Task ListTagsAsync(string image, int? count, string? last, CancellationToken cancellationToken); + + /// The manifests of the image whose subject is , optionally of one artifact type; null when the image is unknown. + Task?> GetReferrersAsync(string image, string digest, string? artifactType, CancellationToken cancellationToken); + + /// The state of an upload session (what a client resumes from); null when there is none. + Task GetUploadAsync(string image, string reference, CancellationToken cancellationToken); + + // ---- uploads and manifests (push) -------------------------------------------------------------------------------- + + /// Starts an upload session for the image (creating the image). + Task StartUploadAsync(string image, CancellationToken cancellationToken); + + /// + /// Appends a chunk. is where the client says the chunk starts (the Content-Range start), + /// or null to append at the end. + /// + /// , or with . + Task AppendAsync(string image, string reference, long? offset, Stream chunk, CancellationToken cancellationToken); + + /// Appends an optional last chunk, verifies the digest, stores the blob and closes the session. + Task CompleteUploadAsync(string image, string reference, string digest, long? offset, Stream? lastChunk, CancellationToken cancellationToken); + + /// Discards an upload session; false when there was none. + Task CancelUploadAsync(string image, string reference, CancellationToken cancellationToken); + + /// Stores a whole blob sent in one request (POST …/uploads/?digest=). + Task PutBlobAsync(string image, string digest, Stream content, CancellationToken cancellationToken); + + /// + /// Makes a blob of available in without copying it (cross-repository + /// mount); false when (in this repository) does not hold it. + /// + Task MountBlobAsync(string image, string digest, string fromImage, CancellationToken cancellationToken); + + /// + /// Stores a manifest or index, under a tag or by digest, after checking that everything it references is in the image. + /// + Task PutManifestAsync(string image, string reference, string? mediaType, byte[] content, CancellationToken cancellationToken); + + // ---- deletes ----------------------------------------------------------------------------------------------------- + + /// Deletes a manifest by digest, with its tags; false when absent. + Task DeleteManifestAsync(string image, string digest, CancellationToken cancellationToken); + + /// Deletes a tag (not its manifest); false when absent. + Task DeleteTagAsync(string image, string tag, CancellationToken cancellationToken); + + /// Removes a blob from the image; false when absent. Refused () while a manifest of the image uses it. + Task DeleteBlobAsync(string image, string digest, CancellationToken cancellationToken); + + /// + /// Where a manifest would come from, without storing or serving it: when this repository + /// holds the tag or digest, otherwise (a remote repository) whether its upstream has it. The resolution preview of a virtual + /// repository asks each member. + /// + Task ProbeAsync(string image, string reference, CancellationToken cancellationToken); + + /// Deletes the image with everything in it; false when absent. + Task DeleteImageAsync(string image, CancellationToken cancellationToken); + + /// Removes the blobs of the image that no manifest uses and that are older than . + Task PruneAsync(string image, CancellationToken cancellationToken); + + // ---- the pages --------------------------------------------------------------------------------------------------- + + /// The images whose name contains (all when empty) that admits. + Task ListImagesAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken); + + /// An image with its tags and manifests; null when unknown. + Task GetImageAsync(string image, CancellationToken cancellationToken); + + /// A manifest in full; null when unknown. + Task GetManifestDetailAsync(string image, string digest, CancellationToken cancellationToken); +} diff --git a/src/BaGet.Core/Formats/Docker/OciAccess.cs b/src/BaGet.Core/Formats/Docker/OciAccess.cs new file mode 100644 index 000000000..3a0519a9c --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciAccess.cs @@ -0,0 +1,309 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// What a caller does to an image, in the words of a registry token (pull,push) and of the access model. +[Flags] +public enum OciActions +{ + /// Nothing. + None = 0, + + /// Read manifests, tags, blobs and referrers: . + Pull = 1, + + /// Upload blobs and put manifests: . + Push = 2, + + /// Delete manifests, tags and blobs: . + Delete = 4, + + /// Every action. + All = Pull | Push | Delete, +} + +/// An image, with the BaGet repository it lives in, as a token scope names it: repository:{repo}/{image}:pull,push. +/// The BaGet repository (lower case). +/// The image name inside it. +/// The actions asked for or granted. +public sealed record OciGrant(string Repository, string Image, OciActions Actions); + +/// Reads and writes the scope strings of the Docker token protocol. +public static class OciScopes +{ + /// + /// Parses repository:{repo}/{image}:pull,push. Returns null for another resource type (registry:catalog:*) or a + /// malformed scope; an unknown action is ignored (a client may ask for more than a registry knows). + /// + public static OciGrant? Parse(string? scope) + { + if (string.IsNullOrWhiteSpace(scope)) return null; + + var parts = scope.Split(':'); + if (parts.Length != 3 || parts[0] != "repository") return null; + + var slash = parts[1].IndexOf('/'); + if (slash <= 0 || slash == parts[1].Length - 1) return null; + + var actions = OciActions.None; + foreach (var action in parts[2].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + actions |= action switch + { + "pull" => OciActions.Pull, + "push" => OciActions.Push, + "delete" => OciActions.Delete, + "*" => OciActions.All, + _ => OciActions.None, + }; + } + + return new OciGrant(parts[1].Substring(0, slash).ToLowerInvariant(), parts[1].Substring(slash + 1), actions); + } + + /// The comma-separated action words (pull,push). + public static string Words(OciActions actions) + { + var words = new List(); + if (actions.HasFlag(OciActions.Pull)) words.Add("pull"); + if (actions.HasFlag(OciActions.Push)) words.Add("push"); + if (actions.HasFlag(OciActions.Delete)) words.Add("delete"); + + return string.Join(",", words); + } + + /// The scope string of . + public static string Format(OciGrant grant) => $"repository:{grant.Repository}/{grant.Image}:{Words(grant.Actions)}"; +} + +/// Decides what a caller may do to an image: the access model, the key's own limits, one rule for the routes, the token endpoint and the pages. +public interface IOciAccess +{ + /// + /// Whether (null: anonymous) may do to of + /// . A pull needs Read, a push Deploy, a delete Delete on the image (the targets' include and + /// exclude patterns see the image name); a key must also carry the scope (package:push or + /// package:pushversion to push, package:unlist to delete) and its package glob must match the image. The + /// superuser may do anything; Deploy is never granted on a repository that is not local (the evaluator). + /// + Task IsAllowedAsync(BaGetPrincipal? principal, RepositoryInfo repository, string image, OciActions action, CancellationToken cancellationToken); + + /// Of the actions, those holds. + Task GrantedAsync(BaGetPrincipal? principal, RepositoryInfo repository, string image, OciActions requested, CancellationToken cancellationToken); +} + +/// over . +public sealed class OciAccess : IOciAccess +{ + private readonly IAccessEvaluator _evaluator; + + /// The access model. + public OciAccess(IAccessEvaluator evaluator) + { + _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator)); + } + + /// + public async Task IsAllowedAsync(BaGetPrincipal? principal, RepositoryInfo repository, string image, OciActions action, CancellationToken cancellationToken) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + if (action == OciActions.None || (action & (action - 1)) != 0) throw new ArgumentException("Ask for one action at a time.", nameof(action)); + + // A format-less deny: only Docker repositories speak this protocol. + if (repository.Format != RepositoryFormat.Docker) return false; + + if (principal != null && !principal.IsSuperuser) + { + if (!principal.MatchesPackage(image)) return false; + + // The key's own limits: a key made for one thing stays that thing. + switch (action) + { + case OciActions.Push when !(principal.HasScope(ApiKeyScopes.Push) || principal.HasScope(ApiKeyScopes.PushVersion)): + case OciActions.Delete when !principal.HasScope(ApiKeyScopes.Unlist): + return false; + } + } + else if (principal == null && action != OciActions.Pull) + { + // Anonymous callers are not given Deploy or Delete here even if a target names Everyone: a write needs credentials. + return false; + } + + var required = action switch + { + OciActions.Pull => AccessAction.Read, + OciActions.Push => AccessAction.Deploy, + _ => AccessAction.Delete, + }; + + return principal is { IsSuperuser: true } || await _evaluator.IsAllowedAsync(principal, repository, image, required, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task GrantedAsync(BaGetPrincipal? principal, RepositoryInfo repository, string image, OciActions requested, CancellationToken cancellationToken) + { + var granted = OciActions.None; + foreach (var action in new[] { OciActions.Pull, OciActions.Push, OciActions.Delete }) + { + if (requested.HasFlag(action) && await IsAllowedAsync(principal, repository, image, action, cancellationToken).ConfigureAwait(false)) granted |= action; + } + + return granted; + } +} + +/// A token as /v2/token returns it. +/// The opaque token. +/// Seconds it stays valid. +/// When it was issued (UTC). +public sealed record OciIssuedToken(string Token, int ExpiresIn, DateTime IssuedAt); + +/// What a valid token says. +/// Who it was issued to (a user name), or null for an anonymous token. +/// What it allows. +/// When it stops being valid (UTC). +public sealed record OciTokenClaims(string? Subject, IReadOnlyList Grants, DateTime Expires) +{ + /// Whether the token allows on the image. + public bool Allows(string repository, string image, OciActions action) + => Grants.Any(g => string.Equals(g.Repository, repository, StringComparison.Ordinal) && string.Equals(g.Image, image, StringComparison.Ordinal) && g.Actions.HasFlag(action)); +} + +/// +/// Issues and checks the short-lived tokens of the docker login flow. A token is signed (and encrypted) by data +/// protection, scope-limited (the images and actions granted when it was issued) and carries no credential: not the API key +/// that earned it, only the user's name for the log. +/// +public interface IOciTokenService +{ + /// Whether tokens can be issued (a data protection provider is registered). + bool IsAvailable { get; } + + /// Issues a token for that is valid for . + OciIssuedToken Issue(string? subject, IReadOnlyList grants); + + /// The claims of a token this registry issued and that has not expired, else null. + OciTokenClaims? Validate(string? token); +} + +/// over ASP.NET Core data protection. +public sealed class OciTokenService : IOciTokenService +{ + private const string Purpose = "BaGet.Oci.Token.v1"; + + private readonly IDataProtector? _protector; + private readonly SystemTime _time; + private readonly IOptionsSnapshot? _options; + + /// The clock. + /// Data protection; without it no token can be issued. + /// The Oci:* options. + public OciTokenService(SystemTime time, IDataProtectionProvider? protection = null, IOptionsSnapshot? options = null) + { + _time = time ?? throw new ArgumentNullException(nameof(time)); + _protector = protection?.CreateProtector(Purpose); + _options = options; + } + + private OciOptions Options => _options?.Value ?? new OciOptions(); + + /// + public bool IsAvailable => _protector != null; + + /// + public OciIssuedToken Issue(string? subject, IReadOnlyList grants) + { + if (_protector == null) throw new InvalidOperationException("Registry tokens need ASP.NET Core data protection, which this host does not provide."); + + var lifetime = Options.TokenLifetime < TimeSpan.FromSeconds(10) ? TimeSpan.FromSeconds(10) : Options.TokenLifetime; + var issued = _time.UtcNow; + var payload = new Payload + { + Audience = Options.Service, + Subject = subject, + IssuedAt = new DateTimeOffset(DateTime.SpecifyKind(issued, DateTimeKind.Utc)).ToUnixTimeSeconds(), + Expires = new DateTimeOffset(DateTime.SpecifyKind(issued + lifetime, DateTimeKind.Utc)).ToUnixTimeSeconds(), + Grants = grants.Select(g => new GrantPayload { Repository = g.Repository, Image = g.Image, Actions = (int)g.Actions }).ToList(), + }; + + var bytes = _protector.Protect(JsonSerializer.SerializeToUtf8Bytes(payload)); + + return new OciIssuedToken(Base64Url(bytes), (int)lifetime.TotalSeconds, DateTime.SpecifyKind(issued, DateTimeKind.Utc)); + } + + /// + public OciTokenClaims? Validate(string? token) + { + if (_protector == null || string.IsNullOrEmpty(token) || token.Length > 16 * 1024) return null; + + try + { + var payload = JsonSerializer.Deserialize(_protector.Unprotect(FromBase64Url(token))); + if (payload == null || payload.Version != 1 || !string.Equals(payload.Audience, Options.Service, StringComparison.Ordinal)) return null; + + var expires = DateTimeOffset.FromUnixTimeSeconds(payload.Expires).UtcDateTime; + if (expires <= _time.UtcNow) return null; + + return new OciTokenClaims( + payload.Subject, + (payload.Grants ?? new List()).Select(g => new OciGrant(g.Repository ?? string.Empty, g.Image ?? string.Empty, (OciActions)g.Actions)).ToList(), + expires); + } + catch (Exception e) when (e is System.Security.Cryptography.CryptographicException or FormatException or JsonException or ArgumentException) + { + // Not ours, tampered with, or from another key ring: the same as no token. + return null; + } + } + + private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static byte[] FromBase64Url(string text) + { + var padded = text.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + (4 - padded.Length % 4) % 4, '='); + + return Convert.FromBase64String(padded); + } + + private sealed class Payload + { + [System.Text.Json.Serialization.JsonPropertyName("v")] + public int Version { get; set; } = 1; + + [System.Text.Json.Serialization.JsonPropertyName("aud")] + public string? Audience { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("sub")] + public string? Subject { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("iat")] + public long IssuedAt { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("exp")] + public long Expires { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("g")] + public List? Grants { get; set; } + } + + private sealed class GrantPayload + { + [System.Text.Json.Serialization.JsonPropertyName("r")] + public string? Repository { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("i")] + public string? Image { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("a")] + public int Actions { get; set; } + } +} diff --git a/src/BaGet.Core/Formats/Docker/OciEntities.cs b/src/BaGet.Core/Formats/Docker/OciEntities.cs new file mode 100644 index 000000000..0b15307b1 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciEntities.cs @@ -0,0 +1,144 @@ +using System; + +namespace BaGet.Core; + +/// +/// An image repository (team/app) inside a BaGet repository of the Docker format: what docker push host/libs/team/app:1 +/// creates (libs is the BaGet repository, team/app the image). Created by the first upload or manifest; it is the +/// unit the access patterns (team/*) and the page of an image speak about. +/// +public class OciRepository : IRepositoryScoped +{ + public int Key { get; set; } + + /// The owning BaGet repository; see . + public int RepositoryKey { get; set; } + + /// The image name, lower case (). Unique per BaGet repository. + public string? Name { get; set; } + + /// When the first upload or manifest arrived. + public DateTime Created { get; set; } + + /// The last manifest or tag change. + public DateTime Modified { get; set; } +} + +/// +/// A manifest or index of an image, addressed by its digest. The bytes are kept exactly as pushed (the digest is over them) in +/// ; a manifest is small (), so it lives in the row and needs no file. +/// +public class OciManifest +{ + public int Key { get; set; } + + /// The . Required; deleting the image deletes its manifests. + public int ImageKey { get; set; } + + /// sha256:… of . Unique per image. + public string? Digest { get; set; } + + /// The manifest's media type ( or ). + public string? MediaType { get; set; } + + /// The artifact type (OCI 1.1): the manifest's artifactType, else its config's media type; null for an index with none. + public string? ArtifactType { get; set; } + + /// The digest of the manifest this one refers to (OCI 1.1 subject): what the referrers API lists it under. + public string? SubjectDigest { get; set; } + + /// Bytes of . + public long Size { get; set; } + + /// The JSON exactly as pushed (valid UTF-8, round-trips byte for byte). + public string? Content { get; set; } + + /// When it was first pushed to this image. + public DateTime Created { get; set; } +} + +/// A tag of an image: a mutable name for a manifest (case-sensitive). +public class OciTag +{ + public int Key { get; set; } + + /// The image; part of the unique (ImageKey, Name). + public int ImageKey { get; set; } + + /// The tag (). + public string? Name { get; set; } + + /// The it points at. Required; deleting the manifest deletes its tags. + public int ManifestKey { get; set; } + + /// When the tag was created or last moved. + public DateTime Updated { get; set; } +} + +/// +/// A blob (a layer, a config, any artifact file) stored once per BaGet repository, by digest: the file is at +/// . counts the images that hold it (); the file +/// goes when the count reaches zero. +/// +public class OciBlob : IRepositoryScoped +{ + public int Key { get; set; } + + /// The owning BaGet repository; see . + public int RepositoryKey { get; set; } + + /// sha256:…. Unique per BaGet repository. + public string? Digest { get; set; } + + /// Bytes stored. + public long Size { get; set; } + + /// How many images hold the blob (rows of ). + public int RefCount { get; set; } + + /// When the blob was first stored. + public DateTime Created { get; set; } +} + +/// +/// The fact that an image holds a blob: it was uploaded to the image, mounted into it, or is part of a manifest of it. A blob is +/// served under an image only through its link, so an image whose access is restricted cannot be used to read another image's +/// layers by guessing a digest. +/// +public class OciBlobLink +{ + public int Key { get; set; } + + /// The image. Required; deleting the image deletes its links. + public int ImageKey { get; set; } + + /// The . Required; unique with . + public int BlobKey { get; set; } + + /// How many manifests of the image use the blob as config or layer; a blob with 0 is an unreferenced upload. + public int Manifests { get; set; } + + /// When the image obtained the blob. + public DateTime Created { get; set; } +} + +/// An upload session: the storage upload behind POST /blobs/uploads/ until it is committed or abandoned. +public class OciUpload +{ + public int Key { get; set; } + + /// The image the upload is for. Required; deleting the image deletes its sessions. + public int ImageKey { get; set; } + + /// The opaque reference handed to the client (the last segment of the upload URL). Unique. + public string? Reference { get; set; } + + /// The upload id. + public string? StorageUploadId { get; set; } + + /// When the session started. + public DateTime Created { get; set; } + + /// The last chunk (or the start). + public DateTime Updated { get; set; } +} diff --git a/src/BaGet.Core/Formats/Docker/OciGarbageCollector.cs b/src/BaGet.Core/Formats/Docker/OciGarbageCollector.cs new file mode 100644 index 000000000..166347386 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciGarbageCollector.cs @@ -0,0 +1,453 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// What a garbage collection found (or, outside a dry run, removed). +public enum OciGcItemKind +{ + /// An upload session nobody touched for : the session and what it received. + ExpiredUpload, + + /// A layer an image holds that none of the image's manifests uses and that is older than . + UnreferencedLayer, + + /// A blob row that no image holds any more (its file goes with it). + OrphanBlob, + + /// A file under the blob folder that no blob row names (a push that died between storing the file and recording it). + OrphanFile, +} + +/// One thing a garbage collection removes. +/// What it is. +/// A digest or a session reference. +/// Bytes it frees (0 for a session). +/// The image it belonged to, if any. +public sealed record OciGcItem(OciGcItemKind Kind, string Subject, long Bytes, string? Image); + +/// The outcome of one garbage collection of a repository. +/// Whether nothing was changed (the numbers are what a run would remove). +/// The repository. +/// Upload sessions discarded. +/// Image-to-layer links dropped (a layer two images hold counts twice). +/// Blobs (rows and files) removed: those no image holds after the links are dropped, orphan rows included. +/// Files under the blob folder with no row, removed. +/// Bytes freed by the blobs and orphan files, as far as they are known (an orphan file's size is not). +/// The first of the things removed (the list is capped). +/// Whether there are more than holds. +/// Something the run could not do (the store cannot list files), or null. +public sealed record OciGcReport( + bool DryRun, + string Repository, + int ExpiredUploads, + int UnreferencedLayers, + int Blobs, + int OrphanFiles, + long Bytes, + IReadOnlyList Items, + bool ItemsTruncated, + string? Note) +{ + /// One line for the Operations page and the audit log. + public string Summary + { + get + { + var text = $"{(DryRun ? "Dry run, nothing removed. Would remove" : "Removed")}: {ExpiredUploads} expired upload session(s), " + + $"{UnreferencedLayers} unreferenced layer link(s), {Blobs} blob(s) ({FormatBytes(Bytes)}), {OrphanFiles} orphan file(s)."; + if (Note != null) text += " " + Note; + + return text; + } + } + + private static string FormatBytes(long bytes) + { + string[] units = { "B", "KiB", "MiB", "GiB", "TiB" }; + double value = bytes; + var unit = 0; + while (value >= 1024 && unit < units.Length - 1) + { + value /= 1024; + unit++; + } + + return unit == 0 ? $"{bytes} B" : $"{value:0.#} {units[unit]}"; + } +} + +/// +/// Removes the blobs of a Docker repository (local or remote) that nothing uses, in the repository of the request. +/// +public interface IOciGarbageCollector +{ + /// + /// Finds what is unreferenced and, unless , removes it. + /// + /// The repository is not a Docker repository with blobs of its own (a virtual one has none). + /// Not a dry run and the server is read-only while a database copy runs. + Task RunAsync(bool dryRun, CancellationToken cancellationToken); +} + +/// +/// : mark and sweep over the repository's rows and files. +/// +/// +/// Marked, in this order: (1) upload sessions idle longer than ; (2) image-to-layer links +/// no manifest of the image uses ( is 0) and older than , except +/// those of an image with an upload session still open (a push in progress sends layers first and the manifest last, however long the +/// layers take); (3) blobs no image holds once those links are gone (reference count 0), and blob rows nobody ever linked, older than the +/// grace period; (4) files under the blob folder that no blob row names, when the store can list files and no blob is being committed +/// right now (a file is stored a moment before its row is written). +/// Swept (not a dry run): the links and blobs are first re-checked against the current rows in a serializable +/// transaction (a manifest or push that committed since the plan was made keeps its links and blobs; the report counts only what was +/// removed), then the sessions, links and blob rows are deleted, the sessions aborted in storage, then the files. A file that cannot be deleted is logged and counted; the next run finds it again as an orphan file. +/// This is what Oci.PruneGrace and Oci.UploadExpiry are for; running it for every repository on a schedule is the +/// retention engine's job (P6), the Operations page runs it by hand. +/// +public sealed class OciGarbageCollector : IOciGarbageCollector +{ + /// The most items a report lists. + public const int MaxItems = 500; + + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IRepositoryContext _repository; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + private readonly IOptionsSnapshot? _options; + private readonly ClusterRuntime? _cluster; + + public OciGarbageCollector( + IContext context, + IStorageService storage, + IRepositoryContext repository, + SystemTime time, + MaintenanceGate gate, + ILogger logger, + IOptionsSnapshot? options = null, + ClusterRuntime? cluster = null) + { + _cluster = cluster; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _options = options; + } + + private OciOptions Options => _options?.Value ?? new OciOptions(); + + private IStreamingStorageService Streaming => StreamingStorage.Require(_storage, "Docker repositories"); + + /// Test seam: runs after the blob rows were loaded and before the storage listing, with the repository name. + internal static Func? AfterRowsLoaded { get; set; } + + private static string BlobFolder => OciNames.StorageFolder + "/blobs"; + + /// + public async Task RunAsync(bool dryRun, CancellationToken cancellationToken) + { + var repository = _repository.Current; + if (repository.Format != RepositoryFormat.Docker || repository.Kind == RepositoryKind.Virtual || _context is NullContext) + { + throw new InvalidOperationException($"'{repository.Name}' is not a Docker repository with blobs of its own."); + } + + if (!dryRun) _gate.ThrowIfClosed(); + + var now = _time.UtcNow; + var uploadCutoff = now - Options.UploadExpiry; + var layerCutoff = now - Options.PruneGrace; + var items = new List(); + var truncated = false; + + void Add(OciGcItem item) + { + if (items.Count < MaxItems) items.Add(item); + else truncated = true; + } + + // (1) Sessions nobody touched for a day. The image join keeps this to the repository of the request. + var expired = await (from u in _context.OciUploads! + join i in _context.OciRepositories! on u.ImageKey equals i.Key + where u.Updated < uploadCutoff + select new { Session = u, Image = i.Name }).ToListAsync(cancellationToken).ConfigureAwait(false); + foreach (var e in expired) Add(new OciGcItem(OciGcItemKind.ExpiredUpload, e.Session.Reference!, 0, e.Image)); + + // Images with a push that is still going on: their loose layers wait for the manifest. + var pushing = (await (from u in _context.OciUploads!.AsNoTracking() + join i in _context.OciRepositories!.AsNoTracking() on u.ImageKey equals i.Key + where u.Updated >= uploadCutoff + select u.ImageKey).Distinct().ToListAsync(cancellationToken).ConfigureAwait(false)).ToHashSet(); + + // (2) Layers an image holds that none of its manifests uses. + var loose = (await (from l in _context.OciBlobLinks! + join b in _context.OciBlobs! on l.BlobKey equals b.Key + join i in _context.OciRepositories! on l.ImageKey equals i.Key + where l.Manifests == 0 && l.Created < layerCutoff + select new { Link = l, b.Digest, b.Size, Image = i.Name }).ToListAsync(cancellationToken).ConfigureAwait(false)) + .Where(l => !pushing.Contains(l.Link.ImageKey)) + .ToList(); + foreach (var l in loose) Add(new OciGcItem(OciGcItemKind.UnreferencedLayer, l.Digest!, l.Size, l.Image)); + + // (3) Blobs nothing holds once those links are gone. + var linkCounts = await (from l in _context.OciBlobLinks!.AsNoTracking() + join b in _context.OciBlobs!.AsNoTracking() on l.BlobKey equals b.Key + group l by l.BlobKey into g + select new { BlobKey = g.Key, Count = g.Count() }).ToDictionaryAsync(g => g.BlobKey, g => g.Count, cancellationToken).ConfigureAwait(false); + var droppedPerBlob = loose.GroupBy(l => l.Link.BlobKey).ToDictionary(g => g.Key, g => g.Count()); + + var blobs = await _context.OciBlobs!.ToListAsync(cancellationToken).ConfigureAwait(false); + var doomed = new List(); + foreach (var blob in blobs) + { + var held = linkCounts.GetValueOrDefault(blob.Key); + var dropped = droppedPerBlob.GetValueOrDefault(blob.Key); + if (held == 0 && blob.Created >= layerCutoff) continue; + if (held - dropped > 0) continue; + + doomed.Add(blob); + if (held == 0) Add(new OciGcItem(OciGcItemKind.OrphanBlob, blob.Digest!, blob.Size, null)); + } + + var doomedKeys = doomed.Select(b => b.Key).ToHashSet(); + var doomedDigests = doomed.Select(b => b.Digest!).ToHashSet(StringComparer.Ordinal); + var bytes = doomed.Sum(b => b.Size); + + // (4) Files no row names. + var survivors = blobs.Where(b => !doomedKeys.Contains(b.Key)).Select(b => b.Digest!).ToHashSet(StringComparer.Ordinal); + var orphanFiles = new List(); + string? note = null; + if (_cluster?.IsEnabled == true) + { + // The in-process commit fence below cannot see a blob another node is storing, so a listing could take a file whose row is + // about to be written. In a cluster the step is skipped rather than risk a layer. + note = "Files without a row were not looked for: other nodes of the cluster may be storing blobs, which this node cannot see."; + } + else if (_storage is not IListableStorageService listable) + { + note = "The storage provider cannot list files, so files without a row were not looked for."; + } + else + { + // A file is an orphan only if no row names it AFTER the listing: a blob committed since `blobs` was loaded has a row now. + // Commits of this process are fenced: none may start during the listing nor be running when it ends (a commit writes its + // row before it leaves the counter), so every file the listing shows has its row by the time the rows are read again. + // Other nodes sharing the store are not fenced (see docs/docker-registry.md). + var folder = RepositoryStorage.Scope(repository, BlobFolder); + if (AfterRowsLoaded != null) await AfterRowsLoaded(repository.Name).ConfigureAwait(false); + var startedBefore = OciBlobCommits.Started; + var listed = await listable.ListAsync(folder, cancellationToken).ConfigureAwait(false); + if (OciBlobCommits.InFlight > 0 || OciBlobCommits.Started != startedBefore) + { + note = "A blob was being stored while this ran, so files without a row were not looked for; run it again."; + } + else + { + var current = (await _context.OciBlobs!.AsNoTracking().Select(b => b.Digest!).ToListAsync(cancellationToken).ConfigureAwait(false)) + .ToHashSet(StringComparer.Ordinal); + foreach (var path in listed) + { + var digest = DigestOfPath(path, folder); + if (digest == null || survivors.Contains(digest) || doomedDigests.Contains(digest) || current.Contains(digest)) continue; + + orphanFiles.Add(path); + Add(new OciGcItem(OciGcItemKind.OrphanFile, digest, 0, null)); + } + } + } + + var removedLinks = loose.Count; + var removedBlobs = doomed.Count; + if (!dryRun) + { + var swept = await SweepAsync(repository, expired.Select(e => e.Session).ToList(), loose.Select(l => l.Link).ToList(), doomed, orphanFiles, cancellationToken).ConfigureAwait(false); + removedLinks = swept.Links; + removedBlobs = swept.Blobs; + bytes = swept.Bytes; + if (swept.Kept > 0) + { + var kept = $"{swept.Kept} layer link(s) or blob(s) were used by a push while this ran and were kept."; + note = note == null ? kept : note + " " + kept; + } + } + + var report = new OciGcReport(dryRun, repository.Name, expired.Count, removedLinks, removedBlobs, orphanFiles.Count, bytes, items, truncated, note); + _logger.LogInformation("Docker garbage collection of {Repository}{DryRun}: {Summary}", repository.Name, dryRun ? " (dry run)" : string.Empty, report.Summary); + + return report; + } + + // "/sha256/ab/" -> "sha256:"; anything else under the folder is not a blob this registry wrote. + private static string? DigestOfPath(string path, string folder) + { + var relative = path.Replace('\\', '/'); + var start = relative.IndexOf(folder + "/", StringComparison.Ordinal); + if (start < 0) return null; + + var parts = relative.Substring(start + folder.Length + 1).Split('/'); + if (parts.Length != 3 || parts[0] != OciNames.Sha256) return null; + + var hex = parts[2]; + + return StreamingStorage.IsSha256Hex(hex) && parts[1] == hex.Substring(0, 2) ? OciNames.DigestOf(hex) : null; + } + + // What the sweep really removed (the plan may shrink: see SweepAsync). + private readonly record struct Swept(int Links, int Blobs, long Bytes, int Kept); + + private async Task SweepAsync( + RepositoryInfo repository, + IReadOnlyList expired, + IReadOnlyList loose, + IReadOnlyList doomed, + IReadOnlyList orphanFiles, + CancellationToken cancellationToken) + { + // The plan was made from rows read earlier; a manifest committed since then has raised Manifests of a planned link (or a push + // has linked a planned blob to another image). Deleting by key would remove that now-used link and its blob. So the plan is + // checked again inside a serializable transaction, against the rows as they are now, and shrinks to what is still unused; + // a committer running at the same time waits for the transaction or fails and retries on its own. + IReadOnlyList removableLinks = loose; + IReadOnlyList removableBlobs = doomed; + var kept = 0; + + // An upload of a planned blob in this process either records its row before the transaction below (the blob is kept) or stores + // its file after the deletion: the digests stay locked from the check to the file deletion (OciBlobCommits). + using var blobLocks = await OciBlobCommits.LockAsync(doomed.Select(b => RepositoryStorage.Scope(repository, OciNames.BlobPath(b.Digest!))), cancellationToken).ConfigureAwait(false); + if (loose.Count > 0 || doomed.Count > 0) + { + await using var transaction = await _context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable, cancellationToken).ConfigureAwait(false); + + var looseKeys = loose.Select(l => l.Key).ToList(); + var stillLoose = (await _context.OciBlobLinks!.AsNoTracking().Where(l => looseKeys.Contains(l.Key) && l.Manifests == 0) + .Select(l => l.Key).ToListAsync(cancellationToken).ConfigureAwait(false)).ToHashSet(); + removableLinks = loose.Where(l => stillLoose.Contains(l.Key)).ToList(); + + var doomedKeys = doomed.Select(b => b.Key).ToList(); + var linkCounts = await _context.OciBlobLinks!.AsNoTracking().Where(l => doomedKeys.Contains(l.BlobKey)) + .GroupBy(l => l.BlobKey).Select(g => new { g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + var droppedPerBlob = removableLinks.GroupBy(l => l.BlobKey).ToDictionary(g => g.Key, g => g.Count()); + removableBlobs = doomed.Where(b => linkCounts.GetValueOrDefault(b.Key) - droppedPerBlob.GetValueOrDefault(b.Key) <= 0).ToList(); + kept = (loose.Count - removableLinks.Count) + (doomed.Count - removableBlobs.Count); + + if (expired.Count > 0) _context.OciUploads!.RemoveRange(expired); + if (removableLinks.Count > 0) _context.OciBlobLinks!.RemoveRange(removableLinks); + if (removableBlobs.Count > 0) _context.OciBlobs!.RemoveRange(removableBlobs); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + } + else if (expired.Count > 0) + { + _context.OciUploads!.RemoveRange(expired); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + foreach (var session in expired) + { + try + { + await Streaming.AbortAsync(session.StorageUploadId!, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "Could not abort the upload {UploadId}", session.StorageUploadId); + } + } + + foreach (var path in removableBlobs.Select(b => RepositoryStorage.Scope(repository, OciNames.BlobPath(b.Digest!))).Concat(orphanFiles)) + { + try + { + await _storage.DeleteAsync(path, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "Could not delete the blob file {Path}", path); + } + } + + return new Swept(removableLinks.Count, removableBlobs.Count, removableBlobs.Sum(b => b.Size), kept); + } +} + +/// The garbage collection as an (a dry run or the real thing), run from the Operations page. +public abstract class OciGarbageCollectionOperation : IAdminOperation +{ + private readonly bool _dryRun; + + /// Whether the operation only reports. + protected OciGarbageCollectionOperation(bool dryRun) + { + _dryRun = dryRun; + } + + /// The name of the operation that only reports. + public const string DryRunName = "oci-gc-dry-run"; + + /// The name of the operation that removes. + public const string RunName = "oci-gc"; + + /// + public string Name => _dryRun ? DryRunName : RunName; + + /// + public string Title => _dryRun ? "Docker garbage collection: dry run" : "Docker garbage collection"; + + /// + public string Description => _dryRun + ? "Reports the Docker blobs, layer links, upload sessions and orphan files that a collection would remove from the repository, and removes nothing." + : "Removes the Docker blobs nothing references (unused layers past the grace period, expired upload sessions, orphan blobs and files) from the repository."; + + /// + public bool IsAvailable(IServiceProvider services) + => services.GetRequiredService() is not NullContext && StreamingStorage.IsSupported(services.GetRequiredService()); + + /// + public bool AppliesTo(RepositoryInfo repository) + => repository.Format == RepositoryFormat.Docker && repository.Kind != RepositoryKind.Virtual; + + /// + /// The collection that removes asks for the password; the dry run deletes nothing. + public bool RequiresConfirmation => !_dryRun; + + /// + public async Task RunAsync(IServiceProvider services, CancellationToken cancellationToken) + { + var report = await services.GetRequiredService().RunAsync(_dryRun, cancellationToken).ConfigureAwait(false); + var listed = string.Join("; ", report.Items.Take(10).Select(i => $"{i.Kind} {i.Subject}")); + + return report.Summary + (listed.Length == 0 ? string.Empty : " First: " + listed + (report.Items.Count > 10 || report.ItemsTruncated ? "; ..." : string.Empty)); + } +} + +/// The garbage collection that only reports (). +public sealed class OciGarbageCollectionDryRunOperation : OciGarbageCollectionOperation +{ + public OciGarbageCollectionDryRunOperation() + : base(dryRun: true) + { + } +} + +/// The garbage collection that removes (). +public sealed class OciGarbageCollectionRunOperation : OciGarbageCollectionOperation +{ + public OciGarbageCollectionRunOperation() + : base(dryRun: false) + { + } +} diff --git a/src/BaGet.Core/Formats/Docker/OciManifestParser.cs b/src/BaGet.Core/Formats/Docker/OciManifestParser.cs new file mode 100644 index 000000000..cad3baaf0 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciManifestParser.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; + +namespace BaGet.Core; + +/// A descriptor of a manifest: a pointer to a blob or manifest by digest. +/// The media type. +/// The digest (sha256:…). +/// The announced size. +/// Whether it is a foreign (non-distributable) layer: a foreign or non-distributable media type with urls. Clients never upload these, so the registry neither requires nor counts them. +public sealed record OciParsedDescriptor(string MediaType, string Digest, long Size, bool Foreign = false); + +/// An entry of an index: a child manifest with the platform it is for. +/// The child. +/// The operating system, or null. +/// The architecture, or null. +/// The variant, or null. +public sealed record OciParsedChild(OciParsedDescriptor Descriptor, string? Os, string? Architecture, string? Variant); + +/// A manifest or index understood by the registry. +public sealed class OciParsedManifest +{ + /// The media type (from the document when it carries one, else the request's). + public string MediaType { get; init; } = string.Empty; + + /// Whether it is an index. + public bool IsIndex { get; init; } + + /// The config of a single-image manifest; null for an index. + public OciParsedDescriptor? Config { get; init; } + + /// The layers of a single-image manifest. + public IReadOnlyList Layers { get; init; } = Array.Empty(); + + /// The entries of an index. + public IReadOnlyList Children { get; init; } = Array.Empty(); + + /// The subject (OCI 1.1), or null. + public OciParsedDescriptor? Subject { get; init; } + + /// The artifact type: the document's artifactType, else the config's media type (single-image manifests). + public string? ArtifactType { get; init; } + + /// The document's annotations. + public IReadOnlyDictionary Annotations { get; init; } = new Dictionary(); + + /// The distinct blob digests the manifest uses (config and layers), foreign layers excluded (they are not stored here). + public IEnumerable BlobDigests + => (Config == null ? Layers : Layers.Prepend(Config)).Where(d => !d.Foreign).Select(d => d.Digest).Distinct(StringComparer.Ordinal); +} + +/// +/// Reads a manifest or index document (OCI image spec and the Docker v2 equivalents) far enough to enforce what a registry +/// must: it is UTF-8 JSON, schema version 2, the media type matches, every descriptor is a well-formed sha256: pointer. +/// It never changes the bytes (the digest is over them). +/// +public static class OciManifestParser +{ + /// + /// Parses . is the request's Content-Type, which must be a + /// supported manifest type and, when the document names one, equal to it. + /// + /// with the reason. + public static OciParsedManifest Parse(string? mediaType, byte[] content) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + + if (!OciNames.IsSupportedManifestType(mediaType)) + { + throw new OciException(OciErrorCode.ManifestInvalid, $"The manifest media type '{mediaType}' is not supported: use {string.Join(", ", OciNames.ImageManifestTypes.Concat(OciNames.IndexTypes))}."); + } + + string text; + try + { + // A BOM, or bytes that are not valid UTF-8, would not round-trip through the stored text: the digest must stay valid. + text = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(content); + } + catch (DecoderFallbackException) + { + throw new OciException(OciErrorCode.ManifestInvalid, "The manifest is not valid UTF-8."); + } + + if (!content.AsSpan().SequenceEqual(Encoding.UTF8.GetBytes(text))) + { + throw new OciException(OciErrorCode.ManifestInvalid, "The manifest must not start with a byte order mark."); + } + + JsonDocument document; + try + { + document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 32 }); + } + catch (JsonException e) + { + throw new OciException(OciErrorCode.ManifestInvalid, "The manifest is not valid JSON: " + e.Message); + } + + using (document) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) throw Invalid("The manifest must be a JSON object."); + + if (!root.TryGetProperty("schemaVersion", out var schema) || schema.ValueKind != JsonValueKind.Number || !schema.TryGetInt32(out var version) || version != 2) + { + throw Invalid("schemaVersion must be 2."); + } + + if (root.TryGetProperty("mediaType", out var declared)) + { + if (declared.ValueKind != JsonValueKind.String || !string.Equals(declared.GetString(), mediaType, StringComparison.Ordinal)) + { + throw Invalid($"The mediaType of the document does not match the Content-Type '{mediaType}'."); + } + } + + var isIndex = OciNames.IsIndex(mediaType); + var subject = root.TryGetProperty("subject", out var subjectElement) && subjectElement.ValueKind != JsonValueKind.Null ? Descriptor(subjectElement, "subject") : null; + var annotations = Annotations(root); + var explicitType = root.TryGetProperty("artifactType", out var artifact) && artifact.ValueKind == JsonValueKind.String ? artifact.GetString() : null; + if (explicitType != null && explicitType.Length > OciNames.MaxMediaTypeLength) throw Invalid("artifactType is too long."); + + if (isIndex) + { + if (!root.TryGetProperty("manifests", out var manifests) || manifests.ValueKind != JsonValueKind.Array) throw Invalid("An index needs a manifests array."); + + var children = new List(); + foreach (var entry in manifests.EnumerateArray()) + { + var descriptor = Descriptor(entry, "manifests[]"); + string? os = null, architecture = null, variant = null; + if (entry.TryGetProperty("platform", out var platform) && platform.ValueKind == JsonValueKind.Object) + { + os = StringOf(platform, "os"); + architecture = StringOf(platform, "architecture"); + variant = StringOf(platform, "variant"); + } + + children.Add(new OciParsedChild(descriptor, os, architecture, variant)); + } + + return new OciParsedManifest + { + MediaType = mediaType!, + IsIndex = true, + Children = children, + Subject = subject, + ArtifactType = explicitType, + Annotations = annotations, + }; + } + + if (!root.TryGetProperty("config", out var config) || config.ValueKind != JsonValueKind.Object) throw Invalid("A manifest needs a config descriptor."); + if (!root.TryGetProperty("layers", out var layers) || layers.ValueKind != JsonValueKind.Array) throw Invalid("A manifest needs a layers array."); + + var configDescriptor = Descriptor(config, "config"); + var layerList = layers.EnumerateArray().Select(l => Descriptor(l, "layers[]")).ToList(); + + return new OciParsedManifest + { + MediaType = mediaType!, + Config = configDescriptor, + Layers = layerList, + Subject = subject, + ArtifactType = explicitType ?? (OciNames.ImageManifestTypes[0] == mediaType ? configDescriptor.MediaType : null), + Annotations = annotations, + }; + } + } + + private static OciException Invalid(string message) => new(OciErrorCode.ManifestInvalid, message); + + private static string? StringOf(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + + private static OciParsedDescriptor Descriptor(JsonElement element, string where) + { + if (element.ValueKind != JsonValueKind.Object) throw Invalid($"{where} must be a descriptor object."); + + var mediaType = StringOf(element, "mediaType"); + var digest = StringOf(element, "digest"); + if (string.IsNullOrEmpty(mediaType)) throw Invalid($"{where} needs a mediaType."); + if (mediaType.Length > OciNames.MaxMediaTypeLength) throw Invalid($"{where} mediaType is too long."); + if (digest == null || !OciNames.LooksLikeDigest(digest)) throw Invalid($"{where} needs a digest."); + if (!OciNames.IsValidDigest(digest)) throw new OciException(OciErrorCode.DigestInvalid, $"{where} uses a digest algorithm this registry does not store (only sha256 is supported).", digest); + if (!element.TryGetProperty("size", out var size) || size.ValueKind != JsonValueKind.Number || !size.TryGetInt64(out var bytes) || bytes < 0) throw Invalid($"{where} needs a size."); + + var foreign = (mediaType.Contains("foreign", StringComparison.OrdinalIgnoreCase) || mediaType.Contains("nondistributable", StringComparison.OrdinalIgnoreCase)) + && element.TryGetProperty("urls", out var urls) && urls.ValueKind == JsonValueKind.Array && urls.GetArrayLength() > 0; + + return new OciParsedDescriptor(mediaType, digest, bytes, foreign); + } + + private static IReadOnlyDictionary Annotations(JsonElement root) + { + var result = new Dictionary(StringComparer.Ordinal); + if (root.TryGetProperty("annotations", out var annotations) && annotations.ValueKind == JsonValueKind.Object) + { + foreach (var property in annotations.EnumerateObject()) + { + if (property.Value.ValueKind == JsonValueKind.String) result[property.Name] = property.Value.GetString()!; + } + } + + return result; + } +} diff --git a/src/BaGet.Core/Formats/Docker/OciNames.cs b/src/BaGet.Core/Formats/Docker/OciNames.cs new file mode 100644 index 000000000..dccaab1eb --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciNames.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace BaGet.Core; + +/// What an OCI route (the part of the path after the BaGet repository) addresses. +public enum OciPathKind +{ + /// {image}/blobs/{digest}. + Blob, + + /// {image}/blobs/uploads/: a new upload session. + UploadStart, + + /// {image}/blobs/uploads/{reference}. + Upload, + + /// {image}/manifests/{reference} (a tag or a digest). + Manifest, + + /// {image}/tags/list. + TagList, + + /// {image}/referrers/{digest}. + Referrers, +} + +/// An OCI request path split into the image and what is asked of it. +/// What the path addresses. +/// The image name inside the BaGet repository (team/app), valid per . +/// The digest, tag or upload reference; null for and . +public sealed record OciPath(OciPathKind Kind, string Image, string? Reference); + +/// +/// The one place that validates and parses OCI names: image names, tags, digests, and the request path of the Distribution +/// Spec ({name}/blobs/{digest}, {name}/blobs/uploads/{ref}, {name}/manifests/{ref}, {name}/tags/list, +/// {name}/referrers/{digest}), where the name has any number of slashes and so can only be found from the right. +/// Image names are lower case, as the specification has them, which is also what keeps two spellings out of storage and +/// the access patterns. +/// +public static class OciNames +{ + /// The longest image name (the column is this wide). + public const int MaxImageLength = 200; + + /// The longest tag, per the specification. + public const int MaxTagLength = 128; + + /// The longest media type or artifact type the columns hold. + public const int MaxMediaTypeLength = 255; + + /// The longest digest the columns hold. + public const int MaxDigestLength = 140; + + /// The storage folder of a Docker repository below the repository's prefix. + public const string StorageFolder = "docker"; + + /// The digest algorithm this registry stores. + public const string Sha256 = "sha256"; + + private static readonly Regex ComponentPattern = new("^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex TagPattern = new("^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex DigestPattern = new("^sha256:[a-f0-9]{64}$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex AnyDigestPattern = new("^[a-z0-9]+(?:[.+_-][a-z0-9]+)*:[a-zA-Z0-9=_-]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex UploadReferencePattern = new("^[A-Za-z0-9_-]{1,128}$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// The media types of a single-image manifest this registry stores. + public static readonly IReadOnlyList ImageManifestTypes = new[] + { + "application/vnd.oci.image.manifest.v1+json", + "application/vnd.docker.distribution.manifest.v2+json", + }; + + /// The media types of a multi-platform index this registry stores. + public static readonly IReadOnlyList IndexTypes = new[] + { + "application/vnd.oci.image.index.v1+json", + "application/vnd.docker.distribution.manifest.list.v2+json", + }; + + /// The media type of the empty descriptor of OCI 1.1 ({}, two bytes). + public const string EmptyMediaType = "application/vnd.oci.empty.v1+json"; + + /// The OCI index media type referrers answer with. + public const string OciIndexType = "application/vnd.oci.image.index.v1+json"; + + /// Whether is a manifest type this registry stores. + public static bool IsSupportedManifestType(string? mediaType) + => mediaType != null && (ImageManifestTypes.Contains(mediaType, StringComparer.Ordinal) || IndexTypes.Contains(mediaType, StringComparer.Ordinal)); + + /// Whether is an index (a list of manifests). + public static bool IsIndex(string? mediaType) => mediaType != null && IndexTypes.Contains(mediaType, StringComparer.Ordinal); + + /// + /// Whether is an image name: one or more lower-case components separated by slashes, each + /// [a-z0-9]+ joined by ., _, __ or dashes; at most characters. + /// + public static bool IsValidImage(string? name) + { + if (string.IsNullOrEmpty(name) || name.Length > MaxImageLength) return false; + + return name.Split('/').All(c => ComponentPattern.IsMatch(c)); + } + + /// Whether is a tag: [A-Za-z0-9_][A-Za-z0-9._-]{0,127}. + public static bool IsValidTag(string? tag) => tag != null && TagPattern.IsMatch(tag); + + /// Whether is a sha256: digest with 64 lower-case hex digits. + public static bool IsValidDigest(string? digest) => digest != null && digest.Length <= MaxDigestLength && DigestPattern.IsMatch(digest); + + /// + /// Whether has the shape of any digest of the specification (algorithm:encoded), supported + /// or not: used to tell a digest this registry does not store from something that is no digest at all. + /// + public static bool LooksLikeDigest(string? digest) => digest != null && digest.Length <= 256 && AnyDigestPattern.IsMatch(digest); + + /// The digest of the hex SHA-256 . + public static string DigestOf(string hex) => Sha256 + ":" + hex; + + /// The hex part of a sha256: digest. + public static string HexOf(string digest) => digest.Substring(Sha256.Length + 1); + + /// + /// Where the blob with is stored, below the repository's prefix: + /// docker/blobs/sha256/ab/abcdef… (two-digit fan-out so a folder never holds millions of entries). + /// + public static string BlobPath(string digest) + { + if (!IsValidDigest(digest)) throw new ArgumentException("Not a sha256 digest.", nameof(digest)); + + var hex = HexOf(digest); + + return $"{StorageFolder}/blobs/{Sha256}/{hex.Substring(0, 2)}/{hex}"; + } + + /// + /// Whether names an upload session: the opaque, URL-safe id the registry handed out. + /// + public static bool IsValidUploadReference(string? reference) => reference != null && UploadReferencePattern.IsMatch(reference); + + /// + /// Splits the part of an OCI path that follows the BaGet repository (team/app/blobs/sha256:…) into what it + /// addresses, or returns null when it is not a path of the specification or names an invalid image, tag or digest. + /// The image name is found from the right because it may contain any number of slashes. + /// + public static OciPath? Parse(string? path) + { + if (string.IsNullOrEmpty(path)) return null; + + var segments = path.Split('/'); + if (segments.Length < 3) return null; + + // {name}/tags/list + if (segments[^2] == "tags" && segments[^1] == "list") + { + return Build(OciPathKind.TagList, segments, 2, reference: null); + } + + // {name}/blobs/uploads/ (a trailing slash gives an empty last segment) and {name}/blobs/uploads/{ref} + if (segments.Length >= 4 && segments[^3] == "blobs" && segments[^2] == "uploads") + { + if (segments[^1].Length == 0) return Build(OciPathKind.UploadStart, segments, 3, reference: null); + + return IsValidUploadReference(segments[^1]) ? Build(OciPathKind.Upload, segments, 3, segments[^1]) : null; + } + + // Some clients leave out the trailing slash of the start URL. + if (segments[^2] == "blobs" && segments[^1] == "uploads") + { + return Build(OciPathKind.UploadStart, segments, 2, reference: null); + } + + var last = segments[^1]; + switch (segments[^2]) + { + case "blobs": + return LooksLikeDigest(last) ? Build(OciPathKind.Blob, segments, 2, last) : null; + + case "manifests": + // Any reference is accepted here: a read of one that is neither a tag nor a digest is "unknown" (404), as the + // specification's conformance suite expects, and only a PUT refuses it (TAG_INVALID). + return last.Length is > 0 and <= 300 ? Build(OciPathKind.Manifest, segments, 2, last) : null; + + case "referrers": + return LooksLikeDigest(last) ? Build(OciPathKind.Referrers, segments, 2, last) : null; + + default: + return null; + } + } + + private static OciPath? Build(OciPathKind kind, string[] segments, int tail, string? reference) + { + var image = string.Join("/", segments.Take(segments.Length - tail)); + + return IsValidImage(image) ? new OciPath(kind, image, reference) : null; + } +} diff --git a/src/BaGet.Core/Formats/Docker/OciPushUndo.cs b/src/BaGet.Core/Formats/Docker/OciPushUndo.cs new file mode 100644 index 000000000..7b690cc05 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciPushUndo.cs @@ -0,0 +1,37 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// Takes back a manifest put that the scanning policy refused. +public static class OciPushUndo +{ + /// + /// A refused put leaves nothing behind: a manifest that was new is removed, and a tag the put created or moved (also onto a manifest + /// the image already held) goes back to where it pointed. Used by the registry route and by pull replication, so both refuse alike. + /// + /// The registry, working in the repository the put went to. + /// The image. + /// The tag or digest the manifest was put under. + /// What the put reported. + public static async Task UndoAsync(IOciRegistry registry, string image, string reference, OciManifestPut put) + { + if (registry == null) throw new ArgumentNullException(nameof(registry)); + if (put == null) throw new ArgumentNullException(nameof(put)); + + var ct = CancellationToken.None; + if (put.Created) await registry.DeleteManifestAsync(image, put.Digest, ct).ConfigureAwait(false); + if (OciNames.LooksLikeDigest(reference)) return; + + if (put.PreviousDigest == null) + { + await registry.DeleteTagAsync(image, reference, ct).ConfigureAwait(false); + } + else if (!string.Equals(put.PreviousDigest, put.Digest, StringComparison.Ordinal)) + { + var previous = await registry.GetManifestAsync(image, put.PreviousDigest, ct).ConfigureAwait(false); + if (previous != null) await registry.PutManifestAsync(image, reference, previous.MediaType, previous.Content, ct).ConfigureAwait(false); + } + } +} diff --git a/src/BaGet.Core/Formats/Docker/OciRegistryService.Cache.cs b/src/BaGet.Core/Formats/Docker/OciRegistryService.Cache.cs new file mode 100644 index 000000000..124f5b188 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciRegistryService.Cache.cs @@ -0,0 +1,382 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// Counts the blob commits in progress in this process (a file committed to storage whose row is not written yet), so a sweep that +/// looks for files without a row () never takes a blob that is about to be recorded for an orphan. +/// +internal static class OciBlobCommits +{ + private static int _inFlight; + private static long _started; + private static readonly KeyedLocks Locks = new(); + + /// + /// Serialises, in this process, the paths of blobs being stored (file committed, then row written) against the same paths being + /// removed (row deleted, then file deleted), so a removal never deletes the file of a blob an upload has just recorded. + /// Paths are taken in a fixed order, so two callers cannot wait on each other. Dispose to release. + /// + public static async Task LockAsync(IEnumerable paths, CancellationToken cancellationToken) + { + var held = new List(); + try + { + foreach (var path in paths.Distinct(StringComparer.Ordinal).OrderBy(p => p, StringComparer.Ordinal)) + { + held.Add(await Locks.LockAsync(path, cancellationToken).ConfigureAwait(false)); + } + } + catch + { + foreach (var h in held) h.Dispose(); + + throw; + } + + return new Group(held); + } + + private sealed class Group : IDisposable + { + private readonly List _held; + + public Group(List held) => _held = held; + + public void Dispose() + { + foreach (var h in _held) h.Dispose(); + _held.Clear(); + } + } + + /// Commits between "file stored" and "row written" right now. + public static int InFlight => Volatile.Read(ref _inFlight); + + /// How many commits have started in this process; a change between two reads means one began in between. + public static long Started => Interlocked.Read(ref _started); + + /// Marks one commit as started; dispose when its row is written (or it failed). + public static IDisposable Enter() + { + Interlocked.Increment(ref _started); + Interlocked.Increment(ref _inFlight); + + return new Exit(); + } + + private sealed class Exit : IDisposable + { + private int _done; + + public void Dispose() + { + if (Interlocked.Exchange(ref _done, 1) == 0) Interlocked.Decrement(ref _inFlight); + } + } +} + +/// +/// A blob being cached from an upstream registry: bytes are appended as they arrive and the blob is stored (its digest verified, its +/// row and its link to the image written) by . Disposing a writer that was not completed discards what was +/// received. The upload is also recorded as an upload session of the image, so a process that dies half way leaves a session the +/// next sweep () aborts, not a file nobody knows about. +/// +public sealed class OciBlobCacheWriter : IAsyncDisposable +{ + private readonly OciRegistryService _owner; + private readonly IStreamingStorageService _streaming; + private readonly int _imageKey; + private readonly string _digest; + private readonly string _uploadId; + private readonly OciUpload _session; + private readonly IDisposable _inFlight; + private long _length; + private bool _finished; + + internal OciBlobCacheWriter(OciRegistryService owner, IStreamingStorageService streaming, int imageKey, string digest, string uploadId, OciUpload session) + { + _owner = owner; + _streaming = streaming; + _imageKey = imageKey; + _digest = digest; + _uploadId = uploadId; + _session = session; + _inFlight = OciBlobCommits.Enter(); + } + + /// The bytes appended so far. + public long Length => _length; + + /// Appends the next bytes. + public async Task AppendAsync(ReadOnlyMemory data, CancellationToken cancellationToken) + { + if (data.IsEmpty) return; + + using var stream = new MemoryStream(data.ToArray(), writable: false); + _length = await _streaming.AppendAsync(_uploadId, _length, stream, cancellationToken).ConfigureAwait(false); + } + + /// + /// Stores the blob under its digest and records it for the image. + /// + /// False when the bytes do not have the digest (nothing is stored). + public async Task CompleteAsync(CancellationToken cancellationToken) + { + if (_finished) return false; + _finished = true; + + try + { + return await _owner.CommitCachedBlobAsync(_imageKey, _digest, _uploadId, _session, cancellationToken).ConfigureAwait(false); + } + finally + { + _inFlight.Dispose(); + } + } + + /// + public async ValueTask DisposeAsync() + { + if (_finished) return; + _finished = true; + + try + { + await _owner.DiscardCachedBlobAsync(_uploadId, _session).ConfigureAwait(false); + } + finally + { + _inFlight.Dispose(); + } + } +} + +public partial class OciRegistryService +{ + /// + /// A manifest of the image by tag or digest, or null when the image or the manifest is not stored. Like + /// for a caller that cannot know whether the image exists yet (a remote repository's first request). + /// + public async Task FindManifestAsync(string image, string reference, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image) || await FindImageAsync(image, cancellationToken).ConfigureAwait(false) == null) return null; + + return await GetManifestAsync(image, reference, cancellationToken).ConfigureAwait(false); + } + + /// + /// Stores a manifest or index fetched from an upstream registry, under when given, creating the image. Unlike + /// a push, it does not require the blobs and child manifests it names to be here: they are fetched when a client asks for them. + /// The document is parsed and its digest computed like any pushed manifest. + /// + /// The document is not a valid manifest. + /// The server is read-only while a database copy runs. + public Task StoreCachedManifestAsync(string image, string? tag, string mediaType, byte[] content, CancellationToken cancellationToken) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + + return PutManifestCoreAsync(image, tag ?? OciNames.DigestOf(StreamingStorage.Sha256Hex(content)), mediaType, content, checkReferences: false, cancellationToken); + } + + /// The blob with as the repository holds it (for any image), if its file is there. + public async Task FindRepositoryBlobAsync(string digest, CancellationToken cancellationToken) + { + RequireSha256(digest); + + var blob = await _context.OciBlobs!.AsNoTracking().FirstOrDefaultAsync(b => b.Digest == digest, cancellationToken).ConfigureAwait(false); + if (blob == null) return null; + + return await Streaming.GetInfoAsync(BlobPath(digest), cancellationToken).ConfigureAwait(false) == null ? null : new OciBlobInfo(digest, blob.Size); + } + + /// + /// Makes a blob the repository already stores (for another image) available to , creating the image. The + /// caller has established that the upstream holds the blob for this image too. + /// + /// False when the repository does not store the blob. + public async Task LinkRepositoryBlobAsync(string image, string digest, CancellationToken cancellationToken) + { + var existing = await FindRepositoryBlobAsync(digest, cancellationToken).ConfigureAwait(false); + if (existing == null) return false; + + var imageKey = await EnsureImageAsync(image, cancellationToken).ConfigureAwait(false); + _gate.ThrowIfClosed(); + + using var blobLock = await OciBlobCommits.LockAsync(new[] { BlobPath(digest) }, cancellationToken).ConfigureAwait(false); + if (await Streaming.GetInfoAsync(BlobPath(digest), cancellationToken).ConfigureAwait(false) == null) return false; + await RecordBlobAsync(imageKey, digest, existing.Size, cancellationToken, countReferences: true).ConfigureAwait(false); + + return true; + } + + /// + /// Starts caching a blob of (creating the image); null while the server is read-only, in which case the + /// blob is passed through without being kept. + /// + public async Task BeginBlobCacheAsync(string image, string digest, CancellationToken cancellationToken) + { + RequireSha256(digest); + if (_gate.IsClosed) return null; + + var imageKey = await EnsureImageAsync(image, cancellationToken).ConfigureAwait(false); + var uploadId = await Streaming.BeginUploadAsync("application/octet-stream", cancellationToken).ConfigureAwait(false); + var now = _time.UtcNow; + var session = new OciUpload { ImageKey = imageKey, Reference = Guid.NewGuid().ToString("N"), StorageUploadId = uploadId, Created = now, Updated = now }; + _context.OciUploads!.Add(session); + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch + { + await TryAbortAsync(uploadId).ConfigureAwait(false); + (_context as DbContext)?.ChangeTracker.Clear(); + + throw; + } + + return new OciBlobCacheWriter(this, Streaming, imageKey, digest, uploadId, session); + } + + internal async Task CommitCachedBlobAsync(int imageKey, string digest, string uploadId, OciUpload session, CancellationToken cancellationToken) + { + using var blobLock = await OciBlobCommits.LockAsync(new[] { BlobPath(digest) }, cancellationToken).ConfigureAwait(false); + StorageCommitResult commit; + try + { + commit = await Streaming.CommitAsync(uploadId, BlobPath(digest), OciNames.HexOf(digest), cancellationToken).ConfigureAwait(false); + } + catch (StorageDigestMismatchException) + { + await ForgetSessionAsync(session).ConfigureAwait(false); + + return false; + } + + if (commit.Result == StoragePutResult.Conflict) + { + _logger.LogError("The file for blob {Digest} exists with other content in repository {Repository}", digest, _repository.Current.Name); + await ForgetSessionAsync(session).ConfigureAwait(false); + + throw new InvalidOperationException("The blob store holds different content under this digest."); + } + + await ForgetSessionAsync(session).ConfigureAwait(false); + await RecordBlobAsync(imageKey, digest, commit.Length, cancellationToken, countReferences: true).ConfigureAwait(false); + await RequireFileAfterAlreadyExistsAsync(commit, imageKey, digest, cancellationToken).ConfigureAwait(false); + + return true; + } + + internal async Task DiscardCachedBlobAsync(string uploadId, OciUpload session) + { + await TryAbortAsync(uploadId).ConfigureAwait(false); + await ForgetSessionAsync(session).ConfigureAwait(false); + } + + // Removes the session row; a context that is gone (the request ended) or a closed gate leave it for the expiry sweep. + private async Task ForgetSessionAsync(OciUpload session) + { + try + { + _context.OciUploads!.Remove(session); + await _context.SaveChangesAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) when (e is ObjectDisposedException or DbUpdateException or MaintenanceException or InvalidOperationException) + { + _logger.LogDebug(e, "The cache session {Reference} was left for the expiry sweep", session.Reference); + } + } + + // How many manifests of the image name the digest (as config or layer): the Manifests count of a new link. + private async Task CountReferencingManifestsAsync(int imageKey, string digest, CancellationToken cancellationToken) + { + var indexTypes = OciNames.IndexTypes.ToArray(); + + return await _context.OciManifests!.AsNoTracking() + .CountAsync(m => m.ImageKey == imageKey && !indexTypes.Contains(m.MediaType!) && m.Content!.Contains(digest), cancellationToken) + .ConfigureAwait(false); + } + + /// + public async Task ProbeAsync(string image, string reference, CancellationToken cancellationToken) + => await FindManifestAsync(image, reference, cancellationToken).ConfigureAwait(false) != null ? ResolutionOutcome.Stored : ResolutionOutcome.NotFound; + + /// The tag's manifest digest, or null. + public async Task FindTagDigestAsync(string image, string tag, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image) || !OciNames.IsValidTag(tag)) return null; + + return await (from i in _context.OciRepositories!.AsNoTracking() + join t in _context.OciTags!.AsNoTracking() on i.Key equals t.ImageKey + join m in _context.OciManifests!.AsNoTracking() on t.ManifestKey equals m.Key + where i.Name == image && t.Name == tag + select m.Digest).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes the stored copy of one tag or digest of the image: a digest removes that manifest, a tag removes the manifest it points at + /// (with every tag of it). The layers nothing uses are left for and the garbage collector. + /// + /// False when nothing was stored under the reference. + public async Task DeleteReferenceAsync(string image, string reference, CancellationToken cancellationToken) + { + var stored = await FindManifestAsync(image, reference, cancellationToken).ConfigureAwait(false); + if (stored == null) return false; + + return await DeleteManifestAsync(image, stored.Digest, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes what a remote repository cached: every image ( null), one image, or one tag or digest of it. The + /// layers a deleted manifest used are removed with the image; after a single manifest they wait for or the + /// garbage collector. + /// + /// The number of manifests deleted. + public async Task PurgeAsync(string? image, string? reference, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + + if (image != null && reference != null) return await DeleteReferenceAsync(image, reference, cancellationToken).ConfigureAwait(false) ? 1 : 0; + + var names = image != null ? new[] { image } : (await ListImageNamesAsync(cancellationToken).ConfigureAwait(false)).ToArray(); + var deleted = 0; + foreach (var name in names) + { + if (!OciNames.IsValidImage(name)) continue; + + var row = await FindImageAsync(name, cancellationToken).ConfigureAwait(false); + if (row == null) continue; + + var manifests = await _context.OciManifests!.AsNoTracking().CountAsync(m => m.ImageKey == row.Key, cancellationToken).ConfigureAwait(false); + if (await DeleteImageAsync(name, cancellationToken).ConfigureAwait(false)) deleted += manifests; + } + + return deleted; + } + + /// The number of manifests and images stored, and the bytes of the distinct blobs held. + public async Task<(int Manifests, int Images, long Bytes)> GetUsageAsync(CancellationToken cancellationToken) + { + var manifests = await (from m in _context.OciManifests!.AsNoTracking() + join i in _context.OciRepositories!.AsNoTracking() on m.ImageKey equals i.Key + select m.Key).CountAsync(cancellationToken).ConfigureAwait(false); + var images = await _context.OciRepositories!.AsNoTracking().CountAsync(cancellationToken).ConfigureAwait(false); + var bytes = await _context.OciBlobs!.AsNoTracking().SumAsync(b => (long?)b.Size, cancellationToken).ConfigureAwait(false) ?? 0; + + return (manifests, images, bytes); + } + + /// Names of every stored image (no access filter): what a purge walks. + public async Task> ListImageNamesAsync(CancellationToken cancellationToken) + => await _context.OciRepositories!.AsNoTracking().OrderBy(i => i.Name).Select(i => i.Name!).ToListAsync(cancellationToken).ConfigureAwait(false); +} diff --git a/src/BaGet.Core/Formats/Docker/OciRegistryService.cs b/src/BaGet.Core/Formats/Docker/OciRegistryService.cs new file mode 100644 index 000000000..eab6c811b --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciRegistryService.cs @@ -0,0 +1,1130 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// over the Oci tables and a streaming storage service. Rows live in the repository of the request +/// (the context's query filter and stamping); a blob is one file per digest under docker/blobs/sha256/… of the +/// repository's storage prefix, shared by every image of the repository, and is served under an image only through an +/// . Manifests are rows. Every write calls before it stores a +/// file or a row. +/// +public partial class OciRegistryService : IOciRegistry +{ + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IRepositoryContext _repository; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + private readonly IOptionsSnapshot? _options; + private readonly ArtifactUsageRecorder? _usage; + + /// The database. + /// Where blobs are kept; it must stream (). + /// The repository of the request. + /// The clock. + /// The read-only gate, checked before anything is stored or removed. + /// The logger. + /// The Oci:* options. + /// Notes downloads for the retention rules; null records nothing. + public OciRegistryService( + IContext context, + IStorageService storage, + IRepositoryContext repository, + SystemTime time, + MaintenanceGate gate, + ILogger logger, + IOptionsSnapshot? options = null, + ArtifactUsageRecorder? usage = null) + { + _usage = usage; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _options = options; + } + + private OciOptions Options => _options?.Value ?? new OciOptions(); + + private IStreamingStorageService Streaming => StreamingStorage.Require(_storage, "Docker repositories"); + + private string BlobPath(string digest) => RepositoryStorage.Scope(_repository.Current, OciNames.BlobPath(digest)); + + private static DateTime Utc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc); + + private static OciException UnknownImage(string image) => new(OciErrorCode.NameUnknown, $"The repository '{image}' does not exist.", image); + + private static void ValidateImage(string image) + { + if (!OciNames.IsValidImage(image)) throw new OciException(OciErrorCode.NameInvalid, $"'{image}' is not a valid repository name: lower-case letters, digits, '.', '_', '-' in components separated by '/'."); + } + + private static string RequireSha256(string digest) + { + if (!OciNames.IsValidDigest(digest)) + { + throw new OciException(OciErrorCode.DigestInvalid, OciNames.LooksLikeDigest(digest) + ? "Only sha256 digests are supported." + : "The digest is not valid: sha256:<64 lower-case hex digits>.", digest); + } + + return digest; + } + + private Task FindImageAsync(string image, CancellationToken cancellationToken) + => _context.OciRepositories!.AsNoTracking().FirstOrDefaultAsync(i => i.Name == image, cancellationToken); + + private async Task RequireImageAsync(string image, CancellationToken cancellationToken) + { + ValidateImage(image); + + return await FindImageAsync(image, cancellationToken).ConfigureAwait(false) ?? throw UnknownImage(image); + } + + // The image is created by the first upload or manifest. Called before the work that follows starts a transaction. + private async Task EnsureImageAsync(string image, CancellationToken cancellationToken) + { + ValidateImage(image); + + for (var attempt = 0; ; attempt++) + { + var existing = await FindImageAsync(image, cancellationToken).ConfigureAwait(false); + if (existing != null) return existing.Key; + + _gate.ThrowIfClosed(); + + var now = _time.UtcNow; + var row = new OciRepository { Name = image, Created = now, Modified = now }; + _context.OciRepositories!.Add(row); + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return row.Key; + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e) && attempt < 2) + { + // A concurrent push created the image first. + (_context as DbContext)?.ChangeTracker.Clear(); + } + } + } + + // ---- reads ------------------------------------------------------------------------------------------------------ + + /// + public async Task ImageExistsAsync(string image, CancellationToken cancellationToken) + => OciNames.IsValidImage(image) && await FindImageAsync(image, cancellationToken).ConfigureAwait(false) != null; + + private async Task FindHeldBlobAsync(int imageKey, string digest, CancellationToken cancellationToken) + => await (from l in _context.OciBlobLinks!.AsNoTracking() + join b in _context.OciBlobs!.AsNoTracking() on l.BlobKey equals b.Key + where l.ImageKey == imageKey && b.Digest == digest + select b).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + + /// + public async Task GetBlobInfoAsync(string image, string digest, CancellationToken cancellationToken) + { + RequireSha256(digest); + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var blob = await FindHeldBlobAsync(row.Key, digest, cancellationToken).ConfigureAwait(false); + + return blob == null ? null : new OciBlobInfo(digest, blob.Size); + } + + /// + public async Task OpenBlobAsync(string image, string digest, long offset, long? length, CancellationToken cancellationToken) + { + RequireSha256(digest); + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var blob = await FindHeldBlobAsync(row.Key, digest, cancellationToken).ConfigureAwait(false); + if (blob == null) return null; + + if (offset < 0 || offset > blob.Size) throw new ArgumentOutOfRangeException(nameof(offset)); + var count = Math.Min(length ?? blob.Size - offset, blob.Size - offset); + + var stream = await Streaming.GetRangeAsync(BlobPath(digest), offset, count, cancellationToken).ConfigureAwait(false); + if (stream == null) + { + _logger.LogError("The blob {Digest} is recorded in repository {Repository} but its file is missing", digest, _repository.Current.Name); + + return null; + } + + return new OciBlobContent(stream, digest, blob.Size, offset, count); + } + + /// + public async Task GetManifestAsync(string image, string reference, CancellationToken cancellationToken) + { + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + + OciManifest? manifest; + if (OciNames.LooksLikeDigest(reference)) + { + if (!OciNames.IsValidDigest(reference)) return null; + + manifest = await _context.OciManifests!.AsNoTracking().FirstOrDefaultAsync(m => m.ImageKey == row.Key && m.Digest == reference, cancellationToken).ConfigureAwait(false); + } + else + { + // Neither a digest nor a tag: nothing can be stored under it, so there is nothing to find. + if (!OciNames.IsValidTag(reference)) return null; + + manifest = await (from t in _context.OciTags!.AsNoTracking() + join m in _context.OciManifests!.AsNoTracking() on t.ManifestKey equals m.Key + where t.ImageKey == row.Key && t.Name == reference + select m).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + // For the retention rules: the tag or digest was just pulled. + if (manifest != null) _usage?.Touch(_repository.Current.Key, image, reference); + + return manifest == null + ? null + : new OciManifestContent(manifest.Digest!, manifest.MediaType!, Encoding.UTF8.GetBytes(manifest.Content!), manifest.SubjectDigest, manifest.ArtifactType, Utc(manifest.Created)); + } + + /// + public async Task ListTagsAsync(string image, int? count, string? last, CancellationToken cancellationToken) + { + ValidateImage(image); + var row = await FindImageAsync(image, cancellationToken).ConfigureAwait(false); + if (row == null) return null; + + // Compared and ordered here, by code point: the engines collate differently and a page boundary must be exact. + var names = await _context.OciTags!.AsNoTracking().Where(t => t.ImageKey == row.Key).Select(t => t.Name!).ToListAsync(cancellationToken).ConfigureAwait(false); + IEnumerable ordered = names.OrderBy(n => n, StringComparer.Ordinal); + if (!string.IsNullOrEmpty(last)) ordered = ordered.Where(n => string.CompareOrdinal(n, last) > 0); + + var all = ordered.ToList(); + if (count == null) return new OciTagList(image, all, HasMore: false); + + var page = all.Take(Math.Max(count.Value, 0)).ToList(); + + return new OciTagList(image, page, HasMore: all.Count > page.Count); + } + + /// + public async Task?> GetReferrersAsync(string image, string digest, string? artifactType, CancellationToken cancellationToken) + { + RequireSha256(digest); + ValidateImage(image); + var row = await FindImageAsync(image, cancellationToken).ConfigureAwait(false); + if (row == null) return null; + + var query = _context.OciManifests!.AsNoTracking().Where(m => m.ImageKey == row.Key && m.SubjectDigest == digest); + if (!string.IsNullOrEmpty(artifactType)) query = query.Where(m => m.ArtifactType == artifactType); + + var manifests = await query.OrderBy(m => m.Created).ThenBy(m => m.Digest).ToListAsync(cancellationToken).ConfigureAwait(false); + + var result = new List(); + foreach (var manifest in manifests) + { + IReadOnlyDictionary? annotations = null; + try + { + var parsed = OciManifestParser.Parse(manifest.MediaType, Encoding.UTF8.GetBytes(manifest.Content!)); + if (parsed.Annotations.Count > 0) annotations = parsed.Annotations; + } + catch (OciException) + { + // Stored documents were validated on the way in; a row that no longer parses is listed without annotations. + } + + result.Add(new OciDescriptor(manifest.MediaType!, manifest.Digest!, manifest.Size, manifest.ArtifactType, annotations)); + } + + return result; + } + + // ---- uploads ---------------------------------------------------------------------------------------------------- + + private async Task FindUploadAsync(int imageKey, string reference, bool tracked, CancellationToken cancellationToken) + { + if (!OciNames.IsValidUploadReference(reference)) return null; + + var query = _context.OciUploads!.Where(u => u.ImageKey == imageKey && u.Reference == reference); + + return await (tracked ? query : query.AsNoTracking()).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task GetUploadAsync(string image, string reference, CancellationToken cancellationToken) + { + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var upload = await FindUploadAsync(row.Key, reference, tracked: false, cancellationToken).ConfigureAwait(false); + if (upload == null) return null; + + var length = await Streaming.GetUploadLengthAsync(upload.StorageUploadId!, cancellationToken).ConfigureAwait(false); + + return length == null ? null : new OciUploadState(reference, length.Value); + } + + /// + public async Task StartUploadAsync(string image, CancellationToken cancellationToken) + { + var imageKey = await EnsureImageAsync(image, cancellationToken).ConfigureAwait(false); + _gate.ThrowIfClosed(); + + await ExpireUploadsAsync(cancellationToken).ConfigureAwait(false); + + var storageId = await Streaming.BeginUploadAsync("application/octet-stream", cancellationToken).ConfigureAwait(false); + var now = _time.UtcNow; + var reference = Guid.NewGuid().ToString("N"); + _context.OciUploads!.Add(new OciUpload { ImageKey = imageKey, Reference = reference, StorageUploadId = storageId, Created = now, Updated = now }); + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch + { + await TryAbortAsync(storageId).ConfigureAwait(false); + throw; + } + + return new OciUploadState(reference, 0); + } + + // Sessions nobody touched for Oci:UploadExpiry are discarded whenever a new one starts, so abandoned pushes do not pile up. + private async Task ExpireUploadsAsync(CancellationToken cancellationToken) + { + var cutoff = _time.UtcNow - Options.UploadExpiry; + var stale = await (from u in _context.OciUploads! + join i in _context.OciRepositories! on u.ImageKey equals i.Key + where u.Updated < cutoff + select u).ToListAsync(cancellationToken).ConfigureAwait(false); + if (stale.Count == 0) return; + + _context.OciUploads!.RemoveRange(stale); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + foreach (var upload in stale) await TryAbortAsync(upload.StorageUploadId!).ConfigureAwait(false); + } + + private async Task TryAbortAsync(string storageUploadId) + { + try + { + await Streaming.AbortAsync(storageUploadId, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "Could not abort the upload {UploadId}", storageUploadId); + } + } + + /// + public async Task AppendAsync(string image, string reference, long? offset, Stream chunk, CancellationToken cancellationToken) + { + if (chunk == null) throw new ArgumentNullException(nameof(chunk)); + + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var upload = await FindUploadAsync(row.Key, reference, tracked: true, cancellationToken).ConfigureAwait(false) + ?? throw new OciException(OciErrorCode.BlobUploadUnknown, "The upload session does not exist.", reference); + + var length = await AppendCoreAsync(upload, offset, chunk, cancellationToken).ConfigureAwait(false); + + return new OciUploadState(reference, length); + } + + private async Task AppendCoreAsync(OciUpload upload, long? offset, Stream chunk, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + + var current = await Streaming.GetUploadLengthAsync(upload.StorageUploadId!, cancellationToken).ConfigureAwait(false); + if (current == null) + { + _context.OciUploads!.Remove(upload); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + throw new OciException(OciErrorCode.BlobUploadUnknown, "The upload session has expired.", upload.Reference); + } + + if (offset != null && offset.Value != current.Value) + { + throw new OciException(OciErrorCode.RangeInvalid, $"The chunk starts at {offset.Value} but the upload holds {current.Value} bytes.", current.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)) { UploadLength = current.Value }; + } + + // An empty chunk (a PATCH with no body, a final PUT with none) adds nothing: not every store takes an empty part. + var length = current.Value; + var data = await OciStreams.NonEmptyAsync(chunk, cancellationToken).ConfigureAwait(false); + try + { + if (data != null) length = await Streaming.AppendAsync(upload.StorageUploadId!, current.Value, data, cancellationToken).ConfigureAwait(false); + } + catch (StorageUploadOffsetException e) + { + throw new OciException(OciErrorCode.RangeInvalid, e.Message, e.ActualLength.ToString(System.Globalization.CultureInfo.InvariantCulture)) { UploadLength = e.ActualLength }; + } + catch (StorageUploadNotFoundException) + { + throw new OciException(OciErrorCode.BlobUploadUnknown, "The upload session does not exist.", upload.Reference); + } + + upload.Updated = _time.UtcNow; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return length; + } + + /// + public async Task CompleteUploadAsync(string image, string reference, string digest, long? offset, Stream? lastChunk, CancellationToken cancellationToken) + { + RequireSha256(digest); + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var upload = await FindUploadAsync(row.Key, reference, tracked: true, cancellationToken).ConfigureAwait(false) + ?? throw new OciException(OciErrorCode.BlobUploadUnknown, "The upload session does not exist.", reference); + var uploadId = upload.StorageUploadId!; + + _gate.ThrowIfClosed(); + using var inFlight = OciBlobCommits.Enter(); + + if (lastChunk != null) await AppendCoreAsync(upload, offset, lastChunk, cancellationToken).ConfigureAwait(false); + + using var blobLock = await OciBlobCommits.LockAsync(new[] { BlobPath(digest) }, cancellationToken).ConfigureAwait(false); + StorageCommitResult commit; + try + { + commit = await Streaming.CommitAsync(uploadId, BlobPath(digest), OciNames.HexOf(digest), cancellationToken).ConfigureAwait(false); + } + catch (StorageDigestMismatchException) + { + // The content is discarded with the session: the client starts again. + _context.OciUploads!.Remove(upload); + await _context.SaveChangesAsync(CancellationToken.None).ConfigureAwait(false); + + throw new OciException(OciErrorCode.DigestInvalid, "The uploaded content does not have the digest given.", digest); + } + catch (StorageUploadNotFoundException) + { + _context.OciUploads!.Remove(upload); + await _context.SaveChangesAsync(CancellationToken.None).ConfigureAwait(false); + + throw new OciException(OciErrorCode.BlobUploadUnknown, "The upload session does not exist.", reference); + } + + if (commit.Result == StoragePutResult.Conflict) + { + _logger.LogError("The file for blob {Digest} exists with other content in repository {Repository}", digest, _repository.Current.Name); + throw new InvalidOperationException("The blob store holds different content under this digest."); + } + + _context.OciUploads!.Remove(upload); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await RecordBlobAsync(row.Key, digest, commit.Length, cancellationToken).ConfigureAwait(false); + await RequireFileAfterAlreadyExistsAsync(commit, row.Key, digest, cancellationToken).ConfigureAwait(false); + + return new OciBlobStored(digest, commit.Length); + } + + /// + public async Task CancelUploadAsync(string image, string reference, CancellationToken cancellationToken) + { + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var upload = await FindUploadAsync(row.Key, reference, tracked: true, cancellationToken).ConfigureAwait(false); + if (upload == null) return false; + + _gate.ThrowIfClosed(); + + _context.OciUploads!.Remove(upload); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await TryAbortAsync(upload.StorageUploadId!).ConfigureAwait(false); + + return true; + } + + /// + public async Task PutBlobAsync(string image, string digest, Stream content, CancellationToken cancellationToken) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + + RequireSha256(digest); + var imageKey = await EnsureImageAsync(image, cancellationToken).ConfigureAwait(false); + _gate.ThrowIfClosed(); + using var inFlight = OciBlobCommits.Enter(); + + // The body is read before the digest is locked: a slow client must not hold up deletes, the GC or other pushes. + var uploadId = await Streaming.BeginUploadAsync("application/octet-stream", cancellationToken).ConfigureAwait(false); + try + { + var data = await OciStreams.NonEmptyAsync(content, cancellationToken).ConfigureAwait(false); + if (data != null) await Streaming.AppendAsync(uploadId, 0, data, cancellationToken).ConfigureAwait(false); + } + catch + { + await TryAbortAsync(uploadId).ConfigureAwait(false); + throw; + } + + using var blobLock = await OciBlobCommits.LockAsync(new[] { BlobPath(digest) }, cancellationToken).ConfigureAwait(false); + StorageCommitResult commit; + try + { + commit = await Streaming.CommitAsync(uploadId, BlobPath(digest), OciNames.HexOf(digest), cancellationToken).ConfigureAwait(false); + } + catch (StorageDigestMismatchException) + { + throw new OciException(OciErrorCode.DigestInvalid, "The uploaded content does not have the digest given.", digest); + } + catch + { + await TryAbortAsync(uploadId).ConfigureAwait(false); + throw; + } + + if (commit.Result == StoragePutResult.Conflict) throw new InvalidOperationException("The blob store holds different content under this digest."); + + await RecordBlobAsync(imageKey, digest, commit.Length, cancellationToken).ConfigureAwait(false); + await RequireFileAfterAlreadyExistsAsync(commit, imageKey, digest, cancellationToken).ConfigureAwait(false); + + return new OciBlobStored(digest, commit.Length); + } + + // A commit onto an existing file reports AlreadyExists; the file may have been removed (by another node, which the in-process + // lock cannot see) after the row was written. Look once more: if it is gone, undo the record (else a retrying client's HEAD would + // find the row, skip the upload and the blob would be a 404) and fail so the client uploads again. + private async Task RequireFileAfterAlreadyExistsAsync(StorageCommitResult commit, int imageKey, string digest, CancellationToken cancellationToken) + { + if (commit.Result != StoragePutResult.AlreadyExists) return; + if (await Streaming.GetInfoAsync(BlobPath(digest), cancellationToken).ConfigureAwait(false) != null) return; + + await UnrecordBlobAsync(imageKey, digest).ConfigureAwait(false); + + throw new OciException(OciErrorCode.BlobUploadInvalid, "The blob was removed while it was being stored: upload it again.", digest); + } + + // Takes back RecordBlobAsync for a blob whose file is gone: the image's link, and the blob row when no image holds it. The caller + // holds the digest lock. + private async Task UnrecordBlobAsync(int imageKey, string digest) + { + (_context as DbContext)?.ChangeTracker.Clear(); + await using var transaction = await _context.Database.BeginTransactionAsync(CancellationToken.None).ConfigureAwait(false); + + var blob = await _context.OciBlobs!.FirstOrDefaultAsync(b => b.Digest == digest, CancellationToken.None).ConfigureAwait(false); + if (blob == null) return; + + var link = await _context.OciBlobLinks!.FirstOrDefaultAsync(l => l.ImageKey == imageKey && l.BlobKey == blob.Key, CancellationToken.None).ConfigureAwait(false); + if (link != null) _context.OciBlobLinks!.Remove(link); + await _context.SaveChangesAsync(CancellationToken.None).ConfigureAwait(false); + + var holders = await _context.OciBlobLinks!.CountAsync(l => l.BlobKey == blob.Key, CancellationToken.None).ConfigureAwait(false); + if (holders == 0) _context.OciBlobs!.Remove(blob); + else blob.RefCount = holders; + await _context.SaveChangesAsync(CancellationToken.None).ConfigureAwait(false); + await transaction.CommitAsync(CancellationToken.None).ConfigureAwait(false); + } + + // Records that the image holds the blob (creating the blob row when this is the repository's first copy) and settles the + // upload session removal that the caller staged. A concurrent push of the same layer races on the unique indexes. + private async Task RecordBlobAsync(int imageKey, string digest, long size, CancellationToken cancellationToken, bool countReferences = false) + { + for (var attempt = 0; ; attempt++) + { + try + { + await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + + var blob = await _context.OciBlobs!.FirstOrDefaultAsync(b => b.Digest == digest, cancellationToken).ConfigureAwait(false); + if (blob == null) + { + blob = new OciBlob { Digest = digest, Size = size, RefCount = 0, Created = _time.UtcNow }; + _context.OciBlobs!.Add(blob); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + var linked = await _context.OciBlobLinks!.AnyAsync(l => l.ImageKey == imageKey && l.BlobKey == blob.Key, cancellationToken).ConfigureAwait(false); + if (!linked) + { + // A layer cached for an image whose manifest is already stored is used by that manifest; an uploaded one is not yet. + var users = countReferences ? await CountReferencingManifestsAsync(imageKey, digest, cancellationToken).ConfigureAwait(false) : 0; + _context.OciBlobLinks!.Add(new OciBlobLink { ImageKey = imageKey, BlobKey = blob.Key, Manifests = users, Created = _time.UtcNow }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + blob.RefCount = await _context.OciBlobLinks!.CountAsync(l => l.BlobKey == blob.Key, cancellationToken).ConfigureAwait(false); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + + return; + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e) && attempt < 2) + { + // A concurrent upload of the same blob (or into the same image) created the row first: look again. + (_context as DbContext)?.ChangeTracker.Clear(); + } + } + } + + /// + public async Task MountBlobAsync(string image, string digest, string fromImage, CancellationToken cancellationToken) + { + RequireSha256(digest); + ValidateImage(fromImage); + + var source = await FindImageAsync(fromImage, cancellationToken).ConfigureAwait(false); + if (source == null) return false; + + var blob = await FindHeldBlobAsync(source.Key, digest, cancellationToken).ConfigureAwait(false); + if (blob == null) return false; + + var imageKey = await EnsureImageAsync(image, cancellationToken).ConfigureAwait(false); + _gate.ThrowIfClosed(); + + // Under the digest lock, and only while the file is there: a delete of the source image may have removed the blob since. + using var blobLock = await OciBlobCommits.LockAsync(new[] { BlobPath(digest) }, cancellationToken).ConfigureAwait(false); + if (await Streaming.GetInfoAsync(BlobPath(digest), cancellationToken).ConfigureAwait(false) == null) return false; + await RecordBlobAsync(imageKey, digest, blob.Size, cancellationToken).ConfigureAwait(false); + + return true; + } + + // ---- manifests -------------------------------------------------------------------------------------------------- + + /// + public Task PutManifestAsync(string image, string reference, string? mediaType, byte[] content, CancellationToken cancellationToken) + => PutManifestCoreAsync(image, reference, mediaType, content, checkReferences: true, cancellationToken); + + // checkReferences false: a manifest cached from an upstream registry is stored before its layers are (they follow when a client + // asks for them), so the blobs and children it names need not be here yet. + private async Task PutManifestCoreAsync(string image, string reference, string? mediaType, byte[] content, bool checkReferences, CancellationToken cancellationToken) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + + ValidateImage(image); + var byDigest = OciNames.LooksLikeDigest(reference); + if (byDigest) RequireSha256(reference); + else if (!OciNames.IsValidTag(reference)) throw new OciException(OciErrorCode.TagInvalid, $"'{reference}' is not a valid tag: letters, digits, '_', '.', '-', at most 128, not starting with '.' or '-'."); + + if (content.Length > Options.MaxManifestBytes) + { + throw new OciException(OciErrorCode.ManifestTooLarge, $"The manifest is larger than {Options.MaxManifestBytes} bytes."); + } + + var parsed = OciManifestParser.Parse(mediaType, content); + var digest = OciNames.DigestOf(StreamingStorage.Sha256Hex(content)); + if (byDigest && !string.Equals(reference, digest, StringComparison.Ordinal)) + { + throw new OciException(OciErrorCode.DigestInvalid, "The manifest does not have the digest in the URL.", digest); + } + + var imageKey = await EnsureImageAsync(image, cancellationToken).ConfigureAwait(false); + _gate.ThrowIfClosed(); + + var text = Encoding.UTF8.GetString(content); + for (var attempt = 0; ; attempt++) + { + try + { + await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + var now = _time.UtcNow; + + // Everything the manifest points at must already be in the image (a client pushes layers, then children, then this). + var wanted = parsed.IsIndex + ? parsed.Children.Select(c => c.Descriptor.Digest).Distinct(StringComparer.Ordinal).ToList() + : parsed.BlobDigests.ToList(); + + List links = new(); + if (parsed.IsIndex) + { + var present = await _context.OciManifests!.AsNoTracking().Where(m => m.ImageKey == imageKey && wanted.Contains(m.Digest!)).Select(m => m.Digest!).ToListAsync(cancellationToken).ConfigureAwait(false); + var missing = wanted.FirstOrDefault(d => !present.Contains(d, StringComparer.Ordinal)); + if (missing != null && checkReferences) throw new OciException(OciErrorCode.ManifestBlobUnknown, "The index references a manifest the repository does not hold.", missing); + } + else + { + var held = await (from l in _context.OciBlobLinks! + join b in _context.OciBlobs! on l.BlobKey equals b.Key + where l.ImageKey == imageKey && wanted.Contains(b.Digest!) + select new { Link = l, b.Digest }).ToListAsync(cancellationToken).ConfigureAwait(false); + var missing = wanted.FirstOrDefault(d => held.All(h => !string.Equals(h.Digest, d, StringComparison.Ordinal))); + if (missing != null && checkReferences) throw new OciException(OciErrorCode.ManifestBlobUnknown, "The manifest references a blob the repository does not hold.", missing); + + links = held.Select(h => h.Link).ToList(); + } + + var manifest = await _context.OciManifests!.FirstOrDefaultAsync(m => m.ImageKey == imageKey && m.Digest == digest, cancellationToken).ConfigureAwait(false); + var created = manifest == null; + if (manifest == null) + { + manifest = new OciManifest + { + ImageKey = imageKey, + Digest = digest, + MediaType = parsed.MediaType, + ArtifactType = parsed.ArtifactType, + SubjectDigest = parsed.Subject?.Digest, + Size = content.LongLength, + Content = text, + Created = now, + }; + _context.OciManifests!.Add(manifest); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // The count is raised in the database (Manifests = Manifests + 1), never written back as a number this request read: + // two pushes using the same layer would otherwise both write the same value and lose one reference. + if (links.Count > 0) + { + var linkKeys = links.Select(l => l.Key).ToList(); + var raised = await _context.OciBlobLinks!.Where(l => linkKeys.Contains(l.Key)) + .ExecuteUpdateAsync(s => s.SetProperty(l => l.Manifests, l => l.Manifests + 1), cancellationToken).ConfigureAwait(false); + if (raised != linkKeys.Count && checkReferences) + { + // A layer link was removed (a prune) between the check and now. + throw new OciException(OciErrorCode.ManifestBlobUnknown, "The manifest references a blob the repository does not hold."); + } + } + } + + string? previousDigest = null; + if (!byDigest) + { + var tag = await _context.OciTags!.FirstOrDefaultAsync(t => t.ImageKey == imageKey && t.Name == reference, cancellationToken).ConfigureAwait(false); + if (tag != null) + { + previousDigest = await _context.OciManifests!.AsNoTracking().Where(m => m.Key == tag.ManifestKey).Select(m => m.Digest).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + if (tag == null) + { + _context.OciTags!.Add(new OciTag { ImageKey = imageKey, Name = reference, ManifestKey = manifest.Key, Updated = now }); + } + else if (tag.ManifestKey != manifest.Key) + { + tag.ManifestKey = manifest.Key; + tag.Updated = now; + } + } + + var imageRow = await _context.OciRepositories!.FirstAsync(i => i.Key == imageKey, cancellationToken).ConfigureAwait(false); + imageRow.Modified = now; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + + return new OciManifestPut(digest, parsed.Subject?.Digest, created, previousDigest); + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e) && attempt < 2) + { + // A concurrent push of the same manifest or tag won; apply on top of its rows. + (_context as DbContext)?.ChangeTracker.Clear(); + } + } + } + + // ---- deletes ---------------------------------------------------------------------------------------------------- + + // Recomputes the holders of each blob and removes the blob (row and file) when no image holds it any more. + // The digests are locked (OciBlobCommits) from the holder check to the file deletion: an upload of the same blob in this process + // either records its row before the check (the blob is kept) or stores its file after the deletion. + private async Task ReleaseBlobsAsync(IReadOnlyCollection blobKeys, CancellationToken cancellationToken) + { + var distinct = blobKeys.Distinct().ToList(); + var digests = await _context.OciBlobs!.AsNoTracking().Where(b => distinct.Contains(b.Key)).Select(b => b.Digest!).ToListAsync(cancellationToken).ConfigureAwait(false); + using var blobLocks = await OciBlobCommits.LockAsync(digests.Select(BlobPath), cancellationToken).ConfigureAwait(false); + + var files = new List(); + foreach (var key in distinct) + { + var blob = await _context.OciBlobs!.FirstOrDefaultAsync(b => b.Key == key, cancellationToken).ConfigureAwait(false); + if (blob == null) continue; + + var holders = await _context.OciBlobLinks!.CountAsync(l => l.BlobKey == key, cancellationToken).ConfigureAwait(false); + if (holders == 0) + { + _context.OciBlobs!.Remove(blob); + files.Add(BlobPath(blob.Digest!)); + } + else + { + blob.RefCount = holders; + } + } + + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + foreach (var path in files) + { + try + { + await _storage.DeleteAsync(path, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "Could not delete the blob file {Path}", path); + } + } + } + + /// + public async Task DeleteManifestAsync(string image, string digest, CancellationToken cancellationToken) + { + RequireSha256(digest); + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var manifest = await _context.OciManifests!.FirstOrDefaultAsync(m => m.ImageKey == row.Key && m.Digest == digest, cancellationToken).ConfigureAwait(false); + if (manifest == null) return false; + + _gate.ThrowIfClosed(); + + await DeleteManifestRowAsync(row.Key, manifest, cancellationToken).ConfigureAwait(false); + + return true; + } + + // Deleting the row deletes its tags (foreign key); the blobs it used lose one manifest reference. + private async Task DeleteManifestRowAsync(int imageKey, OciManifest manifest, CancellationToken cancellationToken) + { + var digests = new List(); + try + { + var parsed = OciManifestParser.Parse(manifest.MediaType, Encoding.UTF8.GetBytes(manifest.Content!)); + if (!parsed.IsIndex) digests.AddRange(parsed.BlobDigests); + } + catch (OciException) + { + // A document that no longer parses had no counted references to give back. + } + + var links = digests.Count == 0 + ? new List() + : await (from l in _context.OciBlobLinks! + join b in _context.OciBlobs! on l.BlobKey equals b.Key + where l.ImageKey == imageKey && digests.Contains(b.Digest!) + select l).ToListAsync(cancellationToken).ConfigureAwait(false); + _gate.ThrowIfClosed(); + await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + + // Removing the row first: a second delete of the same manifest fails here (nothing deleted) and gives no reference back twice. + _context.OciManifests!.Remove(manifest); + var image = await _context.OciRepositories!.FirstOrDefaultAsync(i => i.Key == imageKey, cancellationToken).ConfigureAwait(false); + if (image != null) image.Modified = _time.UtcNow; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Lowered in the database (never below 0), like the raise in PutManifestCoreAsync. + if (links.Count > 0) + { + var linkKeys = links.Select(l => l.Key).ToList(); + await _context.OciBlobLinks!.Where(l => linkKeys.Contains(l.Key) && l.Manifests > 0) + .ExecuteUpdateAsync(s => s.SetProperty(l => l.Manifests, l => l.Manifests - 1), cancellationToken).ConfigureAwait(false); + } + + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task DeleteTagAsync(string image, string tag, CancellationToken cancellationToken) + { + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + if (!OciNames.IsValidTag(tag)) return false; + + var existing = await _context.OciTags!.FirstOrDefaultAsync(t => t.ImageKey == row.Key && t.Name == tag, cancellationToken).ConfigureAwait(false); + if (existing == null) return false; + + _gate.ThrowIfClosed(); + + _context.OciTags!.Remove(existing); + var imageRow = await _context.OciRepositories!.FirstOrDefaultAsync(i => i.Key == row.Key, cancellationToken).ConfigureAwait(false); + if (imageRow != null) imageRow.Modified = _time.UtcNow; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return true; + } + + /// + public async Task DeleteBlobAsync(string image, string digest, CancellationToken cancellationToken) + { + RequireSha256(digest); + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + var link = await (from l in _context.OciBlobLinks! + join b in _context.OciBlobs! on l.BlobKey equals b.Key + where l.ImageKey == row.Key && b.Digest == digest + select l).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (link == null) return false; + + if (link.Manifests > 0) + { + throw new OciException(OciErrorCode.Unsupported, "The blob is used by a manifest of this repository: delete the manifest first.", digest); + } + + _gate.ThrowIfClosed(); + + // Deleted only while no manifest uses it (the count is checked by the statement itself, not by the read above), so a manifest + // pushed in between keeps its layer. + var blobKey = link.BlobKey; + var deleted = await _context.OciBlobLinks!.Where(l => l.Key == link.Key && l.Manifests == 0).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + (_context as DbContext)?.Entry(link).State = EntityState.Detached; + if (deleted == 0) + { + throw new OciException(OciErrorCode.Unsupported, "The blob is used by a manifest of this repository: delete the manifest first.", digest); + } + + await ReleaseBlobsAsync(new[] { blobKey }, cancellationToken).ConfigureAwait(false); + + return true; + } + + /// + public async Task DeleteImageAsync(string image, CancellationToken cancellationToken) + { + ValidateImage(image); + var row = await _context.OciRepositories!.FirstOrDefaultAsync(i => i.Name == image, cancellationToken).ConfigureAwait(false); + if (row == null) return false; + + _gate.ThrowIfClosed(); + + var blobKeys = await _context.OciBlobLinks!.AsNoTracking().Where(l => l.ImageKey == row.Key).Select(l => l.BlobKey).ToListAsync(cancellationToken).ConfigureAwait(false); + var uploads = await _context.OciUploads!.AsNoTracking().Where(u => u.ImageKey == row.Key).Select(u => u.StorageUploadId!).ToListAsync(cancellationToken).ConfigureAwait(false); + + // The manifests, links and sessions go with the image (cascading foreign keys); the tags are removed here, before the image + // (a tag also names the image, which the database must not see deleted while a tag still points at it). + _context.OciTags!.RemoveRange(await _context.OciTags!.Where(t => t.ImageKey == row.Key).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.OciRepositories!.Remove(row); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + await ReleaseBlobsAsync(blobKeys, cancellationToken).ConfigureAwait(false); + foreach (var id in uploads) await TryAbortAsync(id).ConfigureAwait(false); + + return true; + } + + /// + public async Task PruneAsync(string image, CancellationToken cancellationToken) + { + var row = await RequireImageAsync(image, cancellationToken).ConfigureAwait(false); + _gate.ThrowIfClosed(); + + // Like the garbage collector: an image with a push going on keeps its loose layers (they wait for the manifest). + var now = _time.UtcNow; + var uploadCutoff = now - Options.UploadExpiry; + if (await _context.OciUploads!.AsNoTracking().AnyAsync(u => u.ImageKey == row.Key && u.Updated >= uploadCutoff, cancellationToken).ConfigureAwait(false)) + { + return new OciPruneResult(0, 0); + } + + var cutoff = now - Options.PruneGrace; + var candidates = await (from l in _context.OciBlobLinks!.AsNoTracking() + join b in _context.OciBlobs!.AsNoTracking() on l.BlobKey equals b.Key + where l.ImageKey == row.Key && l.Manifests == 0 && l.Created < cutoff + select new { l.Key, l.BlobKey, b.Size }).ToListAsync(cancellationToken).ConfigureAwait(false); + if (candidates.Count == 0) return new OciPruneResult(0, 0); + + // The plan is read again and deleted inside one serializable transaction, with the count in the delete's own condition. + List blobKeys; + long bytes; + int removed; + await using (var transaction = await _context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable, cancellationToken).ConfigureAwait(false)) + { + var candidateKeys = candidates.Select(c => c.Key).ToList(); + var stillLoose = (await _context.OciBlobLinks!.AsNoTracking().Where(l => candidateKeys.Contains(l.Key) && l.Manifests == 0) + .Select(l => l.Key).ToListAsync(cancellationToken).ConfigureAwait(false)).ToHashSet(); + var stale = candidates.Where(c => stillLoose.Contains(c.Key)).ToList(); + var staleKeys = stale.Select(s => s.Key).ToList(); + removed = staleKeys.Count == 0 ? 0 : await _context.OciBlobLinks!.Where(l => staleKeys.Contains(l.Key) && l.Manifests == 0).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + + blobKeys = stale.Select(s => s.BlobKey).ToList(); + bytes = stale.Sum(s => s.Size); + } + + if (removed == 0) return new OciPruneResult(0, 0); + + await ReleaseBlobsAsync(blobKeys, cancellationToken).ConfigureAwait(false); + + return new OciPruneResult(removed, bytes); + } + + // ---- the pages -------------------------------------------------------------------------------------------------- + + /// + public async Task ListImagesAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) + { + IQueryable query = _context.OciRepositories!.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(text)) + { + var needle = text.Trim().ToLowerInvariant(); + query = query.Where(i => i.Name!.Contains(needle)); + } + + var all = await query.OrderBy(i => i.Name).Select(i => new { i.Key, i.Name, i.Modified }).ToListAsync(cancellationToken).ConfigureAwait(false); + + var visible = new List<(int Key, string Name, DateTime Modified)>(); + foreach (var image in all) + { + if (canRead == null || await canRead(image.Name!, cancellationToken).ConfigureAwait(false)) visible.Add((image.Key, image.Name!, image.Modified)); + } + + var page = visible.OrderBy(i => i.Name, StringComparer.Ordinal).Skip(Math.Max(skip, 0)).Take(Math.Clamp(take, 0, 250)).ToList(); + var keys = page.Select(p => p.Key).ToList(); + + var tags = await _context.OciTags!.AsNoTracking().Where(t => keys.Contains(t.ImageKey)).GroupBy(t => t.ImageKey).Select(g => new { Key = g.Key, Count = g.Count() }).ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + var manifests = await _context.OciManifests!.AsNoTracking().Where(m => keys.Contains(m.ImageKey)).GroupBy(m => m.ImageKey).Select(g => new { Key = g.Key, Count = g.Count() }).ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken).ConfigureAwait(false); + var sizes = await (from l in _context.OciBlobLinks!.AsNoTracking() + join b in _context.OciBlobs!.AsNoTracking() on l.BlobKey equals b.Key + where keys.Contains(l.ImageKey) + group b by l.ImageKey into g + select new { Key = g.Key, Size = g.Sum(b => b.Size) }).ToDictionaryAsync(g => g.Key, g => g.Size, cancellationToken).ConfigureAwait(false); + + return new OciImagePage( + visible.Count, + page.Select(p => new OciImageSummary(p.Name, tags.GetValueOrDefault(p.Key), manifests.GetValueOrDefault(p.Key), sizes.GetValueOrDefault(p.Key), Utc(p.Modified))).ToList()); + } + + /// + public async Task GetImageAsync(string image, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image)) return null; + + var row = await FindImageAsync(image, cancellationToken).ConfigureAwait(false); + if (row == null) return null; + + var tagRows = await (from t in _context.OciTags!.AsNoTracking() + join m in _context.OciManifests!.AsNoTracking() on t.ManifestKey equals m.Key + where t.ImageKey == row.Key + select new { t.Name, m.Digest, t.Updated, t.ManifestKey }).ToListAsync(cancellationToken).ConfigureAwait(false); + var manifests = await _context.OciManifests!.AsNoTracking().Where(m => m.ImageKey == row.Key).OrderByDescending(m => m.Created).Take(1000).ToListAsync(cancellationToken).ConfigureAwait(false); + + // The platform of a child is known from the index that lists it. + var platforms = new Dictionary(StringComparer.Ordinal); + var parsedByDigest = new Dictionary(StringComparer.Ordinal); + foreach (var manifest in manifests) + { + var parsed = TryParse(manifest); + parsedByDigest[manifest.Digest!] = parsed; + if (parsed?.IsIndex == true) + { + foreach (var child in parsed.Children) + { + platforms.TryAdd(child.Descriptor.Digest, new OciPlatformInfo(child.Descriptor.Digest, child.Descriptor.MediaType, child.Descriptor.Size, child.Os, child.Architecture, child.Variant, true).Platform); + } + } + } + + var tagsByManifest = tagRows.GroupBy(t => t.ManifestKey).ToDictionary(g => g.Key, g => (IReadOnlyList)g.Select(t => t.Name!).OrderBy(n => n, StringComparer.Ordinal).ToList()); + var summaries = manifests.Select(m => Summarize(m, parsedByDigest[m.Digest!], tagsByManifest.GetValueOrDefault(m.Key) ?? Array.Empty(), platforms.GetValueOrDefault(m.Digest!))).ToList(); + + var size = await (from l in _context.OciBlobLinks!.AsNoTracking() + join b in _context.OciBlobs!.AsNoTracking() on l.BlobKey equals b.Key + where l.ImageKey == row.Key + select (long?)b.Size).SumAsync(cancellationToken).ConfigureAwait(false) ?? 0; + var unreferenced = await _context.OciBlobLinks!.AsNoTracking().CountAsync(l => l.ImageKey == row.Key && l.Manifests == 0, cancellationToken).ConfigureAwait(false); + + return new OciImageInfo( + row.Name!, + Utc(row.Created), + Utc(row.Modified), + tagRows.OrderBy(t => t.Name, StringComparer.Ordinal).Select(t => new OciTagInfo(t.Name!, t.Digest!, Utc(t.Updated))).ToList(), + summaries, + size, + unreferenced); + } + + private static OciParsedManifest? TryParse(OciManifest manifest) + { + try + { + return OciManifestParser.Parse(manifest.MediaType, Encoding.UTF8.GetBytes(manifest.Content!)); + } + catch (OciException) + { + return null; + } + } + + private static OciManifestSummary Summarize(OciManifest manifest, OciParsedManifest? parsed, IReadOnlyList tags, string? platform) + => new( + manifest.Digest!, + manifest.MediaType!, + manifest.Size, + OciNames.IsIndex(manifest.MediaType), + Utc(manifest.Created), + tags, + manifest.ArtifactType, + manifest.SubjectDigest, + platform, + parsed?.Layers.Count ?? 0, + parsed == null ? 0 : parsed.Layers.Sum(l => l.Size) + (parsed.Config?.Size ?? 0)); + + /// + public async Task GetManifestDetailAsync(string image, string digest, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image) || !OciNames.IsValidDigest(digest)) return null; + + var row = await FindImageAsync(image, cancellationToken).ConfigureAwait(false); + if (row == null) return null; + + var manifest = await _context.OciManifests!.AsNoTracking().FirstOrDefaultAsync(m => m.ImageKey == row.Key && m.Digest == digest, cancellationToken).ConfigureAwait(false); + if (manifest == null) return null; + + var parsed = TryParse(manifest); + var tags = await _context.OciTags!.AsNoTracking().Where(t => t.ManifestKey == manifest.Key).Select(t => t.Name!).ToListAsync(cancellationToken).ConfigureAwait(false); + + string? platform = null; + var platforms = new List(); + if (parsed != null && parsed.IsIndex) + { + var present = await _context.OciManifests!.AsNoTracking().Where(m => m.ImageKey == row.Key).Select(m => m.Digest!).ToListAsync(cancellationToken).ConfigureAwait(false); + var set = present.ToHashSet(StringComparer.Ordinal); + platforms.AddRange(parsed.Children.Select(c => new OciPlatformInfo(c.Descriptor.Digest, c.Descriptor.MediaType, c.Descriptor.Size, c.Os, c.Architecture, c.Variant, set.Contains(c.Descriptor.Digest)))); + } + else if (parsed?.Config != null) + { + platform = await ReadPlatformAsync(row.Key, parsed.Config, cancellationToken).ConfigureAwait(false); + } + + string json; + try + { + using var document = JsonDocument.Parse(manifest.Content!); + json = JsonSerializer.Serialize(document.RootElement, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + } + catch (JsonException) + { + json = manifest.Content!; + } + + return new OciManifestDetail( + Summarize(manifest, parsed, tags.OrderBy(t => t, StringComparer.Ordinal).ToList(), platform), + json, + parsed?.Config == null ? null : new OciLayerInfo(parsed.Config.Digest, parsed.Config.Size, parsed.Config.MediaType), + parsed?.Layers.Select(l => new OciLayerInfo(l.Digest, l.Size, l.MediaType)).ToList() ?? new List(), + platforms, + parsed?.Annotations ?? new Dictionary()); + } + + // The config blob of an image manifest says which platform it is for; small, so read whole (bounded). + private async Task ReadPlatformAsync(int imageKey, OciParsedDescriptor config, CancellationToken cancellationToken) + { + if (config.Size is <= 0 or > 1024 * 1024) return null; + + try + { + var blob = await FindHeldBlobAsync(imageKey, config.Digest, cancellationToken).ConfigureAwait(false); + if (blob == null) return null; + + using var stream = await Streaming.GetRangeAsync(BlobPath(config.Digest), 0, blob.Size, cancellationToken).ConfigureAwait(false); + if (stream == null) return null; + + using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); + string? Get(string name) => document.RootElement.ValueKind == JsonValueKind.Object && document.RootElement.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + var parts = new[] { Get("os"), Get("architecture"), Get("variant") }.Where(p => !string.IsNullOrEmpty(p)).ToArray(); + + return parts.Length == 0 ? null : string.Join("/", parts!); + } + catch (Exception e) when (e is JsonException or InvalidOperationException or NotSupportedException or IOException) + { + return null; + } + } +} diff --git a/src/BaGet.Core/Formats/Docker/OciStreams.cs b/src/BaGet.Core/Formats/Docker/OciStreams.cs new file mode 100644 index 000000000..c7b30bd33 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciStreams.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// Small helpers over request bodies. +internal static class OciStreams +{ + /// + /// Null when holds no byte, else a forward-only stream with the same content (the byte looked at is + /// replayed). Lets a registry skip appending an empty chunk, which not every store accepts as a part. + /// + public static async Task NonEmptyAsync(Stream stream, CancellationToken cancellationToken) + { + var first = new byte[1]; + var read = await stream.ReadAsync(first.AsMemory(), cancellationToken).ConfigureAwait(false); + + return read == 0 ? null : new PrefixedStream(first[0], stream); + } + + private sealed class PrefixedStream : Stream + { + private readonly byte _first; + private readonly Stream _rest; + private bool _firstRead; + + public PrefixedStream(byte first, Stream rest) + { + _first = first; + _rest = rest; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + if (buffer.Length == 0) return 0; + + if (!_firstRead) + { + _firstRead = true; + buffer[0] = _first; + + return 1; + } + + return _rest.Read(buffer); + } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (buffer.Length == 0) return new ValueTask(0); + + if (!_firstRead) + { + _firstRead = true; + buffer.Span[0] = _first; + + return new ValueTask(1); + } + + return _rest.ReadAsync(buffer, cancellationToken); + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} diff --git a/src/BaGet.Core/Formats/Docker/OciUpstreamClient.cs b/src/BaGet.Core/Formats/Docker/OciUpstreamClient.cs new file mode 100644 index 000000000..640444a29 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/OciUpstreamClient.cs @@ -0,0 +1,974 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// How asking the upstream of a remote Docker repository ended. +public enum OciUpstreamStatus +{ + /// The upstream answered. + Found, + + /// The upstream does not have it (a real 404, possibly remembered). + NotFound, + + /// Offline mode: the upstream is never contacted. + Offline, + + /// The upstream could not be asked (down, refused the credentials, not a registry) and nothing remembered can answer. + Unavailable, +} + +/// An upstream's answer about a manifest. +/// How it ended. +/// The manifest's digest (computed over the bytes). +/// Its media type. +/// The bytes (a private copy the caller may keep). +/// Whether it is an expired answer served because the upstream could not be reached. +/// What failed, for . +public sealed record OciManifestAnswer(OciUpstreamStatus Status, string? Digest = null, string? MediaType = null, byte[]? Content = null, bool Stale = false, string? Message = null); + +/// An upstream's answer about a blob's size. +/// How it ended. +/// The size in bytes. +/// What failed, for . +public sealed record OciBlobHeadAnswer(OciUpstreamStatus Status, long Size = 0, string? Message = null); + +/// An upstream's tag list. +/// How it ended. +/// The tags (every page the upstream offered, up to a limit). +/// Whether it is an expired list served because the upstream could not be reached. +/// What failed, for . +public sealed record OciTagsAnswer(OciUpstreamStatus Status, IReadOnlyList? Tags = null, bool Stale = false, string? Message = null); + +/// A blob (or a range of one) being downloaded from the upstream; disposing releases the connection. +public sealed class OciUpstreamBlob : IDisposable +{ + private readonly HttpResponseMessage _response; + + internal OciUpstreamBlob(HttpResponseMessage response, Stream content, long totalSize, long offset, long length) + { + _response = response; + Content = content; + TotalSize = totalSize; + Offset = offset; + Length = length; + } + + /// The bytes. + public Stream Content { get; } + + /// The size of the whole blob. + public long TotalSize { get; } + + /// Where the bytes start. + public long Offset { get; } + + /// How many bytes follow. + public long Length { get; } + + /// + public void Dispose() + { + Content.Dispose(); + _response.Dispose(); + } +} + +/// The upstream of a remote Docker repository could not be reached or sent something unusable (the registry answers 502). +public sealed class OciUpstreamException : Exception +{ + /// What failed, safe to show (no URL, header or credential). + public OciUpstreamException(string message) + : base(message) + { + } +} + +/// +/// Asks the upstream registry of the current remote Docker repository () for manifests, blobs and +/// tags, and does the authentication a registry asks for: the first request goes without credentials; a 401 with +/// WWW-Authenticate: Bearer realm="…",service="…",scope="…" sends the client to that realm for a token (HTTP Basic with the +/// configured credentials, or anonymously: Docker Hub hands anonymous pull tokens out), which is remembered per scope until it +/// expires and then sent as the bearer credential; a Basic challenge is answered with the credentials at once, to the registry's own +/// origin. Applies what every remote repository has (): offline mode, the metadata period, +/// the negative period (only a real 404 is remembered as "not found"), an expired answer served when the upstream cannot be +/// reached, the health the status page shows, and Remote:BlockPrivateAddresses (the HTTP client's connect callback; the +/// token service and a redirect go through the same client). +/// +/// +/// Credentials go to the registry's origin and to the realm its challenge names, never to a redirect target on another origin +/// (Docker Hub redirects blobs to a CDN; the CDN is given nothing). A realm on plain http under an https registry is refused (no +/// downgrade). Redirects are followed by hand, at most . +/// Answers are kept in under keys that carry the upstream name after a three-character +/// kind (om: manifest, ob: blob size, ol: tag list), so a purge finds everything about an image by prefix +/// (). +/// +public sealed class OciUpstreamClient +{ + /// The most redirects followed for one request. + public const int MaxRedirects = 5; + + /// The most pages of a tag list read from the upstream. + public const int MaxTagPages = 20; + + /// The most tags kept from one upstream list. + public const int MaxTags = 100000; + + private const int MaxTokenBytes = 1024 * 1024; + private const int MaxTagPageBytes = 16 * 1024 * 1024; + private const int ManifestCacheLimit = 2000; + + private const string ManifestKind = "om:"; + private const string BlobKind = "ob:"; + private const string TagsKind = "ol:"; + + // Docker Hub's "official images" live under library/: `docker pull nginx` asks for library/nginx. + private static readonly string[] DockerHubHosts = { "registry-1.docker.io", "index.docker.io", "registry.hub.docker.com", "docker.io" }; + + private static readonly string AcceptManifests = string.Join( + ", ", + OciNames.IndexTypes.Concat(OciNames.ImageManifestTypes)); + + private readonly IRepositoryContext? _repository; + private readonly IRemoteUpstreamSource _source; + private readonly RemoteRepositoryState _state; + private readonly IRemoteHttpClientFactory _http; + private readonly ILogger _logger; + private readonly Microsoft.Extensions.Options.IOptionsSnapshot? _options; + + public OciUpstreamClient( + IRepositoryContext? repository, + IRemoteUpstreamSource source, + RemoteRepositoryState state, + IRemoteHttpClientFactory http, + ILogger logger, + Microsoft.Extensions.Options.IOptionsSnapshot? options = null) + { + _repository = repository; + _source = source ?? throw new ArgumentNullException(nameof(source)); + _state = state ?? throw new ArgumentNullException(nameof(state)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _options = options; + } + + private int MaxManifestBytes => _options?.Value.MaxManifestBytes ?? new OciOptions().MaxManifestBytes; + + /// The upstream of the request's repository, or null when it has none (not remote, or its settings are not usable). + public Task ResolveAsync(CancellationToken cancellationToken) + => _source.ResolveAsync(_repository?.Current ?? RepositoryInfo.Default, cancellationToken); + + /// + /// Whether a cache key (any kind) is about (a purge drops these). + /// + public static bool ImagePrefix(string cacheKey, string image) + => cacheKey.Length > 3 && cacheKey.AsSpan(3).StartsWith((image + "|").AsSpan(), StringComparison.Ordinal); + + /// + /// The name the upstream knows an image by: the image itself, except at Docker Hub where a single-component name is an official + /// image and lives under library/. + /// + public static string UpstreamName(RemoteRepositorySettings settings, string image) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + var host = settings.UrlOrNull?.IdnHost; + if (host != null && !image.Contains('/') && DockerHubHosts.Contains(host, StringComparer.OrdinalIgnoreCase)) return "library/" + image; + + return image; + } + + // The key of an image's answers: "|" (images never contain '|'). + private static string Key(string kind, string image, string detail) => kind + image + "|" + detail; + + // ---- manifests ------------------------------------------------------------------------------------------------------- + + /// + /// The manifest (a tag or a digest) of , validated (supported type, a + /// document that parses, the digest it claims and, for a digest reference, the digest asked for). + /// + /// The upstream. + /// The image name as clients use it here. + /// A tag or a sha256: digest. + /// + /// The manifest this repository already stores for the reference, if any: when the cached answer has expired the upstream is first + /// asked with HEAD (which Docker Hub does not count as a pull) and, when it names the same digest, + /// is the answer and the document is not downloaded again. + /// + /// A token to cancel the task. + public async Task GetManifestAsync(ResolvedUpstream upstream, string image, string reference, OciManifestContent? known, CancellationToken cancellationToken) + { + var key = upstream.Key; + var settings = upstream.Settings; + var cacheKey = Key(ManifestKind, image, reference); + var cached = _state.TryGet(key, cacheKey, out var value, out var negative, out var fresh); + + if (settings.Offline) + { + if (cached && !negative && value is CachedManifest remembered) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return remembered.ToAnswer(stale: !fresh); + } + + return new OciManifestAnswer(OciUpstreamStatus.Offline); + } + + if (cached && fresh) + { + if (negative) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return new OciManifestAnswer(OciUpstreamStatus.NotFound); + } + + if (value is CachedManifest hit) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return hit.ToAnswer(stale: false); + } + } + + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + var name = UpstreamName(settings, image); + var ttl = TimeSpan.FromSeconds(settings.MetadataTtlSeconds); + + try + { + // A tag the upstream still points at the manifest we hold needs no download. + var heldDigest = (value as CachedManifest)?.Digest ?? known?.Digest; + if (heldDigest != null && !OciNames.LooksLikeDigest(reference)) + { + using var head = await SendAsync(upstream, HttpMethod.Head, ManifestUri(settings, name, reference), AcceptManifests, name, null, cancellationToken).ConfigureAwait(false); + if (head.StatusCode == HttpStatusCode.OK + && head.Headers.TryGetValues(DigestHeader, out var digests) + && string.Equals(digests.FirstOrDefault(), heldDigest, StringComparison.Ordinal)) + { + var current = (value as CachedManifest) + ?? (known == null ? null : new CachedManifest(known.Digest, known.MediaType, known.Content)); + if (current != null) + { + _state.Succeeded(key); + _state.Set(key, cacheKey, current, negative: false, ttl, ManifestCacheLimit); + + return current.ToAnswer(stale: false); + } + } + } + + using var response = await SendAsync(upstream, HttpMethod.Get, ManifestUri(settings, name, reference), AcceptManifests, name, null, cancellationToken).ConfigureAwait(false); + + if (IsAbsent(response.StatusCode)) + { + _state.Succeeded(key); + _state.Set(key, cacheKey, null, negative: true, TimeSpan.FromSeconds(settings.NegativeTtlSeconds), ManifestCacheLimit); + + return new OciManifestAnswer(OciUpstreamStatus.NotFound); + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + byte[] bytes; + await using (var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) + { + bytes = await ReadCappedAsync(response, body, MaxManifestBytes, cancellationToken).ConfigureAwait(false); + } + + var mediaType = response.Content.Headers.ContentType?.MediaType; + var digest = OciNames.DigestOf(StreamingStorage.Sha256Hex(bytes)); + if (OciNames.LooksLikeDigest(reference) && !string.Equals(reference, digest, StringComparison.Ordinal)) + { + throw new InvalidDataException("The manifest the upstream sent does not have the digest asked for."); + } + + if (response.Headers.TryGetValues(DigestHeader, out var claimed) && claimed.FirstOrDefault() is { } claim && !string.Equals(claim, digest, StringComparison.Ordinal)) + { + throw new InvalidDataException("The manifest the upstream sent does not have the digest it announced."); + } + + mediaType = ManifestMediaType(mediaType, bytes); + try + { + OciManifestParser.Parse(mediaType, bytes); + } + catch (OciException e) + { + throw new InvalidDataException("The upstream sent a manifest this registry cannot use: " + e.Message); + } + + var answer = new CachedManifest(digest, mediaType!, bytes); + _state.Succeeded(key); + _state.Set(key, cacheKey, answer, negative: false, ttl, ManifestCacheLimit); + + return answer.ToAnswer(stale: false); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + var what = Fail(upstream, e); + + if (cached && !negative && value is CachedManifest stale) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Stale); + + return stale.ToAnswer(stale: true); + } + + return new OciManifestAnswer(OciUpstreamStatus.Unavailable, Message: what); + } + } + + // A registry names the type in Content-Type; one that sends application/json (or nothing) is read from the document's own mediaType. + private static string? ManifestMediaType(string? header, byte[] content) + { + if (OciNames.IsSupportedManifestType(header)) return header; + + try + { + using var document = JsonDocument.Parse(content, new JsonDocumentOptions { MaxDepth = 32 }); + if (document.RootElement.ValueKind == JsonValueKind.Object + && document.RootElement.TryGetProperty("mediaType", out var declared) + && declared.ValueKind == JsonValueKind.String + && OciNames.IsSupportedManifestType(declared.GetString())) + { + return declared.GetString(); + } + } + catch (JsonException) + { + } + + return header; + } + + private const string DigestHeader = "Docker-Content-Digest"; + + /// + /// Whether the upstream has the manifest (a HEAD; nothing is downloaded, kept or counted as a pull): the resolution preview. + /// + public async Task ProbeManifestAsync(ResolvedUpstream upstream, string image, string reference, CancellationToken cancellationToken) + { + if (upstream.Settings.Offline) return OciUpstreamStatus.Offline; + + var name = UpstreamName(upstream.Settings, image); + try + { + using var response = await SendAsync(upstream, HttpMethod.Head, ManifestUri(upstream.Settings, name, reference), AcceptManifests, name, null, cancellationToken).ConfigureAwait(false); + if (IsAbsent(response.StatusCode)) return OciUpstreamStatus.NotFound; + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + _state.Succeeded(upstream.Key); + + return OciUpstreamStatus.Found; + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + Fail(upstream, e); + + return OciUpstreamStatus.Unavailable; + } + } + + // ---- blobs ----------------------------------------------------------------------------------------------------------- + + /// The size of a blob the upstream holds for (a HEAD), remembered for the metadata period. + public async Task HeadBlobAsync(ResolvedUpstream upstream, string image, string digest, CancellationToken cancellationToken) + { + var key = upstream.Key; + var settings = upstream.Settings; + var cacheKey = Key(BlobKind, image, digest); + var cached = _state.TryGet(key, cacheKey, out var value, out var negative, out var fresh); + + if (settings.Offline) + { + return cached && !negative && value is long size + ? new OciBlobHeadAnswer(OciUpstreamStatus.Found, size) + : new OciBlobHeadAnswer(OciUpstreamStatus.Offline); + } + + if (cached && fresh) + { + if (negative) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return new OciBlobHeadAnswer(OciUpstreamStatus.NotFound); + } + + if (value is long hit) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return new OciBlobHeadAnswer(OciUpstreamStatus.Found, hit); + } + } + + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + var name = UpstreamName(settings, image); + + try + { + using var response = await SendAsync(upstream, HttpMethod.Head, BlobUri(settings, name, digest), "*/*", name, null, cancellationToken).ConfigureAwait(false); + + if (IsAbsent(response.StatusCode)) + { + _state.Succeeded(key); + _state.Set(key, cacheKey, null, negative: true, TimeSpan.FromSeconds(settings.NegativeTtlSeconds), ManifestCacheLimit); + + return new OciBlobHeadAnswer(OciUpstreamStatus.NotFound); + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + var length = response.Content.Headers.ContentLength ?? throw new InvalidDataException("The upstream did not announce the size of the blob."); + _state.Succeeded(key); + _state.Set(key, cacheKey, length, negative: false, TimeSpan.FromSeconds(settings.MetadataTtlSeconds), ManifestCacheLimit); + + return new OciBlobHeadAnswer(OciUpstreamStatus.Found, length); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + var what = Fail(upstream, e); + + return cached && !negative && value is long stale + ? new OciBlobHeadAnswer(OciUpstreamStatus.Found, stale) + : new OciBlobHeadAnswer(OciUpstreamStatus.Unavailable, Message: what); + } + } + + /// + /// Downloads a blob (or, with , the bytes from there to inclusive, or the + /// end); null when the upstream says 404 (remembered for the negative period). + /// + /// The upstream could not be reached or refused. + public async Task OpenBlobAsync(ResolvedUpstream upstream, string image, string digest, long? rangeStart, long? rangeEnd, CancellationToken cancellationToken) + { + var key = upstream.Key; + var settings = upstream.Settings; + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + var name = UpstreamName(settings, image); + + HttpResponseMessage? response = null; + try + { + string? range = rangeStart == null ? null : $"bytes={rangeStart.Value}-{(rangeEnd == null ? string.Empty : rangeEnd.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))}"; + response = await SendAsync(upstream, HttpMethod.Get, BlobUri(settings, name, digest), "*/*", name, range, cancellationToken).ConfigureAwait(false); + + if (IsAbsent(response.StatusCode)) + { + _state.Succeeded(key); + _state.Set(key, Key(BlobKind, image, digest), null, negative: true, TimeSpan.FromSeconds(settings.NegativeTtlSeconds), ManifestCacheLimit); + response.Dispose(); + + return null; + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + long total; + long offset = 0; + long length; + if (response.StatusCode == HttpStatusCode.PartialContent && response.Content.Headers.ContentRange is { } contentRange) + { + offset = contentRange.From ?? 0; + length = response.Content.Headers.ContentLength ?? ((contentRange.To ?? 0) - offset + 1); + total = contentRange.Length ?? throw new InvalidDataException("The upstream did not announce the size of the blob."); + } + else + { + // A server that ignores Range sends the whole blob; the caller skips what it does not want. + total = length = response.Content.Headers.ContentLength ?? throw new InvalidDataException("The upstream did not announce the size of the blob."); + } + + var content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + _state.Succeeded(key); + + return new OciUpstreamBlob(response, content, total, offset, length); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + response?.Dispose(); + + throw new OciUpstreamException(Fail(upstream, e)); + } + } + + // ---- tags ------------------------------------------------------------------------------------------------------------ + + /// The tags of at the upstream (all pages, up to a limit), remembered for the metadata period. + public async Task ListTagsAsync(ResolvedUpstream upstream, string image, CancellationToken cancellationToken) + { + var key = upstream.Key; + var settings = upstream.Settings; + var cacheKey = Key(TagsKind, image, "all"); + var cached = _state.TryGet(key, cacheKey, out var value, out var negative, out var fresh); + + if (settings.Offline) + { + return cached && !negative && value is IReadOnlyList remembered + ? new OciTagsAnswer(OciUpstreamStatus.Found, remembered, Stale: !fresh) + : new OciTagsAnswer(OciUpstreamStatus.Offline); + } + + if (cached && fresh) + { + if (negative) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return new OciTagsAnswer(OciUpstreamStatus.NotFound); + } + + if (value is IReadOnlyList hit) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return new OciTagsAnswer(OciUpstreamStatus.Found, hit); + } + } + + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + var name = UpstreamName(settings, image); + + try + { + var tags = new List(); + var next = new Uri(RegistryBase(settings) + "v2/" + name + "/tags/list"); + for (var page = 0; next != null && page < MaxTagPages; page++) + { + using var response = await SendAsync(upstream, HttpMethod.Get, next, "application/json", name, null, cancellationToken).ConfigureAwait(false); + + if (IsAbsent(response.StatusCode)) + { + if (page > 0) break; + + _state.Succeeded(key); + _state.Set(key, cacheKey, null, negative: true, TimeSpan.FromSeconds(settings.NegativeTtlSeconds), ManifestCacheLimit); + + return new OciTagsAnswer(OciUpstreamStatus.NotFound); + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + byte[] bytes; + await using (var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) + { + bytes = await ReadCappedAsync(response, body, MaxTagPageBytes, cancellationToken).ConfigureAwait(false); + } + + try + { + using var document = JsonDocument.Parse(bytes); + if (document.RootElement.TryGetProperty("tags", out var list) && list.ValueKind == JsonValueKind.Array) + { + foreach (var tag in list.EnumerateArray()) + { + if (tag.ValueKind == JsonValueKind.String && OciNames.IsValidTag(tag.GetString()) && tags.Count < MaxTags) tags.Add(tag.GetString()!); + } + } + else if (!document.RootElement.TryGetProperty("tags", out _)) + { + throw new InvalidDataException("The upstream did not send a tag list."); + } + } + catch (JsonException) + { + throw new InvalidDataException("The upstream did not send a tag list."); + } + + next = NextLink(response, new Uri(RegistryBase(settings))); + } + + var ordered = (IReadOnlyList)tags.Distinct(StringComparer.Ordinal).OrderBy(t => t, StringComparer.Ordinal).ToList(); + _state.Succeeded(key); + _state.Set(key, cacheKey, ordered, negative: false, TimeSpan.FromSeconds(settings.MetadataTtlSeconds), ManifestCacheLimit); + + return new OciTagsAnswer(OciUpstreamStatus.Found, ordered); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + var what = Fail(upstream, e); + + return cached && !negative && value is IReadOnlyList stale + ? new OciTagsAnswer(OciUpstreamStatus.Found, stale, Stale: true) + : new OciTagsAnswer(OciUpstreamStatus.Unavailable, Message: what); + } + } + + // The next page of a list: the Link header's rel="next" target, on the registry's own origin only. + private static Uri? NextLink(HttpResponseMessage response, Uri origin) + { + if (!response.Headers.TryGetValues("Link", out var links)) return null; + + foreach (var link in links.SelectMany(l => l.Split(','))) + { + if (!link.Contains("rel=\"next\"", StringComparison.OrdinalIgnoreCase) && !link.Contains("rel=next", StringComparison.OrdinalIgnoreCase)) continue; + + var start = link.IndexOf('<'); + var end = link.IndexOf('>'); + if (start < 0 || end < start) continue; + + if (Uri.TryCreate(origin, link.Substring(start + 1, end - start - 1), out var next) && SameOrigin(origin, next)) return next; + } + + return null; + } + + // ---- probing --------------------------------------------------------------------------------------------------------- + + /// + /// Whether the upstream answers the version check (GET /v2/) once authenticated: the check Test connection runs. Throws + /// what a failed request throws. + /// + /// The status of the final answer. + public async Task PingAsync(ResolvedUpstream upstream, CancellationToken cancellationToken) + { + using var response = await SendAsync(upstream, HttpMethod.Get, new Uri(RegistryBase(upstream.Settings) + "v2/"), "application/json", repository: null, range: null, cancellationToken).ConfigureAwait(false); + + return response.StatusCode; + } + + /// Records that what the upstream sent was not what it announced. + public string Rejected(ResolvedUpstream upstream, string what) + { + _state.Failed(upstream.Key, what); + _logger.LogWarning("The upstream of repository {Repository} sent something unusable: {Error}", upstream.Name, what); + + return what; + } + + /// Records that the upstream answered. + internal void Reached(ResolvedUpstream upstream) => _state.Succeeded(upstream.Key); + + /// + /// Whether a remembered answer is about (or, with a reference, only that manifest, the tag lists and the + /// answers about blobs would not change): what a purge drops. + /// + public static bool MatchesImage(string cacheKey, string image, string? reference) + => ImagePrefix(cacheKey, image) + && (reference == null || cacheKey.StartsWith(TagsKind, StringComparison.Ordinal) || cacheKey == Key(ManifestKind, image, reference)); + + /// Drops the remembered answers about (or, with a reference, only that manifest's and the tag list's). + public int Forget(ResolvedUpstream upstream, string image, string? reference = null) + => _state.ClearMatching(upstream.Key, key => MatchesImage(key, image, reference)); + + // ---- plumbing -------------------------------------------------------------------------------------------------------- + + /// The registry's address with a trailing slash and without a trailing /v2 (both ways of writing it work). + public static string RegistryBase(RemoteRepositorySettings settings) + { + var text = settings.UrlOrNull!.GetLeftPart(UriPartial.Path).TrimEnd('/'); + if (text.EndsWith("/v2", StringComparison.OrdinalIgnoreCase)) text = text.Substring(0, text.Length - 3); + + return text + "/"; + } + + private static Uri ManifestUri(RemoteRepositorySettings settings, string name, string reference) + => new(RegistryBase(settings) + "v2/" + name + "/manifests/" + reference); + + private static Uri BlobUri(RemoteRepositorySettings settings, string name, string digest) + => new(RegistryBase(settings) + "v2/" + name + "/blobs/" + digest); + + private static bool SameOrigin(Uri a, Uri b) + => string.Equals(a.GetLeftPart(UriPartial.Authority), b.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); + + private UpstreamTransport TransportOf(ResolvedUpstream upstream) + => _state.GetTransport( + upstream.Key, + upstream.Settings, + () => new UpstreamTransport(upstream.Settings.TransportKey(), _http.CreateProbe(upstream.Settings), null)); + + /// + /// Sends one request with the authentication the upstream asks for and follows redirects by hand (the credential stays on the + /// registry's origin). The response is returned unread. + /// + private async Task SendAsync( + ResolvedUpstream upstream, + HttpMethod method, + Uri uri, + string accept, + string? repository, + string? range, + CancellationToken cancellationToken) + { + var settings = upstream.Settings; + var transport = TransportOf(upstream); + var origin = settings.UrlOrNull!; + var scopeKey = repository == null ? "*" : "repository:" + repository + ":pull"; + + AuthenticationHeaderValue? authorization = null; + if (transport.Tokens.TryGetValue(scopeKey, out var token) && token.ExpiresUtc > _state.UtcNow) + { + authorization = new AuthenticationHeaderValue("Bearer", token.Value); + } + else if (settings.HasCredentials && string.IsNullOrEmpty(settings.Username) && !string.IsNullOrEmpty(settings.Password)) + { + // A password with no user name is a ready-made bearer token for the registry itself. + authorization = new AuthenticationHeaderValue("Bearer", settings.Password); + } + else if (transport.BasicChallenged && settings.HasCredentials) + { + authorization = BasicHeader(settings); + } + + for (var attempt = 0; ; attempt++) + { + var (response, answeredBy) = await SendFollowingRedirectsAsync(transport, method, uri, accept, range, authorization, origin, cancellationToken).ConfigureAwait(false); + if (response.StatusCode != HttpStatusCode.Unauthorized || attempt >= 1) return response; + + // A challenge is answered only when it came from the registry's own origin. A 401 from where a redirect led (a CDN, an + // object store) names a realm that host chose: the credentials must not go there. The caller sees a plain 401 (an absence). + if (!SameOrigin(answeredBy, origin)) return response; + + var challenges = response.Headers.WwwAuthenticate; + var bearer = challenges.FirstOrDefault(c => string.Equals(c.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase)); + var basic = challenges.FirstOrDefault(c => string.Equals(c.Scheme, "Basic", StringComparison.OrdinalIgnoreCase)); + + if (bearer != null && !string.IsNullOrEmpty(bearer.Parameter)) + { + var parameters = ParseChallenge(bearer.Parameter); + response.Dispose(); + + var scope = parameters.GetValueOrDefault("scope") ?? (repository == null ? null : "repository:" + repository + ":pull"); + var fetched = await FetchTokenAsync(transport, settings, parameters, scope, cancellationToken).ConfigureAwait(false); + transport.Tokens[scopeKey] = fetched; + authorization = new AuthenticationHeaderValue("Bearer", fetched.Value); + + continue; + } + + if (basic != null && settings.HasCredentials && !string.IsNullOrEmpty(settings.Username)) + { + response.Dispose(); + transport.BasicChallenged = true; + authorization = BasicHeader(settings); + + continue; + } + + return response; + } + } + + // The response and the address that answered it (the last hop of the redirects). + private async Task<(HttpResponseMessage Response, Uri AnsweredBy)> SendFollowingRedirectsAsync( + UpstreamTransport transport, + HttpMethod method, + Uri uri, + string accept, + string? range, + AuthenticationHeaderValue? authorization, + Uri origin, + CancellationToken cancellationToken) + { + var current = uri; + for (var hops = 0; ; hops++) + { + using var request = new HttpRequestMessage(method, current); + request.Headers.TryAddWithoutValidation("Accept", accept); + if (range != null) request.Headers.TryAddWithoutValidation("Range", range); + + // The credential goes to the registry's own origin only: a redirect (Docker Hub sends blobs to a CDN) is given none. + if (authorization != null && SameOrigin(current, origin)) request.Headers.Authorization = authorization; + + var response = await transport.Http!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (!IsRedirect(response.StatusCode) || response.Headers.Location == null) return (response, current); + + var next = new Uri(current, response.Headers.Location); + response.Dispose(); + if (hops >= MaxRedirects) throw new InvalidDataException("The upstream redirected too many times."); + if (next.Scheme != Uri.UriSchemeHttp && next.Scheme != Uri.UriSchemeHttps) throw new InvalidDataException("The upstream redirected to an address that is not http or https."); + if (current.Scheme == Uri.UriSchemeHttps && next.Scheme == Uri.UriSchemeHttp) throw new InvalidDataException("The upstream redirected from https to http."); + + current = next; + } + } + + // The upstream has no such thing for this caller: a 404, or a 401/403 even after the token service gave a token (Docker Hub answers + // an image that does not exist, or that is private, like that). A refusal of the credentials themselves is the token service's. + private static bool IsAbsent(HttpStatusCode status) => status is HttpStatusCode.NotFound or HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden; + + private static bool IsRedirect(HttpStatusCode status) + => status is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; + + private static AuthenticationHeaderValue BasicHeader(RemoteRepositorySettings settings) + => new("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes((settings.Username ?? string.Empty) + ":" + (settings.Password ?? string.Empty)))); + + // `Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:library/nginx:pull"` + internal static Dictionary ParseChallenge(string parameter) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + var i = 0; + while (i < parameter.Length) + { + while (i < parameter.Length && (parameter[i] == ' ' || parameter[i] == ',')) i++; + var equals = parameter.IndexOf('=', i); + if (equals < 0) break; + + var name = parameter.Substring(i, equals - i).Trim(); + i = equals + 1; + string value; + if (i < parameter.Length && parameter[i] == '"') + { + i++; + var builder = new StringBuilder(); + while (i < parameter.Length && parameter[i] != '"') + { + if (parameter[i] == '\\' && i + 1 < parameter.Length) i++; + builder.Append(parameter[i]); + i++; + } + + i++; + value = builder.ToString(); + } + else + { + var end = parameter.IndexOf(',', i); + if (end < 0) end = parameter.Length; + value = parameter.Substring(i, end - i).Trim(); + i = end; + } + + if (name.Length > 0) result[name] = value; + } + + return result; + } + + // Asks the realm named in the challenge for a token: the credentials as HTTP Basic when configured, else anonymously. + private async Task FetchTokenAsync( + UpstreamTransport transport, + RemoteRepositorySettings settings, + Dictionary challenge, + string? scope, + CancellationToken cancellationToken) + { + if (!challenge.TryGetValue("realm", out var realmText) || !Uri.TryCreate(realmText, UriKind.Absolute, out var realm) + || (realm.Scheme != Uri.UriSchemeHttp && realm.Scheme != Uri.UriSchemeHttps)) + { + throw new InvalidDataException("The upstream's authentication challenge names no usable token service."); + } + + if (settings.UrlOrNull!.Scheme == Uri.UriSchemeHttps && realm.Scheme != Uri.UriSchemeHttps) + { + throw new InvalidDataException("The upstream's token service is not on https although the registry is."); + } + + var query = new StringBuilder(); + void Add(string name, string? value) + { + if (string.IsNullOrEmpty(value)) return; + + query.Append(query.Length == 0 ? string.Empty : "&").Append(Uri.EscapeDataString(name)).Append('=').Append(Uri.EscapeDataString(value)); + } + + Add("service", challenge.GetValueOrDefault("service")); + Add("scope", scope); + if (!string.IsNullOrEmpty(settings.Username)) Add("account", settings.Username); + + var builder = new UriBuilder(realm); + builder.Query = string.IsNullOrEmpty(realm.Query) ? query.ToString() : realm.Query.TrimStart('?') + (query.Length == 0 ? string.Empty : "&" + query); + + // The realm may be another host than the registry (Docker Hub: auth.docker.io); only the credentials of this repository go there. + using var request = new HttpRequestMessage(HttpMethod.Get, builder.Uri); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + if (settings.HasCredentials && !string.IsNullOrEmpty(settings.Username)) request.Headers.Authorization = BasicHeader(settings); + + using var response = await transport.Http!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + throw new InvalidDataException(settings.HasCredentials + ? "The upstream's token service refused the credentials." + : "The upstream's token service wants credentials."); + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + byte[] bytes; + await using (var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) + { + bytes = await ReadCappedAsync(response, body, MaxTokenBytes, cancellationToken).ConfigureAwait(false); + } + + try + { + using var document = JsonDocument.Parse(bytes); + var root = document.RootElement; + string? value = null; + if (root.ValueKind == JsonValueKind.Object) + { + if (root.TryGetProperty("token", out var token) && token.ValueKind == JsonValueKind.String) value = token.GetString(); + if (string.IsNullOrEmpty(value) && root.TryGetProperty("access_token", out var access) && access.ValueKind == JsonValueKind.String) value = access.GetString(); + } + + if (string.IsNullOrEmpty(value)) throw new InvalidDataException("The upstream's token service sent no token."); + + var seconds = 60; + if (root.TryGetProperty("expires_in", out var expires) && expires.ValueKind == JsonValueKind.Number && expires.TryGetInt32(out var parsed)) seconds = parsed; + + // Renewed a little early; a token that claims to live under a few seconds is used for one request at least. + var life = TimeSpan.FromSeconds(Math.Clamp(seconds - 10, 5, 3600)); + + return new UpstreamToken(value!, _state.UtcNow + life); + } + catch (JsonException) + { + throw new InvalidDataException("The upstream's token service did not send a token."); + } + } + + private static async Task ReadCappedAsync(HttpResponseMessage response, Stream body, long limit, CancellationToken cancellationToken) + { + if (response.Content.Headers.ContentLength > limit) throw new InvalidDataException("The answer is too large."); + + using var buffer = new MemoryStream(); + var chunk = new byte[16 * 1024]; + int read; + while ((read = await body.ReadAsync(chunk, cancellationToken).ConfigureAwait(false)) > 0) + { + if (buffer.Length + read > limit) throw new InvalidDataException("The answer is larger than " + limit + " bytes."); + + buffer.Write(chunk, 0, read); + } + + return buffer.ToArray(); + } + + private string Fail(ResolvedUpstream upstream, Exception e) + { + // A refusal this client raised itself already says what it is; anything else is described by type, never by message + // (an HTTP exception's message can carry the URL). + var what = e is InvalidDataException ? e.Message : RemoteUpstreamClient.Describe(e); + if (e is HttpRequestException { StatusCode: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } http) + { + what = $"The upstream refused access (HTTP {(int)http.StatusCode}); check the credentials and that the image exists."; + } + + _state.Failed(upstream.Key, what); + + // The exception itself is not logged: its message can carry the upstream's URL with a query string. + _logger.LogWarning("The upstream of repository {Repository} could not be used: {Error}", upstream.Name, what); + + return what; + } + + private sealed record CachedManifest(string Digest, string MediaType, byte[] Content) + { + public OciManifestAnswer ToAnswer(bool stale) => new(OciUpstreamStatus.Found, Digest, MediaType, (byte[])Content.Clone(), stale); + } +} diff --git a/src/BaGet.Core/Formats/Docker/RemoteOciRegistry.cs b/src/BaGet.Core/Formats/Docker/RemoteOciRegistry.cs new file mode 100644 index 000000000..ce268d596 --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/RemoteOciRegistry.cs @@ -0,0 +1,729 @@ +using System; +using System.Buffers; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// of a Docker repository: a pull-through cache of an upstream +/// registry (Docker Hub, GHCR, Quay, another BaGet, Artifactory, Harbor, a registry:2…). +/// +/// +/// Manifests. A digest the repository stores is served from there (it never changes). A tag is asked of the upstream +/// (: authentication, the metadata period, 404s for the negative period, an expired answer when the +/// upstream is down, nothing in offline mode; an expired tag is first checked with HEAD, which Docker Hub does not count as a +/// pull) and, with , kept with its tag so it is served locally from then on, also +/// while the upstream is down. The layers a manifest names are not fetched with it. +/// Blobs. A blob the image holds is served from storage. Otherwise it is streamed from the upstream while it is +/// written to storage (a client is not kept waiting for a multi-gigabyte layer to arrive first), and kept once its digest checks: +/// a download that does not have the digest it was asked for is neither kept nor allowed to complete. A layer that another image of +/// this repository already stores is linked to the image once the upstream confirms (HEAD) that the image has it too, so a base +/// layer is downloaded once. A range request, a download already running for the same digest and a read-only server pass through +/// without being kept. Without StoreLocally everything passes through. +/// Tags are the upstream's plus the stored ones. Referrers, pages and search cover what is stored. Writes (pushes, +/// deletes) are refused: a remote repository takes no changes. Docker Hub's official images are asked for under library/. +/// +public sealed class RemoteOciRegistry : IOciRegistry +{ + private const string NoChanges = "This repository caches an upstream registry and takes no pushes or deletes."; + + // The blobs being downloaded and kept right now ("repository:digest"): a second request for the same one passes through. + private static readonly ConcurrentDictionary Caching = new(); + + private readonly OciRegistryService _local; + private readonly OciUpstreamClient _upstream; + private readonly IRepositoryContext _repository; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + + public RemoteOciRegistry(OciRegistryService local, OciUpstreamClient upstream, IRepositoryContext repository, MaintenanceGate gate, ILogger logger) + { + _local = local ?? throw new ArgumentNullException(nameof(local)); + _upstream = upstream ?? throw new ArgumentNullException(nameof(upstream)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private static OciException Refused() => new(OciErrorCode.Denied, NoChanges); + + // The stored copy of something that may not exist yet: an unknown image is "nothing stored", not an error. + private static async Task StoredAsync(Func> read) + where T : class + { + try + { + return await read().ConfigureAwait(false); + } + catch (OciException e) when (e.Code == OciErrorCode.NameUnknown) + { + return null; + } + } + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + public async Task ImageExistsAsync(string image, CancellationToken cancellationToken) + { + if (await _local.ImageExistsAsync(image, cancellationToken).ConfigureAwait(false)) return true; + if (!OciNames.IsValidImage(image)) return false; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return false; + + var tags = await _upstream.ListTagsAsync(upstream, image, cancellationToken).ConfigureAwait(false); + + return tags.Status == OciUpstreamStatus.Found; + } + + /// + public async Task GetBlobInfoAsync(string image, string digest, CancellationToken cancellationToken) + { + if (!OciNames.IsValidDigest(digest) || !OciNames.IsValidImage(image)) return await _local.GetBlobInfoAsync(image, digest, cancellationToken).ConfigureAwait(false); + + var stored = await StoredAsync(() => _local.GetBlobInfoAsync(image, digest, cancellationToken)).ConfigureAwait(false); + if (stored != null) return stored; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return null; + + var head = await _upstream.HeadBlobAsync(upstream, image, digest, cancellationToken).ConfigureAwait(false); + switch (head.Status) + { + case OciUpstreamStatus.Found: + // A layer this repository stores for another image is this image's too, now that the upstream says so. + if (upstream.Settings.StoreLocally && !_gate.IsClosed && await _local.LinkRepositoryBlobAsync(image, digest, cancellationToken).ConfigureAwait(false)) + { + return await StoredAsync(() => _local.GetBlobInfoAsync(image, digest, cancellationToken)).ConfigureAwait(false) ?? new OciBlobInfo(digest, head.Size); + } + + return new OciBlobInfo(digest, head.Size); + + case OciUpstreamStatus.Unavailable: + throw new OciException(OciErrorCode.UpstreamUnavailable, head.Message ?? "The upstream registry could not be reached."); + + default: + return null; + } + } + + /// + public async Task OpenBlobAsync(string image, string digest, long offset, long? length, CancellationToken cancellationToken) + { + if (!OciNames.IsValidDigest(digest) || !OciNames.IsValidImage(image)) return await _local.OpenBlobAsync(image, digest, offset, length, cancellationToken).ConfigureAwait(false); + + var stored = await StoredAsync(() => _local.OpenBlobAsync(image, digest, offset, length, cancellationToken)).ConfigureAwait(false); + if (stored != null) return stored; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null || upstream.Settings.Offline) return null; + + var settings = upstream.Settings; + var head = await _upstream.HeadBlobAsync(upstream, image, digest, cancellationToken).ConfigureAwait(false); + if (head.Status == OciUpstreamStatus.Unavailable) throw new OciException(OciErrorCode.UpstreamUnavailable, head.Message ?? "The upstream registry could not be reached."); + if (head.Status != OciUpstreamStatus.Found) return null; + + var whole = offset == 0 && (length == null || length.Value == head.Size); + if (settings.StoreLocally && !_gate.IsClosed) + { + // Stored for another image and the upstream confirmed this one has it: served from here. + if (await _local.LinkRepositoryBlobAsync(image, digest, cancellationToken).ConfigureAwait(false)) + { + var linked = await StoredAsync(() => _local.OpenBlobAsync(image, digest, offset, length, cancellationToken)).ConfigureAwait(false); + if (linked != null) return linked; + } + + if (whole) return await CacheWhileStreamingAsync(upstream, image, digest, cancellationToken).ConfigureAwait(false); + } + + return await PassThroughAsync(upstream, image, digest, offset, length, head.Size, cancellationToken).ConfigureAwait(false); + } + + private async Task PassThroughAsync(ResolvedUpstream upstream, string image, string digest, long offset, long? length, long size, CancellationToken cancellationToken) + { + if (offset > size) throw new ArgumentOutOfRangeException(nameof(offset)); + + var count = Math.Min(length ?? size - offset, size - offset); + var whole = offset == 0 && count == size; + + OciUpstreamBlob? blob; + try + { + blob = await _upstream.OpenBlobAsync(upstream, image, digest, whole ? null : offset, whole ? null : offset + count - 1, cancellationToken).ConfigureAwait(false); + } + catch (OciUpstreamException e) + { + throw new OciException(OciErrorCode.UpstreamUnavailable, e.Message); + } + + if (blob == null) return null; + + try + { + // A server that ignores Range sends everything from the start: skip to the part wanted. + if (blob.Offset < offset) await SkipAsync(blob.Content, offset - blob.Offset, cancellationToken).ConfigureAwait(false); + + return new OciBlobContent(new LimitedStream(blob, count), digest, blob.TotalSize, offset, count); + } + catch + { + blob.Dispose(); + + throw; + } + } + + private static async Task SkipAsync(Stream stream, long bytes, CancellationToken cancellationToken) + { + var buffer = ArrayPool.Shared.Rent(81920); + try + { + while (bytes > 0) + { + var read = await stream.ReadAsync(buffer.AsMemory(0, (int)Math.Min(buffer.Length, bytes)), cancellationToken).ConfigureAwait(false); + if (read == 0) throw new IOException("The upstream ended before the requested range."); + + bytes -= read; + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + // Streams the blob to the client while writing it to storage; the blob is kept when the last byte arrives and the digest checks. + private async Task CacheWhileStreamingAsync(ResolvedUpstream upstream, string image, string digest, CancellationToken cancellationToken) + { + var key = _repository.Current.Key + ":" + digest; + if (!Caching.TryAdd(key, 0)) + { + // Another request is downloading it right now: this one reads from the upstream without keeping. + var size = (await _upstream.HeadBlobAsync(upstream, image, digest, cancellationToken).ConfigureAwait(false)).Size; + + return await PassThroughAsync(upstream, image, digest, 0, null, size, cancellationToken).ConfigureAwait(false); + } + + OciUpstreamBlob? blob = null; + OciBlobCacheWriter? writer = null; + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.MirrorFetch); + activity?.SetTag(BaGetDiagnostics.Tags.PackageId, image); + activity?.SetTag(BaGetDiagnostics.Tags.PackageVersion, digest); + try + { + try + { + blob = await _upstream.OpenBlobAsync(upstream, image, digest, null, null, cancellationToken).ConfigureAwait(false); + activity?.SetTag(BaGetDiagnostics.Tags.Result, blob == null ? "NotFound" : "Streaming"); + } + catch (OciUpstreamException e) + { + BaGetDiagnostics.Fail(activity, e); + + throw new OciException(OciErrorCode.UpstreamUnavailable, e.Message); + } + + if (blob == null) + { + Caching.TryRemove(key, out _); + + return null; + } + + try + { + writer = await _local.BeginBlobCacheAsync(image, digest, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + // A store that cannot take the blob must not stop the pull: it passes through. + _logger.LogWarning(e, "Could not start caching blob {Digest} in repository {Repository}", digest, _repository.Current.Name); + } + + var stream = new CachingStream(blob, writer, digest, () => Caching.TryRemove(key, out _), _upstream, upstream, _logger); + + return new OciBlobContent(stream, digest, blob.TotalSize, 0, blob.Length); + } + catch + { + if (writer != null) await writer.DisposeAsync().ConfigureAwait(false); + blob?.Dispose(); + Caching.TryRemove(key, out _); + + throw; + } + } + + /// + public async Task GetManifestAsync(string image, string reference, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image)) return await _local.GetManifestAsync(image, reference, cancellationToken).ConfigureAwait(false); + + var isDigest = OciNames.LooksLikeDigest(reference); + if (isDigest ? !OciNames.IsValidDigest(reference) : !OciNames.IsValidTag(reference)) return null; + + var stored = await _local.FindManifestAsync(image, reference, cancellationToken).ConfigureAwait(false); + + // A digest never changes: what is stored is the answer. + if (isDigest && stored != null) return stored; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return stored; + + // The span of a fetch from the upstream (as a NuGet mirror fetch has): image and reference, never a URL or a credential. + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.MirrorFetch); + activity?.SetTag(BaGetDiagnostics.Tags.PackageId, image); + activity?.SetTag(BaGetDiagnostics.Tags.PackageVersion, reference); + + var answer = await _upstream.GetManifestAsync(upstream, image, reference, stored, cancellationToken).ConfigureAwait(false); + activity?.SetTag(BaGetDiagnostics.Tags.Result, answer.Status.ToString()); + switch (answer.Status) + { + case OciUpstreamStatus.Found: + if (stored != null && string.Equals(stored.Digest, answer.Digest, StringComparison.Ordinal)) return stored; + + return await KeepAsync(upstream, image, isDigest ? null : reference, answer, cancellationToken).ConfigureAwait(false); + + case OciUpstreamStatus.Unavailable: + // What was cached before keeps being served while the upstream is down. + if (stored != null) return stored; + + throw new OciException(OciErrorCode.UpstreamUnavailable, answer.Message ?? "The upstream registry could not be reached."); + + default: + // 404 or offline: a copy kept earlier stays available, as in any caching repository. + return stored; + } + } + + private async Task KeepAsync(ResolvedUpstream upstream, string image, string? tag, OciManifestAnswer answer, CancellationToken cancellationToken) + { + var content = answer.Content!; + if (upstream.Settings.StoreLocally && !_gate.IsClosed) + { + try + { + await _local.StoreCachedManifestAsync(image, tag, answer.MediaType!, content, cancellationToken).ConfigureAwait(false); + var kept = await _local.FindManifestAsync(image, tag ?? answer.Digest!, cancellationToken).ConfigureAwait(false); + if (kept != null) return kept; + } + catch (OciException e) + { + // A document this registry cannot store (the upstream's, validated already) is still served as it came. + _logger.LogWarning("Manifest {Digest} of {Image} was not kept in repository {Repository}: {Reason}", answer.Digest, image, _repository.Current.Name, e.Message); + } + catch (MaintenanceException) + { + // Read-only while a database copy runs: serve without keeping. + } + } + + string? subject = null; + string? artifactType = null; + try + { + var parsed = OciManifestParser.Parse(answer.MediaType, content); + subject = parsed.Subject?.Digest; + artifactType = parsed.ArtifactType; + } + catch (OciException) + { + } + + return new OciManifestContent(answer.Digest!, answer.MediaType!, content, subject, artifactType, DateTime.UtcNow); + } + + /// + public async Task ListTagsAsync(string image, int? count, string? last, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image)) return await _local.ListTagsAsync(image, count, last, cancellationToken).ConfigureAwait(false); + + var stored = await _local.ListTagsAsync(image, null, null, cancellationToken).ConfigureAwait(false); + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + + IReadOnlyList? names = stored?.Tags; + if (upstream != null) + { + var answer = await _upstream.ListTagsAsync(upstream, image, cancellationToken).ConfigureAwait(false); + if (answer.Status == OciUpstreamStatus.Found) + { + names = answer.Tags!.Concat(stored?.Tags ?? Array.Empty()).Distinct(StringComparer.Ordinal).OrderBy(t => t, StringComparer.Ordinal).ToList(); + } + else if (answer.Status == OciUpstreamStatus.Unavailable && stored == null) + { + throw new OciException(OciErrorCode.UpstreamUnavailable, answer.Message ?? "The upstream registry could not be reached."); + } + } + + if (names == null) return null; + + return Page(image, names, count, last); + } + + // The tags after 'last', at most 'count', in ordinal order: the page rule of the local registry. + internal static OciTagList Page(string image, IReadOnlyList names, int? count, string? last) + { + IEnumerable ordered = names.OrderBy(n => n, StringComparer.Ordinal); + if (!string.IsNullOrEmpty(last)) ordered = ordered.Where(n => string.CompareOrdinal(n, last) > 0); + + var all = ordered.ToList(); + if (count == null) return new OciTagList(image, all, HasMore: false); + + var page = all.Take(Math.Max(count.Value, 0)).ToList(); + + return new OciTagList(image, page, HasMore: all.Count > page.Count); + } + + /// + public Task?> GetReferrersAsync(string image, string digest, string? artifactType, CancellationToken cancellationToken) + => _local.GetReferrersAsync(image, digest, artifactType, cancellationToken); + + /// + public Task GetUploadAsync(string image, string reference, CancellationToken cancellationToken) => Task.FromResult(null); + + /// + public async Task ProbeAsync(string image, string reference, CancellationToken cancellationToken) + { + if (await _local.ProbeAsync(image, reference, cancellationToken).ConfigureAwait(false) == ResolutionOutcome.Stored) return ResolutionOutcome.Stored; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return ResolutionOutcome.NotFound; + + return await _upstream.ProbeManifestAsync(upstream, image, reference, cancellationToken).ConfigureAwait(false) switch + { + OciUpstreamStatus.Found => ResolutionOutcome.WouldFetch, + OciUpstreamStatus.Offline => ResolutionOutcome.Offline, + OciUpstreamStatus.Unavailable => ResolutionOutcome.Unavailable, + _ => ResolutionOutcome.NotFound, + }; + } + + // ---- writes: refused ------------------------------------------------------------------------------------------------ + + /// + public Task StartUploadAsync(string image, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task AppendAsync(string image, string reference, long? offset, Stream chunk, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task CompleteUploadAsync(string image, string reference, string digest, long? offset, Stream? lastChunk, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task CancelUploadAsync(string image, string reference, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task PutBlobAsync(string image, string digest, Stream content, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task MountBlobAsync(string image, string digest, string fromImage, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task PutManifestAsync(string image, string reference, string? mediaType, byte[] content, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task DeleteManifestAsync(string image, string digest, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task DeleteTagAsync(string image, string tag, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task DeleteBlobAsync(string image, string digest, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task DeleteImageAsync(string image, CancellationToken cancellationToken) => throw Refused(); + + /// + public Task PruneAsync(string image, CancellationToken cancellationToken) => _local.PruneAsync(image, cancellationToken); + + // ---- the pages: what is stored -------------------------------------------------------------------------------------- + + /// + public Task ListImagesAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) + => _local.ListImagesAsync(text, skip, take, canRead, cancellationToken); + + /// + public Task GetImageAsync(string image, CancellationToken cancellationToken) => _local.GetImageAsync(image, cancellationToken); + + /// + public Task GetManifestDetailAsync(string image, string digest, CancellationToken cancellationToken) => _local.GetManifestDetailAsync(image, digest, cancellationToken); + + // ---- streams -------------------------------------------------------------------------------------------------------- + + // The bytes of a pass-through download, at most 'limit' of them, releasing the connection on disposal. + private sealed class LimitedStream : Stream + { + private readonly OciUpstreamBlob _blob; + private long _left; + + public LimitedStream(OciUpstreamBlob blob, long limit) + { + _blob = blob; + _left = limit; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + if (_left <= 0) return 0; + + var read = _blob.Content.Read(buffer.Slice(0, (int)Math.Min(buffer.Length, _left))); + _left -= read; + + return read; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_left <= 0) return 0; + + var read = await _blob.Content.ReadAsync(buffer.Slice(0, (int)Math.Min(buffer.Length, _left)), cancellationToken).ConfigureAwait(false); + _left -= read; + + return read; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) _blob.Dispose(); + + base.Dispose(disposing); + } + } + + // Reads the upstream's bytes for the client and appends the same bytes to the store; at the end of the data the digest is checked and + // the blob recorded. A failure of the store never fails the download (the blob is just not kept); a digest that does not match the + // one asked for fails it (the client would reject the bytes anyway) and keeps nothing. + private sealed class CachingStream : Stream + { + private const int FlushSize = 8 * 1024 * 1024; + + private readonly OciUpstreamBlob _blob; + private readonly string _digest; + private readonly Action _release; + private readonly OciUpstreamClient _client; + private readonly ResolvedUpstream _upstream; + private readonly ILogger _logger; + private OciBlobCacheWriter? _writer; + private byte[]? _pending; + private int _pendingLength; + private long _received; + private bool _finished; + private int _released; + + public CachingStream(OciUpstreamBlob blob, OciBlobCacheWriter? writer, string digest, Action release, OciUpstreamClient client, ResolvedUpstream upstream, ILogger logger) + { + _blob = blob; + _writer = writer; + _digest = digest; + _release = release; + _client = client; + _upstream = upstream; + _logger = logger; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + => ReadAsync(buffer.AsMemory(offset, count), CancellationToken.None).AsTask().GetAwaiter().GetResult(); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = await _blob.Content.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + if (read > 0) + { + _received += read; + if (_writer != null) await AppendAsync(buffer.Slice(0, read), cancellationToken).ConfigureAwait(false); + + // The last bytes are held back until the blob is stored: a client that has them all may go on at once (and ask for the + // layer again), and a digest that does not match must reach it as a download that ends in error, not as a finished one. + if (_received >= _blob.Length && !_finished) + { + _finished = true; + await FinishAsync(cancellationToken).ConfigureAwait(false); + } + + return read; + } + + if (!_finished) + { + _finished = true; + await FinishAsync(cancellationToken).ConfigureAwait(false); + } + + return 0; + } + + private async Task AppendAsync(ReadOnlyMemory data, CancellationToken cancellationToken) + { + try + { + _pending ??= ArrayPool.Shared.Rent(FlushSize); + while (!data.IsEmpty) + { + var take = Math.Min(data.Length, FlushSize - _pendingLength); + data.Slice(0, take).CopyTo(_pending.AsMemory(_pendingLength)); + _pendingLength += take; + data = data.Slice(take); + + if (_pendingLength == FlushSize) await FlushPendingAsync(cancellationToken).ConfigureAwait(false); + } + } + catch (Exception e) when (e is not OperationCanceledException) + { + await GiveUpAsync(e).ConfigureAwait(false); + } + } + + private async Task FlushPendingAsync(CancellationToken cancellationToken) + { + if (_pendingLength == 0 || _writer == null) return; + + await _writer.AppendAsync(_pending.AsMemory(0, _pendingLength), cancellationToken).ConfigureAwait(false); + _pendingLength = 0; + } + + private async Task GiveUpAsync(Exception e) + { + _logger.LogWarning(e, "Caching blob {Digest} failed; it is passed through without being kept", _digest); + var writer = _writer; + _writer = null; + if (writer != null) await writer.DisposeAsync().ConfigureAwait(false); + } + + private async Task FinishAsync(CancellationToken cancellationToken) + { + try + { + if (_writer != null) + { + try + { + await FlushPendingAsync(cancellationToken).ConfigureAwait(false); + if (_received != _blob.Length) throw new IOException("The upstream sent fewer bytes than it announced."); + + if (!await _writer.CompleteAsync(cancellationToken).ConfigureAwait(false)) + { + _writer = null; + _client.Rejected(_upstream, "A blob the upstream sent does not have the digest it was asked for."); + + throw new IOException("The upstream sent a blob that does not have the digest asked for."); + } + + _writer = null; + } + catch (Exception e) when (e is not OperationCanceledException and not IOException) + { + await GiveUpAsync(e).ConfigureAwait(false); + } + } + } + finally + { + Release(); + } + } + + private void Release() + { + if (_pending != null) + { + ArrayPool.Shared.Return(_pending); + _pending = null; + } + + if (Interlocked.Exchange(ref _released, 1) == 0) _release(); + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override async ValueTask DisposeAsync() => await CleanupAsync().ConfigureAwait(false); + + protected override void Dispose(bool disposing) + { + if (disposing) CleanupAsync().GetAwaiter().GetResult(); + + base.Dispose(disposing); + } + + private async Task CleanupAsync() + { + // Not read to the end (the client went away): what was received is discarded. + var writer = _writer; + _writer = null; + if (writer != null) + { + try + { + await writer.DisposeAsync().ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogDebug(e, "Discarding the partial blob {Digest} failed", _digest); + } + } + + _blob.Dispose(); + Release(); + } + } +} diff --git a/src/BaGet.Core/Formats/Docker/VirtualOciRegistry.cs b/src/BaGet.Core/Formats/Docker/VirtualOciRegistry.cs new file mode 100644 index 000000000..cf2cb2bcb --- /dev/null +++ b/src/BaGet.Core/Formats/Docker/VirtualOciRegistry.cs @@ -0,0 +1,455 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// Decides, for the members of a virtual Docker repository, whether the caller of the request may pull an image from them. The +/// registry's request pipeline (OciAuthorizationFilter) tells it how the caller is found (a registry token carries +/// grants for the members it was issued for, an API key is a principal); anything else (a page, a job) asks the access model for +/// the principal of . Scoped. +/// +public interface IOciRequestAccess +{ + /// Sets how a member's pull is decided for this request. + void Use(Func> canPull); + + /// Whether the caller may pull from . + Task CanPullAsync(RepositoryInfo member, string image, CancellationToken cancellationToken); +} + +/// The scoped . +public sealed class OciRequestAccess : IOciRequestAccess +{ + private readonly IRequestCaller _caller; + private readonly IOciAccess _access; + private Func>? _canPull; + + public OciRequestAccess(IRequestCaller caller, IOciAccess access) + { + _caller = caller ?? throw new ArgumentNullException(nameof(caller)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + } + + /// + public void Use(Func> canPull) + => _canPull = canPull ?? throw new ArgumentNullException(nameof(canPull)); + + /// + public async Task CanPullAsync(RepositoryInfo member, string image, CancellationToken cancellationToken) + { + if (_canPull != null) return await _canPull(member, image, cancellationToken).ConfigureAwait(false); + + var principal = await _caller.GetAsync(cancellationToken).ConfigureAwait(false); + + return await _access.IsAllowedAsync(principal, member, image, OciActions.Pull, cancellationToken).ConfigureAwait(false); + } +} + +/// +/// of a Docker repository: one registry made of its members, local or +/// remote, in resolution order. Each question is asked of the members the caller may pull the image from, one after the other, each in +/// its own DI scope (so its database filter, storage prefix, upstream and rules apply as they do when the member is read directly); +/// a member that fails (its upstream is down) is logged and skipped so the next one can answer. +/// +/// +/// Manifests and blobs come from the first member that has them: a tag is the first member's tag, a digest is the same +/// bytes in every member, so a layer is served by whichever member holds it first (a remote member in front of a local one fetches +/// and keeps it; one that does not have it is asked and passes). Tags are the union of the members' (a tag in several members +/// names the first member's manifest when pulled). Referrers are the members' merged. Pages and search merge the members' +/// images. +/// Writes go to the deploy repository () with that repository's rules: +/// the HTTP routes are moved to it before they reach this class (OciAuthorizationFilter); a caller of the service gets the same +/// through this class. Without a deploy repository they are refused (403). +/// +public sealed class VirtualOciRegistry : IOciRegistry +{ + private const string NoDeploy = "This virtual repository has no deploy repository, so it takes no pushes or deletes."; + + private readonly IRepositoryContext _repository; + private readonly IVirtualRepositories _virtuals; + private readonly IOciRequestAccess _access; + private readonly IServiceScopeFactory _scopes; + private readonly ILogger _logger; + + public VirtualOciRegistry( + IRepositoryContext repository, + IVirtualRepositories virtuals, + IOciRequestAccess access, + IServiceScopeFactory scopes, + ILogger logger) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + // The members that answer for the virtual repository and that the caller may pull the image from, in resolution order. + private async Task> MembersAsync(string image, CancellationToken cancellationToken) + { + var members = await _virtuals.EffectiveMembersAsync(_repository.Current, cancellationToken).ConfigureAwait(false); + var readable = new List(); + foreach (var member in members) + { + if (await _access.CanPullAsync(member, image, cancellationToken).ConfigureAwait(false)) readable.Add(member); + } + + return readable; + } + + // Runs 'action' in a scope pinned to the member. A member that does not know the image answers with nothing; one that fails is + // skipped. Cancellation and a closed maintenance gate are never swallowed. + private async Task InMemberAsync(RepositoryInfo member, Func> action) + where T : class + { + using var scope = _scopes.CreateRepositoryScope(member); + try + { + return await action(scope.ServiceProvider.GetRequiredService()).ConfigureAwait(false); + } + catch (OciException e) when (e.Code is OciErrorCode.NameUnknown or OciErrorCode.ManifestUnknown or OciErrorCode.BlobUnknown) + { + return null; + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + _logger.LogWarning("Member {Member} of virtual repository {Virtual} failed; the next member answers instead: {Reason}", member.Name, _repository.Current.Name, e is OciException ? e.Message : e.GetType().Name); + + return null; + } + } + + private async Task FirstAsync(string image, Func> action, CancellationToken cancellationToken) + where T : class + { + foreach (var member in await MembersAsync(image, cancellationToken).ConfigureAwait(false)) + { + var answer = await InMemberAsync(member, action).ConfigureAwait(false); + if (answer != null) return answer; + } + + return null; + } + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + public async Task ImageExistsAsync(string image, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image)) return false; + + foreach (var member in await MembersAsync(image, cancellationToken).ConfigureAwait(false)) + { + var exists = await InMemberAsync(member, async registry => await registry.ImageExistsAsync(image, cancellationToken).ConfigureAwait(false) ? new object() : null).ConfigureAwait(false); + if (exists != null) return true; + } + + return false; + } + + /// + public Task GetBlobInfoAsync(string image, string digest, CancellationToken cancellationToken) + => FirstAsync(image, registry => registry.GetBlobInfoAsync(image, digest, cancellationToken), cancellationToken); + + /// + /// The member's scope lives as long as the blob is read: a remote member keeps the blob it streams in its own database. + public async Task OpenBlobAsync(string image, string digest, long offset, long? length, CancellationToken cancellationToken) + { + foreach (var member in await MembersAsync(image, cancellationToken).ConfigureAwait(false)) + { + var scope = _scopes.CreateRepositoryScope(member); + try + { + var content = await scope.ServiceProvider.GetRequiredService().OpenBlobAsync(image, digest, offset, length, cancellationToken).ConfigureAwait(false); + if (content != null) + { + content.Owner = scope; + + return content; + } + } + catch (OciException e) when (e.Code is OciErrorCode.NameUnknown or OciErrorCode.ManifestUnknown or OciErrorCode.BlobUnknown) + { + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + _logger.LogWarning("Member {Member} of virtual repository {Virtual} failed; the next member answers instead: {Reason}", member.Name, _repository.Current.Name, e is OciException ? e.Message : e.GetType().Name); + } + catch + { + scope.Dispose(); + + throw; + } + + scope.Dispose(); + } + + return null; + } + + /// + public Task GetManifestAsync(string image, string reference, CancellationToken cancellationToken) + => FirstAsync(image, registry => registry.GetManifestAsync(image, reference, cancellationToken), cancellationToken); + + /// + public async Task ListTagsAsync(string image, int? count, string? last, CancellationToken cancellationToken) + { + var known = false; + var names = new HashSet(StringComparer.Ordinal); + foreach (var member in await MembersAsync(image, cancellationToken).ConfigureAwait(false)) + { + var list = await InMemberAsync(member, registry => registry.ListTagsAsync(image, null, null, cancellationToken)).ConfigureAwait(false); + if (list == null) continue; + + known = true; + names.UnionWith(list.Tags); + } + + return known ? RemoteOciRegistry.Page(image, names.ToList(), count, last) : null; + } + + /// + public async Task?> GetReferrersAsync(string image, string digest, string? artifactType, CancellationToken cancellationToken) + { + IReadOnlyList? merged = null; + var seen = new HashSet(StringComparer.Ordinal); + foreach (var member in await MembersAsync(image, cancellationToken).ConfigureAwait(false)) + { + var list = await InMemberAsync(member, registry => registry.GetReferrersAsync(image, digest, artifactType, cancellationToken)).ConfigureAwait(false); + if (list == null) continue; + + merged ??= new List(); + foreach (var descriptor in list) + { + if (seen.Add(descriptor.Digest)) ((List)merged).Add(descriptor); + } + } + + return merged; + } + + /// + public async Task ProbeAsync(string image, string reference, CancellationToken cancellationToken) + { + var first = ResolutionOutcome.NotFound; + foreach (var member in await MembersAsync(image, cancellationToken).ConfigureAwait(false)) + { + using var scope = _scopes.CreateRepositoryScope(member); + ResolutionOutcome outcome; + try + { + outcome = await scope.ServiceProvider.GetRequiredService().ProbeAsync(image, reference, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + outcome = ResolutionOutcome.Unavailable; + } + + if (outcome is ResolutionOutcome.Stored) return outcome; + if (first == ResolutionOutcome.NotFound) first = outcome; + } + + return first; + } + + // ---- writes: the deploy repository ---------------------------------------------------------------------------------- + + private async Task InDeployAsync(Func> action, CancellationToken cancellationToken) + { + var target = await _virtuals.DeployTargetAsync(_repository.Current, cancellationToken).ConfigureAwait(false) + ?? throw new OciException(OciErrorCode.Denied, NoDeploy); + + using var scope = _scopes.CreateRepositoryScope(target); + + return await action(scope.ServiceProvider.GetRequiredService()).ConfigureAwait(false); + } + + /// + public Task GetUploadAsync(string image, string reference, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.GetUploadAsync(image, reference, cancellationToken), cancellationToken); + + /// + public Task StartUploadAsync(string image, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.StartUploadAsync(image, cancellationToken), cancellationToken); + + /// + public Task AppendAsync(string image, string reference, long? offset, Stream chunk, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.AppendAsync(image, reference, offset, chunk, cancellationToken), cancellationToken); + + /// + public Task CompleteUploadAsync(string image, string reference, string digest, long? offset, Stream? lastChunk, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.CompleteUploadAsync(image, reference, digest, offset, lastChunk, cancellationToken), cancellationToken); + + /// + public Task CancelUploadAsync(string image, string reference, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.CancelUploadAsync(image, reference, cancellationToken), cancellationToken); + + /// + public Task PutBlobAsync(string image, string digest, Stream content, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.PutBlobAsync(image, digest, content, cancellationToken), cancellationToken); + + /// + public Task MountBlobAsync(string image, string digest, string fromImage, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.MountBlobAsync(image, digest, fromImage, cancellationToken), cancellationToken); + + /// + public Task PutManifestAsync(string image, string reference, string? mediaType, byte[] content, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.PutManifestAsync(image, reference, mediaType, content, cancellationToken), cancellationToken); + + /// + public Task DeleteManifestAsync(string image, string digest, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.DeleteManifestAsync(image, digest, cancellationToken), cancellationToken); + + /// + public Task DeleteTagAsync(string image, string tag, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.DeleteTagAsync(image, tag, cancellationToken), cancellationToken); + + /// + public Task DeleteBlobAsync(string image, string digest, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.DeleteBlobAsync(image, digest, cancellationToken), cancellationToken); + + /// + public Task DeleteImageAsync(string image, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.DeleteImageAsync(image, cancellationToken), cancellationToken); + + /// + public Task PruneAsync(string image, CancellationToken cancellationToken) + => InDeployAsync(registry => registry.PruneAsync(image, cancellationToken), cancellationToken); + + // ---- the pages: the members' images --------------------------------------------------------------------------------- + + /// + public async Task ListImagesAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) + { + // Each member lists the images the caller may pull from it; the first member's entry wins an image. + var members = await _virtuals.EffectiveMembersAsync(_repository.Current, cancellationToken).ConfigureAwait(false); + var byName = new Dictionary(StringComparer.Ordinal); + foreach (var member in members) + { + var page = await InMemberAsync(member, registry => registry.ListImagesAsync( + text, + 0, + 250, + async (name, ct) => await _access.CanPullAsync(member, name, ct).ConfigureAwait(false) + && (canRead == null || await canRead(name, ct).ConfigureAwait(false)), + cancellationToken)!).ConfigureAwait(false); + if (page == null) continue; + + foreach (var summary in page.Images) byName.TryAdd(summary.Name, summary); + } + + var all = byName.Values.OrderBy(i => i.Name, StringComparer.Ordinal).ToList(); + + return new OciImagePage(all.Count, all.Skip(Math.Max(skip, 0)).Take(Math.Clamp(take, 0, 250)).ToList()); + } + + /// + public Task GetImageAsync(string image, CancellationToken cancellationToken) + => FirstAsync(image, registry => registry.GetImageAsync(image, cancellationToken), cancellationToken); + + /// + public Task GetManifestDetailAsync(string image, string digest, CancellationToken cancellationToken) + => FirstAsync(image, registry => registry.GetManifestDetailAsync(image, digest, cancellationToken), cancellationToken); +} + +/// +/// The everything else asks for: it forwards each call to the registry of the request's repository +/// ( for a local one, , ), so the routes +/// and pages never ask which. Resolved per call, because a write to a virtual repository continues in its deploy repository. +/// +public sealed class RepositoryOciRegistry : IOciRegistry +{ + private readonly IRepositoryContext _repository; + private readonly IServiceProvider _services; + + public RepositoryOciRegistry(IRepositoryContext repository, IServiceProvider services) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + private IOciRegistry Inner => _repository.Current.Kind switch + { + RepositoryKind.Remote => _services.GetRequiredService(), + RepositoryKind.Virtual => _services.GetRequiredService(), + _ => _services.GetRequiredService(), + }; + + /// + public Task ImageExistsAsync(string image, CancellationToken cancellationToken) => Inner.ImageExistsAsync(image, cancellationToken); + + /// + public Task GetBlobInfoAsync(string image, string digest, CancellationToken cancellationToken) => Inner.GetBlobInfoAsync(image, digest, cancellationToken); + + /// + public Task OpenBlobAsync(string image, string digest, long offset, long? length, CancellationToken cancellationToken) => Inner.OpenBlobAsync(image, digest, offset, length, cancellationToken); + + /// + public Task GetManifestAsync(string image, string reference, CancellationToken cancellationToken) => Inner.GetManifestAsync(image, reference, cancellationToken); + + /// + public Task ListTagsAsync(string image, int? count, string? last, CancellationToken cancellationToken) => Inner.ListTagsAsync(image, count, last, cancellationToken); + + /// + public Task?> GetReferrersAsync(string image, string digest, string? artifactType, CancellationToken cancellationToken) => Inner.GetReferrersAsync(image, digest, artifactType, cancellationToken); + + /// + public Task GetUploadAsync(string image, string reference, CancellationToken cancellationToken) => Inner.GetUploadAsync(image, reference, cancellationToken); + + /// + public Task StartUploadAsync(string image, CancellationToken cancellationToken) => Inner.StartUploadAsync(image, cancellationToken); + + /// + public Task AppendAsync(string image, string reference, long? offset, Stream chunk, CancellationToken cancellationToken) => Inner.AppendAsync(image, reference, offset, chunk, cancellationToken); + + /// + public Task CompleteUploadAsync(string image, string reference, string digest, long? offset, Stream? lastChunk, CancellationToken cancellationToken) => Inner.CompleteUploadAsync(image, reference, digest, offset, lastChunk, cancellationToken); + + /// + public Task CancelUploadAsync(string image, string reference, CancellationToken cancellationToken) => Inner.CancelUploadAsync(image, reference, cancellationToken); + + /// + public Task PutBlobAsync(string image, string digest, Stream content, CancellationToken cancellationToken) => Inner.PutBlobAsync(image, digest, content, cancellationToken); + + /// + public Task MountBlobAsync(string image, string digest, string fromImage, CancellationToken cancellationToken) => Inner.MountBlobAsync(image, digest, fromImage, cancellationToken); + + /// + public Task PutManifestAsync(string image, string reference, string? mediaType, byte[] content, CancellationToken cancellationToken) => Inner.PutManifestAsync(image, reference, mediaType, content, cancellationToken); + + /// + public Task DeleteManifestAsync(string image, string digest, CancellationToken cancellationToken) => Inner.DeleteManifestAsync(image, digest, cancellationToken); + + /// + public Task DeleteTagAsync(string image, string tag, CancellationToken cancellationToken) => Inner.DeleteTagAsync(image, tag, cancellationToken); + + /// + public Task DeleteBlobAsync(string image, string digest, CancellationToken cancellationToken) => Inner.DeleteBlobAsync(image, digest, cancellationToken); + + /// + public Task ProbeAsync(string image, string reference, CancellationToken cancellationToken) => Inner.ProbeAsync(image, reference, cancellationToken); + + /// + public Task DeleteImageAsync(string image, CancellationToken cancellationToken) => Inner.DeleteImageAsync(image, cancellationToken); + + /// + public Task PruneAsync(string image, CancellationToken cancellationToken) => Inner.PruneAsync(image, cancellationToken); + + /// + public Task ListImagesAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) => Inner.ListImagesAsync(text, skip, take, canRead, cancellationToken); + + /// + public Task GetImageAsync(string image, CancellationToken cancellationToken) => Inner.GetImageAsync(image, cancellationToken); + + /// + public Task GetManifestDetailAsync(string image, string digest, CancellationToken cancellationToken) => Inner.GetManifestDetailAsync(image, digest, cancellationToken); +} diff --git a/src/BaGet.Core/Formats/FormatRegistry.cs b/src/BaGet.Core/Formats/FormatRegistry.cs new file mode 100644 index 000000000..60689689e --- /dev/null +++ b/src/BaGet.Core/Formats/FormatRegistry.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Core; + +/// +/// The registered s by format. Singleton; built once from the DI container, so a duplicate format or +/// a clash of storage folders fails at the first use rather than corrupting a store later. +/// +public class FormatRegistry +{ + /// The registry of a host that registered nothing: NuGet only (what tests and hand-built services use). + public static FormatRegistry Default { get; } = new(new IFormatModule[] { new NuGetFormatModule() }); + + private readonly Dictionary _modules; + + /// The modules; two for the same format, or claiming the same storage folder, are refused. + /// A duplicate format or storage folder. + public FormatRegistry(IEnumerable modules) + { + if (modules == null) throw new ArgumentNullException(nameof(modules)); + + _modules = new Dictionary(); + var folders = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [RepositoryStorage.ReposFolder] = default, + }; + var prefixes = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var module in modules) + { + if (!_modules.TryAdd(module.Format, module)) + { + throw new InvalidOperationException($"The {module.Format} format has two modules: {_modules[module.Format].GetType().Name} and {module.GetType().Name}."); + } + + foreach (var folder in module.StorageFolders) + { + if (folders.TryGetValue(folder, out var owner)) + { + throw new InvalidOperationException(folder == RepositoryStorage.ReposFolder + ? $"The {module.Format} module claims the storage folder '{folder}', which holds the non-default repositories." + : $"The {module.Format} and {owner} modules both claim the storage folder '{folder}'."); + } + + folders[folder] = module.Format; + } + + // Two formats under one path segment would answer each other's routes. An empty prefix (NuGet) may be held once. + if (prefixes.TryGetValue(module.RoutePrefix, out var other)) + { + throw new InvalidOperationException($"The {module.Format} and {other} modules both use the route prefix '{module.RoutePrefix}'."); + } + + prefixes[module.RoutePrefix] = module.Format; + } + } + + /// The modules, NuGet first, then by format. + public IReadOnlyList Modules => _modules.Values.OrderBy(m => m.Format).ToList(); + + /// The module of , or null when none is registered. + public IFormatModule? Find(RepositoryFormat format) => _modules.TryGetValue(format, out var module) ? module : null; + + /// The module of . + /// None is registered. + public IFormatModule Require(RepositoryFormat format) + => Find(format) ?? throw new NotSupportedException($"The {format} format is not available on this server."); +} diff --git a/src/BaGet.Core/Formats/IFormatModule.cs b/src/BaGet.Core/Formats/IFormatModule.cs new file mode 100644 index 000000000..ca9744744 --- /dev/null +++ b/src/BaGet.Core/Formats/IFormatModule.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// One package format (NuGet, npm, later Maven and OCI) as the common code sees it: what its repositories are called and where +/// they live, which kinds a repository of it can have, the UI it contributes, and how its artifacts are counted and purged. +/// A module only describes the format; what it does per request is a set of services registered beside it +/// (, , , +/// , looked up with ) and the format's own controllers, +/// whose routes go through BaGetEndpointBuilder.MapRoute with the module's . +/// +/// +/// Register a module with TryAddEnumerable (services.TryAddEnumerable(ServiceDescriptor.Singleton<IFormatModule, X>())); +/// collects them. A value without a registered module cannot be +/// created, routed or listed with artifacts. Modules are singletons and must not hold request state. +/// Routes. A format's protocol is served under of the repository base: for the default +/// repository /{prefix}/…, for the others /r/{repo}/{prefix}/…. NuGet predates the layer and keeps its +/// own paths (v3/…, api/v2) with an empty prefix. A request to a route of format X in a repository of another +/// format is answered 404 by RepositoryResolutionMiddleware. +/// +public interface IFormatModule +{ + /// The format this module serves; unique among registered modules. + RepositoryFormat Format { get; } + + /// The name shown to people: NuGet, npm. + string DisplayName { get; } + + /// + /// The path segment (or segments, without slashes at the ends) every route of the format starts with, after the repository + /// base: npm. Empty for NuGet, whose routes were there first. + /// + string RoutePrefix { get; } + + /// + /// The address a client is configured with, relative to the repository base (r/{repo}/, or the root for the default + /// repository): v3/index.json for NuGet, npm/ for npm. + /// + string FeedPath { get; } + + /// + /// The kinds of repository that can be created through without a dedicated administration + /// service (a virtual repository is created with its members by and is not + /// listed here). Kinds not listed are refused for this format. + /// + IReadOnlyCollection CreatableKinds { get; } + + /// + /// Whether virtual repositories of this format exist (): the format's + /// reads then merge the members, and a write goes to the deploy repository. False for a format that has not implemented the + /// merge. + /// + bool SupportsVirtual => false; + + /// + /// Whether the format stores blobs too large to buffer (Docker layers) and so needs a store that is an + /// . A repository of such a format is refused at creation when the configured store + /// cannot stream (). + /// + bool RequiresStreamingStorage => false; + + /// + /// The top-level storage folders the format writes below a repository's + /// (packages, symbols…). Two modules may not claim the same folder, nor : + /// refuses the registration, since a collision would let one format read another's files. + /// + IReadOnlyList StorageFolders { get; } + + /// + /// What the administrator fills in to create a repository of this format, on top of the name. Empty when a name is all that + /// is needed. + /// + IReadOnlyList CreateFields { get; } + + /// + /// Turns the posted (keyed by ) into the repository's + /// JSON, or null for none. + /// + /// A value is missing or not valid; the message is shown to the administrator. + string? CreateSettings(IReadOnlyDictionary fields); + + /// The links the administrator pages show for a repository of this format (browse, upload…). + IReadOnlyList RepositoryLinks(RepositoryInfo repository); + + /// + /// The number of artifacts (packages, tarballs…) each repository holds, by , over every repository + /// (the repository filter is off). Repositories without any are left out. + /// + Task> CountArtifactsAsync(IContext context, CancellationToken cancellationToken); + + /// + /// What stops a repository of this format from being deleted: artifacts, or work in flight that would be lost. + /// + Task GetUsageAsync(IContext context, int repositoryKey, CancellationToken cancellationToken); + + /// + /// Stages the removal of every database row the format keeps for the repository (the caller saves): history that dies with + /// the repository, after found it empty. + /// + Task StagePurgeAsync(IContext context, int repositoryKey, CancellationToken cancellationToken); +} + +/// What a repository still holds, from a format's point of view. +/// Stored artifacts. +/// Whether something accepted but not finished (a submission awaiting validation) would be lost. +public sealed record FormatUsage(int Artifacts, bool PendingWork); + +/// An input of the create form a format contributes. +/// The key in the dictionary receives. +/// The visible label. +/// One line of explanation, or null. +/// Whether an empty value is refused by the form. +/// For a choice: the allowed values; null for free text. +public sealed record FormatCreateField(string Name, string Label, string? Help = null, bool Required = false, IReadOnlyList? Options = null); + +/// A link a format contributes to the administration of a repository: to one of its screens or to a path under its base. +/// Built with or : the constructor is private, so a call written for the older +/// (Id, Label, Page, Path) shape fails to compile instead of putting the path in . +public sealed record FormatLink +{ + private FormatLink(string id, string label, string? controller, string? action, string? path, bool needsUploads) + { + Id = id; + Label = label; + Controller = controller; + Action = action; + Path = path; + NeedsUploads = needsUploads; + } + + /// A link to a screen of the repository (Home/Index), given the repository's repo route value. + public static FormatLink ToScreen(string id, string label, string controller, string action, bool needsUploads = false) + => new(id, label, controller ?? throw new ArgumentNullException(nameof(controller)), action ?? throw new ArgumentNullException(nameof(action)), null, needsUploads); + + /// A link to a path under the repository base (npm/). + public static FormatLink ToPath(string id, string label, string path, bool needsUploads = false) + => new(id, label, null, null, path ?? throw new ArgumentNullException(nameof(path)), needsUploads); + + /// A stable identifier (browse, upload); becomes the CSS class repository-{id}. + public string Id { get; } + + /// The visible text. + public string Label { get; } + + /// The MVC controller (without the suffix) of the screen it opens; null for a path link. + public string? Controller { get; } + + /// The action of that controller that shows the screen; null for a path link. + public string? Action { get; } + + /// A path under the repository base; null for a screen link. + public string? Path { get; } + + /// Shown only for repositories that take uploads (not a remote one, nor a virtual one without a deploy repository). + public bool NeedsUploads { get; } +} diff --git a/src/BaGet.Core/Formats/IFormatServices.cs b/src/BaGet.Core/Formats/IFormatServices.cs new file mode 100644 index 000000000..c129f38a8 --- /dev/null +++ b/src/BaGet.Core/Formats/IFormatServices.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Core; + +/// +/// A per-request capability of one format, registered (scoped) beside its . It works in the +/// request's repository (), like every other scoped service. +/// +public interface IFormatService +{ + /// The format the service belongs to. + RepositoryFormat Format { get; } +} + +/// Finds the capability of a format. +public static class FormatServices +{ + /// + /// The registered of , or null when the format does not offer it (a + /// phase that has not implemented it yet). Callers treat null as "not supported", never as an error. + /// + public static T? GetFormatService(this IServiceProvider provider, RepositoryFormat format) + where T : class, IFormatService + => provider.GetServices().FirstOrDefault(s => s.Format == format); +} + +/// What happened to an artifact handed to . +public enum FormatIndexResult +{ + /// The bytes are not a valid artifact of the format. + Invalid, + + /// The same name and version is already in the repository. + AlreadyExists, + + /// Stored and visible. + Indexed, + + /// Stored and queued (validation); not visible yet. + Accepted, +} + +/// Reads an artifact, stores it and records its metadata in the repository of the request (deploy). +public interface IFormatIndexer : IFormatService +{ + /// Indexes the artifact in . + Task IndexAsync(Stream? artifact, CancellationToken cancellationToken); +} + +/// A search in one repository. +/// The text, or null for everything. +/// Results to skip. +/// Results to return. +/// Whether prerelease versions count. +public sealed record FormatSearchQuery(string? Query, int Skip, int Take, bool IncludePrerelease); + +/// One search result: an artifact name with its newest version. +public sealed record FormatSearchHit(string Name, string? Version, string? Description, long Downloads); + +/// A page of search results. +/// All matches, not only this page. +/// This page. +public sealed record FormatSearchPage(long TotalHits, IReadOnlyList Hits); + +/// Searches the repository of the request in the format's own terms (the protocol's search endpoint uses its richer model). +public interface IFormatSearchProvider : IFormatService +{ + /// Runs . + Task SearchAsync(FormatSearchQuery query, CancellationToken cancellationToken); +} + +/// A stored version, as retention policies see it. +/// The artifact name (package id, npm name, Maven coordinates). +/// The version. +/// When it was stored. +/// The last download, when known. +/// Bytes stored for it, when known. +/// Whether it is a prerelease (npm), a pre-release (NuGet) or a snapshot (Maven). +public sealed record FormatVersion(string Name, string Version, DateTime Published, DateTime? LastDownloaded, long? Size, bool Prerelease); + +/// +/// What retention (phase P6) needs from a format: list what is stored and delete one version, in the repository of the request +/// (the retention engine runs each repository in its own scope). Implemented for NuGet, npm, Maven and Docker. Deleting is the +/// administrator's cleanup, not a user action: no caller is checked, but the maintenance gate is ( is +/// never swallowed by the engine). +/// +public interface IFormatRetentionHooks : IFormatService +{ + /// + /// Every stored version of the repository that a policy may delete (a Docker tag is a version of its image). A virtual + /// repository stores nothing and has none. + /// + Task> ListVersionsAsync(CancellationToken cancellationToken); + + /// + /// Deletes one version for good (metadata and files). The name and version are the ones or + /// returned. + /// + Task DeleteVersionAsync(string name, string version, CancellationToken cancellationToken); + + /// + /// Things the format stores that no version points at, which only the "untagged" rule considers (Docker manifests without a + /// tag, index or referrer relationship; is their digest). Default: none. + /// + Task> ListUnreferencedAsync(CancellationToken cancellationToken) + => Task.FromResult>(Array.Empty()); + + /// + /// Bytes stored for one version, when was left null by the listing because measuring is costly + /// (NuGet reads the package, Docker adds its layers); null when unknown. Only the remote cache limit asks. + /// + Task GetSizeAsync(string name, string version, CancellationToken cancellationToken) + => Task.FromResult(null); + + /// + /// The name and version in the form the listing uses (NuGet: normalized version; a legal hold is stored this way), or null + /// when they are not valid for the format. An empty or null stays empty (every version). Default: trimmed as given. + /// + (string Name, string Version)? Canonical(string name, string? version) + => string.IsNullOrWhiteSpace(name) ? null : (name.Trim(), version?.Trim() ?? string.Empty); +} +/// A third-party component of an artifact, named the way a vulnerability database names it. +/// The OSV ecosystem: NuGet, npm, Maven. +/// The component name in that ecosystem. +/// Its version. +public sealed record ScanComponent(string Ecosystem, string Name, string Version); + +/// An artifact version to scan, named as names it. +/// The artifact name (NuGet id, npm name, Maven group:artifact, Docker image). +/// The version (Docker: the manifest digest). +public sealed record ScanArtifact(string Name, string Version); + +/// How a format's artifacts are checked. +public enum ScanEngine +{ + /// The artifact's components are looked up in OSV (). + Osv, + + /// The artifact is a container image that Trivy pulls and scans (). + Image, +} + +/// +/// What vulnerability scanning (phase P7) needs from a format, in the repository of the request: how its artifacts are checked, +/// what is stored (to scan on a schedule), and for an OSV format the components an artifact consists of (itself and its +/// declared dependencies, by exact version where the format states one). +/// +public interface IFormatScanner : IFormatService +{ + /// How the format's artifacts are checked. Default: components against OSV. + ScanEngine Engine => ScanEngine.Osv; + + /// The components of the stored version, or none when it is unknown ( formats). + Task> ListComponentsAsync(string name, string version, CancellationToken cancellationToken); + + /// + /// For : the image as a registry names it below the repository, {image}@{digest}, or null + /// when it is not stored. + /// + Task GetImageReferenceAsync(string name, string version, CancellationToken cancellationToken) + => Task.FromResult(null); + + /// Every artifact version stored in the repository (what a scheduled sweep and Scan now go through). + Task> ListArtifactsAsync(CancellationToken cancellationToken); +} diff --git a/src/BaGet.Core/Formats/Maven/IMavenRepository.cs b/src/BaGet.Core/Formats/Maven/IMavenRepository.cs new file mode 100644 index 000000000..e81c47752 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/IMavenRepository.cs @@ -0,0 +1,300 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// How an operation of a Maven repository ended; the HTTP routes and the pages map it the same way. +public enum MavenStatus +{ + /// Done. + Ok, + + /// Done, and something was stored (HTTP 201). + Created, + + /// Nobody is authenticated (HTTP 401). + Unauthorized, + + /// The caller is not allowed, or the repository takes no changes (HTTP 403). + Forbidden, + + /// No such artifact, version or file (HTTP 404). + NotFound, + + /// The request clashes with what exists or with the repository's policy (HTTP 409). + Conflict, + + /// The request is not valid (HTTP 400); says why. + Invalid, + + /// The file is larger than Maven:MaxFileBytes (HTTP 413). + TooLarge, +} + +/// The outcome of an operation of a Maven repository. +/// How it ended. +/// A sentence for the person or client when it did not succeed (or a note when it did). +/// For a deletion or a cleanup: how many files were removed. +/// The artifact the operation was about (group:artifact), when it succeeded. +public sealed record MavenResult(MavenStatus Status, string? Message = null, int Count = 0, string? Subject = null) +{ + /// Whether the operation was done. + public bool Succeeded => Status is MavenStatus.Ok or MavenStatus.Created; + + internal static MavenResult Ok(string? message = null, int count = 0, string? subject = null) => new(MavenStatus.Ok, message, count, subject); + + internal static MavenResult Created(string? message = null, string? subject = null) => new(MavenStatus.Created, message, 0, subject); + + internal static MavenResult Fail(MavenStatus status, string message) => new(status, message); +} + +/// A file (or generated metadata) being served. Dispose it when the response is written. +public sealed class MavenDownload : IDisposable +{ + internal MavenDownload(Stream content, long length, string contentType, string fileName, DateTime lastModified) + { + Content = content; + Length = length; + ContentType = contentType; + FileName = fileName; + LastModified = lastModified; + } + + /// The bytes. + public Stream Content { get; } + + /// Their number. + public long Length { get; } + + /// The content type. + public string ContentType { get; } + + /// The file name. + public string FileName { get; } + + /// When the file was stored (UTC). + public DateTime LastModified { get; } + + /// SHA-1 hex of the content, sent as X-Checksum-Sha1. + public string? Sha1 { get; internal init; } + + /// MD5 hex of the content. + public string? Md5 { get; internal init; } + + /// SHA-256 hex of the content. + public string? Sha256 { get; internal init; } + + /// + public void Dispose() => Content.Dispose(); +} + +/// A file of a version as the pages list it. +/// The file name. +/// The classifier, or null. +/// The extension. +/// Bytes. +/// SHA-1 hex. +/// MD5 hex. +/// SHA-256 hex. +/// SHA-512 hex. +/// When stored (UTC). +/// The snapshot build timestamp, or null. +/// The snapshot build number, or 0. +public sealed record MavenFileDetail( + string FileName, + string? Classifier, + string Extension, + long Size, + string Sha1, + string Md5, + string Sha256, + string Sha512, + DateTime Created, + string? SnapshotTimestamp, + int SnapshotBuild); + +/// A version as the artifact page lists it. +/// The version. +/// Whether it is a snapshot. +/// The POM's name, or null. +/// The POM's description, or null. +/// The POM's packaging, or null. +/// The first file (UTC). +/// The last change (UTC). +/// Files of the version. +/// Bytes of the version. +/// For a snapshot: how many timestamped builds it holds. +public sealed record MavenVersionSummary( + string Version, + bool IsSnapshot, + string? Name, + string? Description, + string? Packaging, + DateTime Created, + DateTime Modified, + int FileCount, + long Size, + int Builds); + +/// An artifact with its versions, newest first. +/// The group id. +/// The artifact id. +/// The first deploy (UTC). +/// The last change (UTC). +/// Its versions, highest first. +public sealed record MavenArtifactInfo(string GroupId, string ArtifactId, DateTime Created, DateTime Modified, IReadOnlyList Versions) +{ + /// The highest release, else the highest version. + public MavenVersionSummary? Latest => Versions.Count == 0 ? null : Versions.FirstOrDefault(v => !v.IsSnapshot) ?? Versions[0]; + + /// group:artifact. + public string Name => MavenNames.ArtifactName(GroupId, ArtifactId); +} + +/// One version with its files and POM. +/// The version. +/// Its files, by name. +/// The parsed POM, or null when none was deployed or it could not be read. +/// The POM text (for the view), or null. +public sealed record MavenVersionDetail(MavenVersionSummary Summary, IReadOnlyList Files, MavenPomInfo? Pom, string? PomText); + +/// A search hit. +/// The group id. +/// The artifact id. +/// The newest version (a release if there is one), or null. +/// The POM's description of it, or null. +/// The POM's name of it, or null. +/// The last change (UTC). +public sealed record MavenSearchHit(string GroupId, string ArtifactId, string? Version, string? Name, string? Description, DateTime Modified) +{ + /// group:artifact. + public string CoordinateName => MavenNames.ArtifactName(GroupId, ArtifactId); +} + +/// A page of hits. +/// All matches. +/// This page. +public sealed record MavenSearchPage(int Total, IReadOnlyList Hits); + +/// +/// A Maven repository (): the Maven 2 layout under maven/ of the repository +/// base, checksums, maven-metadata.xml, snapshots with timestamped builds and the pages' reads. It works in the repository +/// of the request, whose kind picks the implementation (): +/// for a local repository (generated metadata, the release/snapshot policy; every change takes the caller and is authorized through +/// : the access model, then ownership of group:artifact), +/// (a caching proxy of an upstream such as Maven Central, which takes no changes) and (members +/// merged, changes going to the deploy repository), so routes, pages and accounts cannot differ. +/// +public interface IMavenRepository +{ + /// + /// The artifact a request path is about, for the access check: the version level of a metadata path when that version is + /// stored, else the artifact level. Null when the path names no artifact (a group-level metadata path). + /// + Task ResolveAsync(MavenRequestPath path, CancellationToken cancellationToken); + + /// Opens what names: a stored file, a checksum, or generated metadata. Null when there is none. + Task OpenAsync(MavenRequestPath path, CancellationToken cancellationToken); + + /// + /// Like for a HEAD request: the answer's length, type and checksums are right but its content is + /// not read (a remote repository does not download and keep a file only to say that it exists). Null when there is none. + /// + Task HeadAsync(MavenRequestPath path, CancellationToken cancellationToken); + + /// + /// PUT: stores a file, checks a checksum, or accepts metadata (which is generated, not stored). The body is read once, + /// to a temporary file, while its checksums are computed. + /// + Task PutAsync(BaGetPrincipal? caller, MavenRequestPath path, Stream content, CancellationToken cancellationToken); + + /// + /// Stores the files of one artifact version at once (the upload page): a pom (generated when none is given) and the + /// main file, each under its Maven name. + /// + Task DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken); + + /// DELETE of one file (and its checksums with it). The version and artifact go with their last file. + Task DeleteFileAsync(BaGetPrincipal? caller, MavenCoordinate version, string fileName, CancellationToken cancellationToken); + + /// Deletes a version with its files. + Task DeleteVersionAsync(BaGetPrincipal? caller, MavenCoordinate version, CancellationToken cancellationToken); + + /// Deletes an artifact with every version. + Task DeleteArtifactAsync(BaGetPrincipal? caller, string groupId, string artifactId, CancellationToken cancellationToken); + + /// + /// Deletes the timestamped builds of a snapshot version older than the newest (at least 1). The + /// result's is the number of files removed. + /// + Task CleanupSnapshotsAsync(BaGetPrincipal? caller, MavenCoordinate version, int keep, CancellationToken cancellationToken); + + /// The artifacts whose group id, artifact id or POM name or description contains the text, by coordinates. + /// The text, or null for everything. + /// Hits to skip. + /// Hits to return. + /// Whether the caller may read an artifact (group:artifact); null for all. Unreadable ones are left out of the page and the total. + /// Cancellation. + Task SearchAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken); + + /// An artifact with its versions, or null. + Task GetArtifactAsync(string groupId, string artifactId, CancellationToken cancellationToken); + + /// One version with its files and POM, or null. + Task GetVersionAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken); + + /// The settings of the repository (policy, redeploy, snapshot builds kept; a remote or virtual repository has none of its own and accepts both kinds). + Task GetSettingsAsync(CancellationToken cancellationToken); + + /// + /// Where a version would come from, without storing or serving anything: stored here, fetched from the upstream, unknown, or + /// not askable (the resolution preview of a virtual repository asks each member). + /// + Task ProbeAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken); +} + +/// What the upload page hands to . +public sealed class MavenDeployment +{ + /// The group id. + public string? GroupId { get; init; } + + /// The artifact id. + public string? ArtifactId { get; init; } + + /// The version. + public string? Version { get; init; } + + /// The packaging, the extension of the main file when it has no other (default jar). + public string? Packaging { get; init; } + + /// The classifier of the main file, or null. + public string? Classifier { get; init; } + + /// The extension of the main file (default: the packaging). + public string? Extension { get; init; } + + /// The main file, or null when only a POM is deployed. + public Stream? File { get; init; } + + /// The POM file, or null to generate a minimal one (only when the main file has no classifier). + public Stream? Pom { get; init; } +} + +/// +/// The upstream of a remote Maven repository could not be reached (or refused the credentials, or sent something that is not a +/// repository's answer) and nothing stored or remembered can answer instead. The HTTP route answers 502; a virtual repository +/// skips the member. The message names no URL and no credential. +/// +public sealed class MavenUpstreamException : Exception +{ + /// What failed, safe to show. + public MavenUpstreamException(string message) + : base(message) + { + } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenEntities.cs b/src/BaGet.Core/Formats/Maven/MavenEntities.cs new file mode 100644 index 000000000..73b201fb6 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenEntities.cs @@ -0,0 +1,106 @@ +using System; + +namespace BaGet.Core; + +/// +/// A Maven artifact (groupId:artifactId) of one repository: the facts shared by all its versions. Group and artifact +/// ids are case-sensitive, as Maven's layout is (the SQL Server and MySQL contexts compare them by code point). +/// +public class MavenArtifact : IRepositoryScoped +{ + public int Key { get; set; } + + /// The owning repository; see . + public int RepositoryKey { get; set; } + + /// The group id (org.apache.maven). Unique with per repository. + public string? GroupId { get; set; } + + /// The artifact id (maven-core). + public string? ArtifactId { get; set; } + + /// The first deploy. + public DateTime Created { get; set; } + + /// The last change to any version or file. + public DateTime Modified { get; set; } +} + +/// +/// One version of a (1.2.3, or 1.0-SNAPSHOT, which holds the timestamped builds as +/// files). The POM facts are read from the .pom file when it is deployed and feed the search; the POM itself is a file. +/// +public class MavenVersion +{ + public int Key { get; set; } + + /// The . Required; deleting the artifact deletes its versions. + public int ArtifactKey { get; set; } + + /// The version as it is in the path. Unique per artifact. + public string? Version { get; set; } + + /// Whether the version ends in -SNAPSHOT. + public bool IsSnapshot { get; set; } + + /// The POM's name (cut to the column), or null. + public string? Name { get; set; } + + /// The POM's description (cut to the column), or null. + public string? Description { get; set; } + + /// The POM's packaging (jar when the POM says nothing), or null before a POM was deployed. + public string? Packaging { get; set; } + + /// The first file of the version. + public DateTime Created { get; set; } + + /// The last file added or replaced. + public DateTime Modified { get; set; } +} + +/// +/// A file of a : an artifact (a-1.0.jar, a-1.0-sources.jar), a POM or a signature. The +/// bytes live in storage (maven/{group}/{artifact}/{version}/{file} under the repository's prefix); checksums are +/// computed on the way in and served from here. +/// +public class MavenFile +{ + public int Key { get; set; } + + /// The . Required; deleting the version deletes its files. + public int VersionKey { get; set; } + + /// The file name as in the path. Unique per version. + public string? FileName { get; set; } + + /// The classifier (sources), or null. + public string? Classifier { get; set; } + + /// The extension without the dot (jar, tar.gz, jar.asc). + public string? Extension { get; set; } + + /// For a timestamped snapshot build: its yyyyMMdd.HHmmss UTC timestamp; otherwise null. + public string? SnapshotTimestamp { get; set; } + + /// For a timestamped snapshot build: its build number; otherwise 0. + public int SnapshotBuild { get; set; } + + /// Bytes stored. + public long Size { get; set; } + + /// SHA-1, lower-case hex. + public string? Sha1 { get; set; } + + /// MD5, lower-case hex. + public string? Md5 { get; set; } + + /// SHA-256, lower-case hex. + public string? Sha256 { get; set; } + + /// SHA-512, lower-case hex. + public string? Sha512 { get; set; } + + /// When the file was stored. + public DateTime Created { get; set; } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenFormatModule.cs b/src/BaGet.Core/Formats/Maven/MavenFormatModule.cs new file mode 100644 index 000000000..9ec2dacd6 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenFormatModule.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Maven on the format layer: the Maven 2 repository layout under maven/ of the repository base (never served for +/// default, which is NuGet; a repository libs is at /r/libs/maven/), files under maven/… in storage. +/// A local repository holds artifacts (its release/snapshot policy, redeploy and snapshot retention are its +/// ); a remote one caches an upstream such as Maven Central (); +/// a virtual one merges members (). See . +/// +public class MavenFormatModule : IFormatModule +{ + /// + public RepositoryFormat Format => RepositoryFormat.Maven; + + /// + public string DisplayName => "Maven"; + + /// + public string RoutePrefix => "maven"; + + /// + public string FeedPath => "maven/"; + + /// + public IReadOnlyCollection CreatableKinds { get; } = new[] { RepositoryKind.Local, RepositoryKind.Remote }; + + /// + public bool SupportsVirtual => true; + + /// + public IReadOnlyList StorageFolders { get; } = new[] { MavenNames.StorageFolder }; + + /// + public IReadOnlyList CreateFields { get; } = new[] + { + new FormatCreateField("policy", "Versions accepted", "Releases (the default), -SNAPSHOT versions, or both.", Options: new[] { "Releases", "Snapshots", "Both" }), + new FormatCreateField("redeploy", "Redeploy releases", "Whether a release file that exists may be replaced (needs the Delete permission). Default: no.", Options: new[] { "No", "Yes" }), + new FormatCreateField("snapshotBuilds", "Snapshot builds kept", "How many timestamped builds of a snapshot are kept (0: all). Older ones are deleted when a newer build arrives."), + }; + + /// + public string? CreateSettings(IReadOnlyDictionary fields) => MavenRepositorySettings.FromFields(fields).ToJson(); + + /// + public IReadOnlyList RepositoryLinks(RepositoryInfo repository) => new[] + { + FormatLink.ToScreen("browse", "Browse", "MavenBrowse", "Artifacts"), + FormatLink.ToScreen("upload", "Upload", "MavenBrowse", "Upload", needsUploads: true), + FormatLink.ToPath("repository", "Repository", "maven/"), + }; + + /// + public async Task> CountArtifactsAsync(IContext context, CancellationToken cancellationToken) + => await context.MavenArtifacts! + .IgnoreQueryFilters() + .GroupBy(a => a.RepositoryKey) + .Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken) + .ConfigureAwait(false); + + /// + public async Task GetUsageAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + var artifacts = await context.MavenArtifacts!.IgnoreQueryFilters().CountAsync(e => e.RepositoryKey == repositoryKey, cancellationToken).ConfigureAwait(false); + + return new FormatUsage(artifacts, PendingWork: false); + } + + /// + /// An empty repository has no artifacts, so versions and files (which cascade) are gone; what is left is the owner rows. + public async Task StagePurgeAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + context.MavenArtifacts!.RemoveRange(await context.MavenArtifacts!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + context.PackageOwners!.RemoveRange(await context.PackageOwners!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + } +} + +/// Maven's : artifacts whose coordinates or POM name or description contain the query. +public class MavenFormatSearchProvider : IFormatSearchProvider +{ + private readonly IMavenRepository _repository; + + /// The repository of the request. + public MavenFormatSearchProvider(IMavenRepository repository) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Maven; + + /// + public async Task SearchAsync(FormatSearchQuery query, CancellationToken cancellationToken) + { + if (query == null) throw new ArgumentNullException(nameof(query)); + + var page = await _repository.SearchAsync(query.Query, query.Skip, query.Take, canRead: null, cancellationToken).ConfigureAwait(false); + + return new FormatSearchPage( + page.Total, + page.Hits + .Where(h => query.IncludePrerelease || h.Version == null || !MavenNames.IsSnapshot(h.Version)) + .Select(h => new FormatSearchHit(h.CoordinateName, h.Version, h.Description ?? h.Name, Downloads: 0)) + .ToList()); + } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenFormatScanner.cs b/src/BaGet.Core/Formats/Maven/MavenFormatScanner.cs new file mode 100644 index 000000000..024fc84e4 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenFormatScanner.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// What a Maven version is made of for scanning: itself and the POM's compile and runtime dependencies that state a literal +/// version (1.2.3, or the lower bound of a range such as [1.2,2.0)); versions that are properties +/// (${spring.version}), managed elsewhere or empty are skipped. +/// +public static class MavenScanComponents +{ + /// The OSV ecosystem name. + public const string Ecosystem = "Maven"; + + /// The artifact and the dependencies of (null: just the artifact). + public static IReadOnlyList Of(string groupId, string artifactId, string version, MavenPomInfo? pom) + { + var result = new List { new(Ecosystem, MavenNames.ArtifactName(groupId, artifactId), version) }; + foreach (var dependency in pom?.Dependencies ?? Array.Empty()) + { + if (dependency.Optional) continue; + if (dependency.Scope != null && dependency.Scope != "compile" && dependency.Scope != "runtime") continue; + + var literal = LiteralVersion(dependency.Version); + if (literal == null) continue; + + var component = new ScanComponent(Ecosystem, MavenNames.ArtifactName(dependency.GroupId, dependency.ArtifactId), literal); + if (!result.Contains(component)) result.Add(component); + } + + return result; + } + + /// The version a requirement names: a plain version, or the lower bound of a range; null when there is none. + internal static string? LiteralVersion(string? requirement) + { + var value = requirement?.Trim(); + if (string.IsNullOrEmpty(value) || value.Contains("${", StringComparison.Ordinal)) return null; + + if (value[0] == '[' || value[0] == '(') + { + var inner = value.Trim('[', ']', '(', ')'); + var lower = inner.Split(',')[0].Trim(); + return lower.Length == 0 ? null : lower; + } + + return value; + } +} + +/// Maven's : the stored versions with the dependencies of their POM against OSV. +public sealed class MavenFormatScanner : IFormatScanner +{ + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IRepositoryContext _repository; + + public MavenFormatScanner(IContext context, IStorageService storage, IRepositoryContext repository) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Maven; + + /// + public async Task> ListComponentsAsync(string name, string version, CancellationToken cancellationToken) + { + if (_context is NullContext || !MavenNames.TryParseArtifactName(name, out var groupId, out var artifactId)) return Array.Empty(); + + var versionKey = await (from v in _context.MavenVersions!.AsNoTracking() + join a in _context.MavenArtifacts!.AsNoTracking() on v.ArtifactKey equals a.Key + where a.GroupId == groupId && a.ArtifactId == artifactId && v.Version == version + select (int?)v.Key).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (versionKey == null) return Array.Empty(); + + MavenPomInfo? pom = null; + var pomRow = await _context.MavenFiles!.AsNoTracking() + .Where(f => f.VersionKey == versionKey && f.Extension == "pom" && f.Classifier == null) + .OrderByDescending(f => f.SnapshotTimestamp) + .ThenByDescending(f => f.SnapshotBuild) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + if (pomRow != null && pomRow.Size <= MavenPom.MaxBytes) + { + try + { + using var stream = await _storage.GetAsync(RepositoryStorage.Scope(_repository.Current, MavenNames.StoragePath(groupId, artifactId, version, pomRow.FileName!)), cancellationToken).ConfigureAwait(false); + pom = MavenPom.TryParse(stream); + } + catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) + { + // A POM missing from storage leaves the artifact itself to scan. + } + } + + return MavenScanComponents.Of(groupId, artifactId, version, pom); + } + + /// + public async Task> ListArtifactsAsync(CancellationToken cancellationToken) + { + if (_context is NullContext) return Array.Empty(); + + var rows = await _context.MavenVersions! + .AsNoTracking() + .Join(_context.MavenArtifacts!, v => v.ArtifactKey, a => a.Key, (v, a) => new { a.GroupId, a.ArtifactId, v.Version }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + return rows.Select(r => new ScanArtifact(MavenNames.ArtifactName(r.GroupId!, r.ArtifactId!), r.Version!)).ToList(); + } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenMetadata.cs b/src/BaGet.Core/Formats/Maven/MavenMetadata.cs new file mode 100644 index 000000000..59799ee11 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenMetadata.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Xml.Linq; + +namespace BaGet.Core; + +/// A stored file as the metadata generator needs it. +/// The file name. +/// The classifier, or null. +/// The extension. +/// The snapshot build's timestamp (yyyyMMdd.HHmmss), or null. +/// The snapshot build number, 0 when not a timestamped build. +/// When it was stored. +public sealed record MavenFileInfo(string FileName, string? Classifier, string Extension, string? SnapshotTimestamp, int SnapshotBuild, DateTime Created); + +/// +/// Generates maven-metadata.xml from what is stored; it is never kept as a file, so it can never disagree with the +/// versions (and a client's own copy, uploaded by mvn deploy, is not needed). The same bytes are hashed for the +/// .sha1 / .md5 companions. +/// +public static class MavenMetadata +{ + /// The artifact level: every version, with latest and release. + /// The group id. + /// The artifact id. + /// The stored versions. + /// When the artifact last changed. + /// The version to name as latest when it is one of (a virtual repository follows its member order); the highest otherwise. + /// The version to name as release when it is one of ; the highest release otherwise. + public static string ForArtifact(string groupId, string artifactId, IEnumerable versions, DateTime lastUpdated, string? latest = null, string? release = null) + { + var ordered = versions.Distinct(StringComparer.Ordinal).OrderBy(v => v, Comparer.Create(MavenNames.CompareVersions)).ToList(); + latest = latest != null && ordered.Contains(latest, StringComparer.Ordinal) ? latest : ordered.Count > 0 ? ordered[^1] : null; + release = release != null && ordered.Contains(release, StringComparer.Ordinal) ? release : ordered.LastOrDefault(v => !MavenNames.IsSnapshot(v)); + + var versioning = new XElement("versioning"); + if (latest != null) versioning.Add(new XElement("latest", latest)); + if (release != null) versioning.Add(new XElement("release", release)); + + versioning.Add(new XElement("versions", ordered.Select(v => new XElement("version", v)))); + versioning.Add(new XElement("lastUpdated", Stamp(lastUpdated))); + + return Document(new XElement( + "metadata", + new XElement("groupId", groupId), + new XElement("artifactId", artifactId), + versioning)); + } + + /// + /// The version level of a snapshot: the newest build and, per classifier and extension, the timestamped version that + /// resolves it. A release version has no such file in Maven's layout, and gets the plain form. + /// + /// The group id. + /// The artifact id. + /// The version. + /// The version's files. + /// When the version last changed. + public static string ForVersion(string groupId, string artifactId, string version, IEnumerable files, DateTime lastUpdated) + { + var root = new XElement( + "metadata", + new XAttribute("modelVersion", "1.1.0"), + new XElement("groupId", groupId), + new XElement("artifactId", artifactId), + new XElement("version", version)); + + var builds = files.Where(f => f.SnapshotTimestamp != null).ToList(); + if (MavenNames.IsSnapshot(version) && builds.Count > 0) + { + var baseVersion = version.Substring(0, version.Length - MavenNames.SnapshotSuffix.Length); + var newest = builds.OrderByDescending(f => f.SnapshotTimestamp, StringComparer.Ordinal).ThenByDescending(f => f.SnapshotBuild).First(); + + var snapshotVersions = builds + .GroupBy(f => (f.Classifier, f.Extension)) + .Select(g => g.OrderByDescending(f => f.SnapshotTimestamp, StringComparer.Ordinal).ThenByDescending(f => f.SnapshotBuild).First()) + .OrderBy(f => f.Extension, StringComparer.Ordinal).ThenBy(f => f.Classifier, StringComparer.Ordinal) + .Select(f => + { + var element = new XElement("snapshotVersion"); + if (f.Classifier != null) element.Add(new XElement("classifier", f.Classifier)); + + element.Add(new XElement("extension", f.Extension)); + element.Add(new XElement("value", $"{baseVersion}-{f.SnapshotTimestamp}-{f.SnapshotBuild.ToString(CultureInfo.InvariantCulture)}")); + element.Add(new XElement("updated", Stamp(f.Created))); + + return element; + }); + + root.Add(new XElement( + "versioning", + new XElement( + "snapshot", + new XElement("timestamp", newest.SnapshotTimestamp), + new XElement("buildNumber", newest.SnapshotBuild.ToString(CultureInfo.InvariantCulture))), + new XElement("lastUpdated", Stamp(lastUpdated)), + new XElement("snapshotVersions", snapshotVersions))); + } + + return Document(root); + } + + /// Maven's yyyyMMddHHmmss UTC timestamp. + public static string Stamp(DateTime value) + => DateTime.SpecifyKind(value, DateTimeKind.Utc).ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture); + + private static string Document(XElement root) + => new XDeclaration("1.0", "UTF-8", null) + Environment.NewLine + root.ToString() + Environment.NewLine; +} diff --git a/src/BaGet.Core/Formats/Maven/MavenNames.cs b/src/BaGet.Core/Formats/Maven/MavenNames.cs new file mode 100644 index 000000000..243fa18ae --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenNames.cs @@ -0,0 +1,396 @@ +using System; +using Ctx = BaGet.Core.AbstractContext; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; + +namespace BaGet.Core; + +/// What a requested Maven path names. +public enum MavenPathKind +{ + /// A file of an artifact version (or a checksum of one). + File, + + /// maven-metadata.xml at the artifact, version or group level (or a checksum of it). + Metadata, +} + +/// A groupId:artifactId and optionally a version. +/// The group id. +/// The artifact id. +/// The version, or null for the artifact level. +public sealed record MavenCoordinate(string GroupId, string ArtifactId, string? Version) +{ + /// The name the access model, ownership and the pages call the artifact: group:artifact. + public string Name => MavenNames.ArtifactName(GroupId, ArtifactId); +} + +/// A request path below maven/, taken apart. +public sealed class MavenRequestPath +{ + internal MavenRequestPath(string relativePath, MavenPathKind kind, string fileName, string baseName, string? checksum, IReadOnlyList candidates, string? groupOnly) + { + RelativePath = relativePath; + Kind = kind; + FileName = fileName; + BaseName = baseName; + ChecksumAlgorithm = checksum; + Candidates = candidates; + GroupOnly = groupOnly; + } + + /// The path as requested, relative to the repository's maven/ address (org/acme/lib/1.0/lib-1.0.jar.sha1). + public string RelativePath { get; } + + /// Whether it is a file or metadata. + public MavenPathKind Kind { get; } + + /// The last segment as requested (a-1.0.jar.sha1). + public string FileName { get; } + + /// The file the request is about: without the checksum extension. + public string BaseName { get; } + + /// md5, sha1, sha256 or sha512 when the request is for a checksum; otherwise null. + public string? ChecksumAlgorithm { get; } + + /// + /// What the directory path can mean. A file has exactly one (group, artifact, version). Metadata has the version level + /// (when the path is deep enough) first and the artifact level second: a/b/c/maven-metadata.xml is version c + /// of a:b or the artifact b:c of group a; the stored versions decide. + /// + public IReadOnlyList Candidates { get; } + + /// + /// The same request without the checksum extension (…/lib-1.0.jar for …/lib-1.0.jar.sha1); this path itself when it + /// is not a checksum request. + /// + public MavenRequestPath Plain + => ChecksumAlgorithm == null ? this : MavenNames.ParsePath(RelativePath.Substring(0, RelativePath.Length - ChecksumAlgorithm.Length - 1)) ?? this; + + /// For metadata one level above the artifacts (org/acme/maven-metadata.xml, plugin prefixes): the group; else null. + public string? GroupOnly { get; } +} + +/// A file name taken apart. +/// The classifier, or null. +/// The extension without the dot. +/// For a timestamped snapshot build: yyyyMMdd.HHmmss; else null. +/// For a timestamped snapshot build: the build number; else 0. +public sealed record MavenFileParts(string? Classifier, string Extension, string? SnapshotTimestamp, int SnapshotBuild); + +/// +/// The Maven repository layout (group/as/dirs/artifact/version/artifact-version[-classifier].ext) and the one rule +/// every route, page and service uses to accept a name. Group and artifact ids and versions are case-sensitive; characters are +/// limited to those Maven itself uses, so a path can never leave its folder and a name is the same in every database. +/// +public static class MavenNames +{ + /// The storage folder below a repository's prefix. + public const string StorageFolder = "maven"; + + /// The metadata file name. + public const string MetadataFileName = "maven-metadata.xml"; + + /// The version suffix of a snapshot. + public const string SnapshotSuffix = "-SNAPSHOT"; + + /// The checksum extensions, in the order a repository serves them. + public static readonly IReadOnlyList ChecksumAlgorithms = new[] { "sha1", "md5", "sha256", "sha512" }; + + private static readonly Regex GroupSegment = new(@"^[A-Za-z0-9_][A-Za-z0-9_\-]*\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex Identifier = new(@"^[A-Za-z0-9_][A-Za-z0-9_.+\-]*\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex ExtensionPattern = new(@"^[A-Za-z][A-Za-z0-9_.+\-]*\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex ClassifierPattern = new(@"^[A-Za-z0-9_][A-Za-z0-9_+\-]*\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex Timestamp = new(@"^\d{8}\.\d{6}\z", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// The name of an artifact in the access model: group:artifact. + public static string ArtifactName(string groupId, string artifactId) => groupId + ":" + artifactId; + + /// Splits group:artifact; false when it is not one. + public static bool TryParseArtifactName(string? name, out string groupId, out string artifactId) + { + groupId = artifactId = string.Empty; + if (string.IsNullOrEmpty(name)) return false; + + var colon = name.IndexOf(':'); + if (colon <= 0 || colon == name.Length - 1) return false; + + groupId = name.Substring(0, colon); + artifactId = name.Substring(colon + 1); + + return IsValidGroupId(groupId) && IsValidArtifactId(artifactId); + } + + /// A group id: dot-separated segments of letters, digits, underscore and hyphen (it becomes folders). + public static bool IsValidGroupId(string? groupId) + => !string.IsNullOrEmpty(groupId) + && groupId.Length <= Ctx.MaxMavenGroupLength + && groupId.Split('.').All(s => GroupSegment.IsMatch(s)); + + /// An artifact id. + public static bool IsValidArtifactId(string? artifactId) + => !string.IsNullOrEmpty(artifactId) + && artifactId.Length <= Ctx.MaxMavenArtifactLength + && Identifier.IsMatch(artifactId); + + /// A version (a directory name). + public static bool IsValidVersion(string? version) + => !string.IsNullOrEmpty(version) + && version.Length <= Ctx.MaxMavenVersionLength + && Identifier.IsMatch(version); + + /// Whether a version is a snapshot. + public static bool IsSnapshot(string? version) + => version != null && version.EndsWith(SnapshotSuffix, StringComparison.Ordinal); + + /// The folder of a group: org.apache.maven becomes org/apache/maven. + public static string GroupPath(string groupId) => groupId.Replace('.', '/'); + + /// The storage path of a file, relative to the repository's prefix. + public static string StoragePath(string groupId, string artifactId, string version, string fileName) + => StorageFolder + "/" + GroupPath(groupId) + "/" + artifactId + "/" + version + "/" + fileName; + + /// The path a client uses, relative to the repository's maven/ address. + public static string ClientPath(string groupId, string artifactId, string version, string fileName) + => GroupPath(groupId) + "/" + artifactId + "/" + version + "/" + fileName; + + /// Takes a request path (the part after maven/) apart. + /// Null when the path is not a valid Maven path (too short, an invalid character, a name that cannot be a file). + public static MavenRequestPath? ParsePath(string? path) + { + if (string.IsNullOrEmpty(path) || path.Length > 2048) return null; + + var segments = path.Split('/'); + if (segments.Length < 2 || segments.Any(s => s.Length == 0)) return null; + + var fileName = segments[^1]; + if (fileName.Length > Ctx.MaxMavenFileNameLength || !Identifier.IsMatch(fileName)) return null; + + var directories = segments.Take(segments.Length - 1).ToArray(); + if (directories.Any(d => d.Length > Ctx.MaxMavenGroupLength || !Identifier.IsMatch(d))) return null; + + var baseName = fileName; + string? checksum = null; + foreach (var algorithm in ChecksumAlgorithms) + { + if (fileName.Length > algorithm.Length + 1 && fileName.EndsWith("." + algorithm, StringComparison.Ordinal)) + { + checksum = algorithm; + baseName = fileName.Substring(0, fileName.Length - algorithm.Length - 1); + break; + } + } + + if (baseName == MetadataFileName) + { + var candidates = new List(); + if (directories.Length >= 3 && TryGroup(directories.Take(directories.Length - 2), out var versionGroup) + && IsValidArtifactId(directories[^2]) && IsValidVersion(directories[^1])) + { + candidates.Add(new MavenCoordinate(versionGroup, directories[^2], directories[^1])); + } + + if (directories.Length >= 2 && TryGroup(directories.Take(directories.Length - 1), out var artifactGroup) && IsValidArtifactId(directories[^1])) + { + candidates.Add(new MavenCoordinate(artifactGroup, directories[^1], null)); + } + + var groupOnly = TryGroup(directories, out var onlyGroup) ? onlyGroup : null; + if (candidates.Count == 0 && groupOnly == null) return null; + + return new MavenRequestPath(path, MavenPathKind.Metadata, fileName, baseName, checksum, candidates, groupOnly); + } + + if (directories.Length < 3) return null; + if (!TryGroup(directories.Take(directories.Length - 2), out var group) + || !IsValidArtifactId(directories[^2]) + || !IsValidVersion(directories[^1])) + { + return null; + } + + return new MavenRequestPath( + path, + MavenPathKind.File, + fileName, + baseName, + checksum, + new[] { new MavenCoordinate(group, directories[^2], directories[^1]) }, + groupOnly: null); + } + + private static bool TryGroup(IEnumerable directories, out string groupId) + { + var list = directories.ToList(); + groupId = string.Join(".", list); + + // A folder name with a dot would be read as two segments of the group id, so it is not a group folder. + return list.Count > 0 && list.All(d => GroupSegment.IsMatch(d)) && IsValidGroupId(groupId); + } + + /// + /// Takes the file name of the artifact version apart: + /// {artifactId}-{version}[-{classifier}].{extension}, where a snapshot's version may be its timestamped form + /// (1.0-20240101.120000-3 for 1.0-SNAPSHOT). + /// + /// Null when the name does not belong to the artifact and version. + public static MavenFileParts? ParseFileName(string artifactId, string version, string fileName) + { + var prefix = artifactId + "-"; + if (!fileName.StartsWith(prefix, StringComparison.Ordinal)) return null; + + var rest = fileName.Substring(prefix.Length); + string tail; + string? stamp = null; + var build = 0; + + if (rest.StartsWith(version, StringComparison.Ordinal)) + { + tail = rest.Substring(version.Length); + } + else if (IsSnapshot(version)) + { + var baseVersion = version.Substring(0, version.Length - SnapshotSuffix.Length); + var stampStart = baseVersion + "-"; + if (!rest.StartsWith(stampStart, StringComparison.Ordinal)) return null; + + var afterBase = rest.Substring(stampStart.Length); + + // yyyyMMdd.HHmmss-N + if (afterBase.Length < 17 || !Timestamp.IsMatch(afterBase.Substring(0, 15)) || afterBase[15] != '-') return null; + + var digits = 0; + while (16 + digits < afterBase.Length && char.IsAsciiDigit(afterBase[16 + digits])) digits++; + if (digits == 0 || digits > 9 || !int.TryParse(afterBase.AsSpan(16, digits), NumberStyles.None, CultureInfo.InvariantCulture, out build) || build < 1) return null; + + stamp = afterBase.Substring(0, 15); + if (!DateTime.TryParseExact(stamp, "yyyyMMdd.HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) return null; + + tail = afterBase.Substring(16 + digits); + } + else + { + return null; + } + + string? classifier = null; + string extension; + if (tail.StartsWith('.')) + { + extension = tail.Substring(1); + } + else if (tail.StartsWith('-')) + { + var dot = tail.IndexOf('.'); + if (dot < 2) return null; + + classifier = tail.Substring(1, dot - 1); + extension = tail.Substring(dot + 1); + if (!ClassifierPattern.IsMatch(classifier)) return null; + } + else + { + return null; + } + + if (!ExtensionPattern.IsMatch(extension) || extension.Length > Ctx.MaxMavenExtensionLength) return null; + if (classifier != null && classifier.Length > Ctx.MaxMavenClassifierLength) return null; + + return new MavenFileParts(classifier, extension, stamp, build); + } + + /// The content type served for a file of this extension. + public static string ContentTypeOf(string extension) => extension switch + { + "pom" or "xml" => "application/xml", + "jar" or "war" or "ear" => "application/java-archive", + "module" or "json" => "application/json", + "asc" or "txt" => "text/plain", + _ => "application/octet-stream", + }; + + /// + /// Orders Maven versions the way Maven does, close enough for latest, release and the listings: numeric parts + /// numerically, the qualifiers alpha < beta < milestone < rc < snapshot < (release) < sp, others after. + /// + public static int CompareVersions(string? left, string? right) + { + var a = Tokens(left ?? string.Empty); + var b = Tokens(right ?? string.Empty); + for (var i = 0; i < Math.Max(a.Count, b.Count); i++) + { + var result = CompareToken(i < a.Count ? a[i] : null, i < b.Count ? b[i] : null); + if (result != 0) return result; + } + + return string.CompareOrdinal(left, right); + } + + private static List Tokens(string version) + { + var tokens = new List(); + var current = new System.Text.StringBuilder(); + bool? digit = null; + foreach (var c in version.ToLowerInvariant()) + { + if (c is '.' or '-' or '_') + { + if (current.Length > 0) tokens.Add(current.ToString()); + current.Clear(); + digit = null; + continue; + } + + var isDigit = char.IsAsciiDigit(c); + if (digit != null && digit != isDigit) + { + tokens.Add(current.ToString()); + current.Clear(); + } + + current.Append(c); + digit = isDigit; + } + + if (current.Length > 0) tokens.Add(current.ToString()); + + // Trailing zeros and release markers do not count: 1.0 == 1.0.0 == 1.0-final. + while (tokens.Count > 0 && (tokens[^1] is "0" or "final" or "ga" or "release")) tokens.RemoveAt(tokens.Count - 1); + + return tokens; + } + + // A missing token is the release: 1.0 > 1.0-rc1, 1.0 < 1.0.1, 1.0 < 1.0-sp1. + private static int CompareToken(string? x, string? y) + { + if (x == null && y == null) return 0; + if (x == null) return -CompareToken(y, null); + + var numeric = long.TryParse(x, NumberStyles.None, CultureInfo.InvariantCulture, out var number); + if (y == null) return numeric ? (number == 0 ? 0 : 1) : QualifierRank(x) >= QualifierRank(string.Empty) ? 1 : -1; + + var otherNumeric = long.TryParse(y, NumberStyles.None, CultureInfo.InvariantCulture, out var otherNumber); + if (numeric && otherNumeric) return number.CompareTo(otherNumber); + if (numeric) return 1; + if (otherNumeric) return -1; + + var rank = QualifierRank(x).CompareTo(QualifierRank(y)); + + return rank != 0 ? rank : string.CompareOrdinal(x, y); + } + + private static int QualifierRank(string qualifier) => qualifier switch + { + "alpha" or "a" => 1, + "beta" or "b" => 2, + "milestone" or "m" => 3, + "rc" or "cr" => 4, + "snapshot" => 5, + "" => 6, + "sp" => 7, + _ => 8, + }; +} diff --git a/src/BaGet.Core/Formats/Maven/MavenPom.cs b/src/BaGet.Core/Formats/Maven/MavenPom.cs new file mode 100644 index 000000000..d78fc5214 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenPom.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; + +namespace BaGet.Core; + +/// A dependency a POM declares (versions and scopes as written; properties are not resolved). +/// The group id. +/// The artifact id. +/// The version, or null (managed elsewhere). +/// The scope, or null (compile). +/// Whether the dependency is optional. +public sealed record MavenPomDependency(string GroupId, string ArtifactId, string? Version, string? Scope, bool Optional); + +/// What the search and the pages read from a POM. +/// The group id (the parent's when the POM has none). +/// The artifact id. +/// The version (the parent's when the POM has none). +/// The packaging, jar by default. +/// The name. +/// The description. +/// The project url. +/// The parent as group:artifact:version, or null. +/// The declared dependencies, in order. +public sealed record MavenPomInfo( + string? GroupId, + string? ArtifactId, + string? Version, + string Packaging, + string? Name, + string? Description, + string? Url, + string? Parent, + IReadOnlyList Dependencies); + +/// Reads the few facts of a POM that the repository shows and searches. +public static class MavenPom +{ + /// A POM larger than this is stored but not read (a real one is a few kilobytes). + public const int MaxBytes = 2 * 1024 * 1024; + + /// + /// Reads . DTDs are refused (no entity expansion), and the POM's namespace is ignored. + /// + /// Null when the bytes are not an XML document with a project root. + public static MavenPomInfo? TryParse(Stream pom) + { + if (pom == null) throw new ArgumentNullException(nameof(pom)); + + try + { + var settings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + MaxCharactersInDocument = MaxBytes, + IgnoreComments = true, + }; + + using var reader = XmlReader.Create(pom, settings); + var root = XDocument.Load(reader).Root; + if (root == null || root.Name.LocalName != "project") return null; + + var parent = root.Elements().FirstOrDefault(e => e.Name.LocalName == "parent"); + var parentGroup = Text(parent, "groupId"); + var parentVersion = Text(parent, "version"); + + var dependencies = root.Elements().Where(e => e.Name.LocalName == "dependencies") + .SelectMany(d => d.Elements().Where(e => e.Name.LocalName == "dependency")) + .Select(d => new MavenPomDependency( + Text(d, "groupId") ?? string.Empty, + Text(d, "artifactId") ?? string.Empty, + Text(d, "version"), + Text(d, "scope"), + string.Equals(Text(d, "optional"), "true", StringComparison.OrdinalIgnoreCase))) + .Where(d => d.GroupId.Length > 0 && d.ArtifactId.Length > 0) + .Take(500) + .ToList(); + + return new MavenPomInfo( + Text(root, "groupId") ?? parentGroup, + Text(root, "artifactId"), + Text(root, "version") ?? parentVersion, + Text(root, "packaging") ?? "jar", + Text(root, "name"), + Text(root, "description"), + Text(root, "url"), + parent == null ? null : $"{parentGroup}:{Text(parent, "artifactId")}:{parentVersion}", + dependencies); + } + catch (Exception e) when (e is XmlException or InvalidOperationException) + { + return null; + } + } + + private static string? Text(XElement? parent, string name) + { + var value = parent?.Elements().FirstOrDefault(e => e.Name.LocalName == name)?.Value; + value = value == null ? null : string.Join(" ", value.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + + return string.IsNullOrEmpty(value) ? null : value; + } + + /// + /// A POM for a deploy made with only coordinates (the browser upload page): the minimum Maven needs to resolve the + /// artifact. + /// + public static string Generate(string groupId, string artifactId, string version, string packaging, string? name = null, string? description = null) + { + XNamespace ns = "http://maven.apache.org/POM/4.0.0"; + var project = new XElement( + ns + "project", + new XElement(ns + "modelVersion", "4.0.0"), + new XElement(ns + "groupId", groupId), + new XElement(ns + "artifactId", artifactId), + new XElement(ns + "version", version), + new XElement(ns + "packaging", packaging)); + if (!string.IsNullOrWhiteSpace(name)) project.Add(new XElement(ns + "name", name)); + if (!string.IsNullOrWhiteSpace(description)) project.Add(new XElement(ns + "description", description)); + + return new XDocument(new XDeclaration("1.0", "UTF-8", null), project).Declaration + Environment.NewLine + project.ToString() + Environment.NewLine; + } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenRepositoryAdministration.cs b/src/BaGet.Core/Formats/Maven/MavenRepositoryAdministration.cs new file mode 100644 index 000000000..b7e4b7906 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenRepositoryAdministration.cs @@ -0,0 +1,64 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// Changes the settings of a local Maven repository (the administration page). +public interface IMavenRepositoryAdministration +{ + /// The settings of the Maven repository , or null when there is none of that name or format. + Task GetSettingsAsync(string name, CancellationToken cancellationToken); + + /// + /// Saves for the Maven repository and audits it. A stricter policy does not + /// touch what is stored: it applies to later deploys. + /// + /// False when there is no Maven repository of that name. + /// The server is read-only while a database copy runs. + Task SaveSettingsAsync(string name, MavenRepositorySettings settings, string? actor, CancellationToken cancellationToken); +} + +/// over the repositories table. +public class MavenRepositoryAdministration : IMavenRepositoryAdministration +{ + private readonly IContext _context; + private readonly MaintenanceGate _gate; + private readonly SystemTime _time; + + /// The database. + /// The read-only gate. + /// The clock. + public MavenRepositoryAdministration(IContext context, MaintenanceGate gate, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + /// + public async Task GetSettingsAsync(string name, CancellationToken cancellationToken) + { + var row = await _context.Repositories!.AsNoTracking().FirstOrDefaultAsync(r => r.Name == name && r.Format == RepositoryFormat.Maven, cancellationToken).ConfigureAwait(false); + + return row == null ? null : MavenRepositorySettings.Parse(row.Settings); + } + + /// + public async Task SaveSettingsAsync(string name, MavenRepositorySettings settings, string? actor, CancellationToken cancellationToken) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + _gate.ThrowIfClosed(); + + var row = await _context.Repositories!.FirstOrDefaultAsync(r => r.Name == name && r.Format == RepositoryFormat.Maven, cancellationToken).ConfigureAwait(false); + if (row == null || row.Kind != RepositoryKind.Local) return false; + + row.Settings = settings.ToJson(); + AccessAdministration.Audit(_context, _time.UtcNow, actor, "repository.maven-settings", name, new { policy = settings.Policy.ToString(), settings.AllowRedeploy, settings.MaxSnapshotBuilds }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return true; + } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenRepositoryService.cs b/src/BaGet.Core/Formats/Maven/MavenRepositoryService.cs new file mode 100644 index 000000000..91860eb11 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenRepositoryService.cs @@ -0,0 +1,1231 @@ +using System; +using Ctx = BaGet.Core.AbstractContext; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// over the Maven tables and the storage service. Rows live in the repository of the request +/// (the context's query filter and stamping), files under maven/{group}/{artifact}/{version}/{file} of that repository's +/// storage prefix. Checksums are computed once, on the way in, and kept in the file's row; maven-metadata.xml is never +/// stored. +/// +public class MavenRepositoryService : IMavenRepository +{ + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IRepositoryContext _repository; + private readonly IPackageAuthorizationService _authorization; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + private readonly IOptionsSnapshot? _options; + private readonly ArtifactUsageRecorder? _usage; + private readonly IScanGate? _scanGate; + private MavenRepositorySettings? _settings; + + /// The database. + /// Where files are kept. + /// The repository of the request. + /// Decides who may deploy and delete. + /// The clock. + /// The read-only gate, checked before a file is stored or removed. + /// The logger. + /// The Maven:* options. + /// Notes downloads for the retention rules; null records nothing. + /// The vulnerability scanning policy checked before a deploy and told of what was stored. + public MavenRepositoryService( + IContext context, + IStorageService storage, + IRepositoryContext repository, + IPackageAuthorizationService authorization, + SystemTime time, + MaintenanceGate gate, + ILogger logger, + IOptionsSnapshot? options = null, + ArtifactUsageRecorder? usage = null, + IScanGate? scanGate = null) + { + _usage = usage; + _scanGate = scanGate; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _options = options; + } + + private static readonly KeyedLocks FileLocks = new(); + + private long MaxFileBytes => _options?.Value.MaxFileBytes ?? 1024L * 1024 * 1024; + + private string StoragePath(string groupId, string artifactId, string version, string fileName) + => RepositoryStorage.Scope(_repository.Current, MavenNames.StoragePath(groupId, artifactId, version, fileName)); + + /// + public async Task GetSettingsAsync(CancellationToken cancellationToken) + { + if (_settings != null) return _settings; + + var key = _repository.Current.Key; + var json = await _context.Repositories!.AsNoTracking() + .Where(r => r.Key == key) + .Select(r => r.Settings) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + + return _settings = MavenRepositorySettings.Parse(json); + } + + /// + public async Task ProbeAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) + => await HasVersionAsync(groupId, artifactId, version, cancellationToken).ConfigureAwait(false) ? ResolutionOutcome.Stored : ResolutionOutcome.NotFound; + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + public async Task ResolveAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + if (path.Candidates.Count == 0) return null; + if (path.Kind == MavenPathKind.File) return path.Candidates[0]; + + foreach (var candidate in path.Candidates) + { + var artifact = await FindArtifactAsync(candidate.GroupId, candidate.ArtifactId, cancellationToken).ConfigureAwait(false); + if (artifact == null) continue; + + if (candidate.Version == null) return candidate; + + if (await _context.MavenVersions!.AsNoTracking().AnyAsync(v => v.ArtifactKey == artifact.Key && v.Version == candidate.Version, cancellationToken).ConfigureAwait(false)) + { + return candidate; + } + } + + // Nothing stored: the artifact level is the question that gets "not found". + return path.Candidates[^1]; + } + + private Task FindArtifactAsync(string groupId, string artifactId, CancellationToken cancellationToken) + => _context.MavenArtifacts!.AsNoTracking().FirstOrDefaultAsync(a => a.GroupId == groupId && a.ArtifactId == artifactId, cancellationToken); + + /// + public async Task OpenAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + + return path.Kind == MavenPathKind.Metadata + ? await OpenMetadataAsync(path, cancellationToken).ConfigureAwait(false) + : await OpenFileAsync(path, cancellationToken).ConfigureAwait(false); + } + + /// + public Task HeadAsync(MavenRequestPath path, CancellationToken cancellationToken) => OpenAsync(path, cancellationToken); + + private async Task OpenFileAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + var coordinate = path.Candidates[0]; + var artifact = await FindArtifactAsync(coordinate.GroupId, coordinate.ArtifactId, cancellationToken).ConfigureAwait(false); + if (artifact == null) return null; + + var version = await _context.MavenVersions!.AsNoTracking().FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == coordinate.Version, cancellationToken).ConfigureAwait(false); + if (version == null) return null; + + var file = await _context.MavenFiles!.AsNoTracking().FirstOrDefaultAsync(f => f.VersionKey == version.Key && f.FileName == path.BaseName, cancellationToken).ConfigureAwait(false) + ?? await NewestSnapshotBuildAsync(version, coordinate, path.BaseName, cancellationToken).ConfigureAwait(false); + if (file == null) return null; + + if (path.ChecksumAlgorithm != null) + { + var hex = HexOf(file, path.ChecksumAlgorithm); + var bytes = Encoding.ASCII.GetBytes(hex); + + return new MavenDownload(new MemoryStream(bytes, writable: false), bytes.Length, "text/plain", path.FileName, Utc(file.Created)); + } + + var stream = await _storage.GetAsync(StoragePath(coordinate.GroupId, coordinate.ArtifactId, coordinate.Version!, file.FileName!), cancellationToken).ConfigureAwait(false); + if (stream == null) return null; + + // For the retention rules: the version was just downloaded. + _usage?.Touch(_repository.Current.Key, MavenNames.ArtifactName(coordinate.GroupId, coordinate.ArtifactId), coordinate.Version); + + return new MavenDownload(stream, file.Size, MavenNames.ContentTypeOf(LastExtension(file.Extension!)), file.FileName!, Utc(file.Created)) + { + Sha1 = file.Sha1, + Md5 = file.Md5, + Sha256 = file.Sha256, + }; + } + + // "a-1.0-SNAPSHOT.jar" (what a Maven 2 client asks for) is the newest timestamped build of the same classifier and extension. + private async Task NewestSnapshotBuildAsync(MavenVersion version, MavenCoordinate coordinate, string requested, CancellationToken cancellationToken) + { + if (!MavenNames.IsSnapshot(version.Version)) return null; + + var parts = MavenNames.ParseFileName(coordinate.ArtifactId, version.Version!, requested); + if (parts == null || parts.SnapshotTimestamp != null) return null; + + var builds = await _context.MavenFiles!.AsNoTracking() + .Where(f => f.VersionKey == version.Key && f.SnapshotTimestamp != null && f.Extension == parts.Extension && f.Classifier == parts.Classifier) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + + return builds.OrderByDescending(f => f.SnapshotTimestamp, StringComparer.Ordinal).ThenByDescending(f => f.SnapshotBuild).FirstOrDefault(); + } + + private async Task OpenMetadataAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + foreach (var candidate in path.Candidates) + { + var artifact = await FindArtifactAsync(candidate.GroupId, candidate.ArtifactId, cancellationToken).ConfigureAwait(false); + if (artifact == null) continue; + + string xml; + if (candidate.Version == null) + { + var versions = await _context.MavenVersions!.AsNoTracking().Where(v => v.ArtifactKey == artifact.Key).Select(v => v.Version!).ToListAsync(cancellationToken).ConfigureAwait(false); + if (versions.Count == 0) continue; + + xml = MavenMetadata.ForArtifact(candidate.GroupId, candidate.ArtifactId, versions, Utc(artifact.Modified)); + } + else + { + var version = await _context.MavenVersions!.AsNoTracking().FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == candidate.Version, cancellationToken).ConfigureAwait(false); + if (version == null) continue; + + var files = await _context.MavenFiles!.AsNoTracking().Where(f => f.VersionKey == version.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + xml = MavenMetadata.ForVersion( + candidate.GroupId, + candidate.ArtifactId, + candidate.Version, + files.Select(f => new MavenFileInfo(f.FileName!, f.Classifier, f.Extension!, f.SnapshotTimestamp, f.SnapshotBuild, Utc(f.Created))), + Utc(version.Modified)); + } + + var content = Encoding.UTF8.GetBytes(xml); + var modified = candidate.Version == null ? artifact.Modified : DateTime.UtcNow; + if (path.ChecksumAlgorithm != null) + { + var hex = Convert.ToHexString(HashOf(path.ChecksumAlgorithm, content)).ToLowerInvariant(); + var text = Encoding.ASCII.GetBytes(hex); + + return new MavenDownload(new MemoryStream(text, writable: false), text.Length, "text/plain", path.FileName, Utc(modified)); + } + + return new MavenDownload(new MemoryStream(content, writable: false), content.Length, "application/xml", path.FileName, Utc(modified)) + { + Sha1 = Convert.ToHexString(SHA1.HashData(content)).ToLowerInvariant(), + Md5 = Convert.ToHexString(MD5.HashData(content)).ToLowerInvariant(), + Sha256 = Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant(), + }; + } + + return null; + } + + private static byte[] HashOf(string algorithm, byte[] content) => algorithm switch + { + "md5" => MD5.HashData(content), + "sha256" => SHA256.HashData(content), + "sha512" => SHA512.HashData(content), + _ => SHA1.HashData(content), + }; + + private static string HexOf(MavenFile file, string algorithm) => algorithm switch + { + "md5" => file.Md5!, + "sha256" => file.Sha256!, + "sha512" => file.Sha512!, + _ => file.Sha1!, + }; + + // The extension of "jar.asc" for the content type: the signature is text, the rest follows the last part. + private static string LastExtension(string extension) + { + var dot = extension.LastIndexOf('.'); + + return dot < 0 ? extension : extension.Substring(dot + 1); + } + + private static DateTime Utc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc); + + /// + public async Task SearchAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) + { + IQueryable query = _context.MavenArtifacts!.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(text)) + { + var needle = text.Trim().ToLowerInvariant(); + query = query.Where(a => + (a.GroupId!.ToLower() + ":" + a.ArtifactId!.ToLower()).Contains(needle) + || _context.MavenVersions!.Any(v => v.ArtifactKey == a.Key + && ((v.Name != null && v.Name.ToLower().Contains(needle)) || (v.Description != null && v.Description.ToLower().Contains(needle))))); + } + + skip = Math.Max(skip, 0); + take = Math.Clamp(take, 0, 250); + + var all = await query.OrderBy(a => a.GroupId).ThenBy(a => a.ArtifactId) + .Select(a => new { a.Key, a.GroupId, a.ArtifactId, a.Modified }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + + // Only the artifacts the caller may read count; the names are filtered and paged here. + var visible = new List<(int Key, string Group, string Artifact, DateTime Modified)>(); + foreach (var row in all) + { + if (canRead == null || await canRead(MavenNames.ArtifactName(row.GroupId!, row.ArtifactId!), cancellationToken).ConfigureAwait(false)) + { + visible.Add((row.Key, row.GroupId!, row.ArtifactId!, row.Modified)); + } + } + + var page = visible.Skip(skip).Take(take).ToList(); + var keys = page.Select(p => p.Key).ToList(); + var versions = await _context.MavenVersions!.AsNoTracking().Where(v => keys.Contains(v.ArtifactKey)).ToListAsync(cancellationToken).ConfigureAwait(false); + + var hits = new List(); + foreach (var item in page) + { + var own = versions.Where(v => v.ArtifactKey == item.Key).OrderByDescending(v => v.Version, Comparer.Create(MavenNames.CompareVersions)).ToList(); + var latest = own.FirstOrDefault(v => !v.IsSnapshot) ?? own.FirstOrDefault(); + + hits.Add(new MavenSearchHit(item.Group, item.Artifact, latest?.Version, latest?.Name, latest?.Description, Utc(item.Modified))); + } + + return new MavenSearchPage(visible.Count, hits); + } + + /// + public async Task GetArtifactAsync(string groupId, string artifactId, CancellationToken cancellationToken) + { + var artifact = await FindArtifactAsync(groupId, artifactId, cancellationToken).ConfigureAwait(false); + if (artifact == null) return null; + + var versions = await _context.MavenVersions!.AsNoTracking().Where(v => v.ArtifactKey == artifact.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var keys = versions.Select(v => v.Key).ToList(); + var files = await _context.MavenFiles!.AsNoTracking() + .Where(f => keys.Contains(f.VersionKey)) + .Select(f => new { f.VersionKey, f.Size, f.SnapshotTimestamp, f.SnapshotBuild }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + + var summaries = versions + .OrderByDescending(v => v.Version, Comparer.Create(MavenNames.CompareVersions)) + .Select(v => + { + var own = files.Where(f => f.VersionKey == v.Key).ToList(); + + return new MavenVersionSummary( + v.Version!, + v.IsSnapshot, + v.Name, + v.Description, + v.Packaging, + Utc(v.Created), + Utc(v.Modified), + own.Count, + own.Sum(f => f.Size), + own.Where(f => f.SnapshotTimestamp != null).Select(f => (f.SnapshotTimestamp, f.SnapshotBuild)).Distinct().Count()); + }) + .ToList(); + + return new MavenArtifactInfo(artifact.GroupId!, artifact.ArtifactId!, Utc(artifact.Created), Utc(artifact.Modified), summaries); + } + + /// + public async Task GetVersionAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) + { + var artifact = await FindArtifactAsync(groupId, artifactId, cancellationToken).ConfigureAwait(false); + if (artifact == null) return null; + + var row = await _context.MavenVersions!.AsNoTracking().FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == version, cancellationToken).ConfigureAwait(false); + if (row == null) return null; + + var files = await _context.MavenFiles!.AsNoTracking().Where(f => f.VersionKey == row.Key).OrderBy(f => f.FileName).ToListAsync(cancellationToken).ConfigureAwait(false); + + var summary = new MavenVersionSummary( + row.Version!, + row.IsSnapshot, + row.Name, + row.Description, + row.Packaging, + Utc(row.Created), + Utc(row.Modified), + files.Count, + files.Sum(f => f.Size), + files.Where(f => f.SnapshotTimestamp != null).Select(f => (f.SnapshotTimestamp, f.SnapshotBuild)).Distinct().Count()); + + // The POM shown is the newest build's for a snapshot, the version's own for a release. + var pomFile = files + .Where(f => f.Classifier == null && f.Extension == "pom") + .OrderByDescending(f => f.SnapshotTimestamp, StringComparer.Ordinal).ThenByDescending(f => f.SnapshotBuild) + .FirstOrDefault(); + + MavenPomInfo? pom = null; + string? pomText = null; + if (pomFile != null && pomFile.Size <= MavenPom.MaxBytes) + { + using var stream = await _storage.GetAsync(StoragePath(groupId, artifactId, version, pomFile.FileName!), cancellationToken).ConfigureAwait(false); + if (stream != null) + { + using var buffer = new MemoryStream(); + await stream.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); + buffer.Position = 0; + pomText = new UTF8Encoding(false).GetString(buffer.ToArray()); + buffer.Position = 0; + pom = MavenPom.TryParse(buffer); + } + } + + return new MavenVersionDetail( + summary, + files.Select(f => new MavenFileDetail(f.FileName!, f.Classifier, f.Extension!, f.Size, f.Sha1!, f.Md5!, f.Sha256!, f.Sha512!, Utc(f.Created), f.SnapshotTimestamp, f.SnapshotBuild)).ToList(), + pom, + pomText); + } + + // ---- authorization -------------------------------------------------------------------------------------------------- + + private async Task DenyAsync(BaGetPrincipal? caller, PackageAction action, string name, CancellationToken cancellationToken) + { + if (caller == null) return MavenResult.Fail(MavenStatus.Unauthorized, "Authentication is required."); + + if (_repository.Current.Kind != RepositoryKind.Local) + { + return MavenResult.Fail(MavenStatus.Forbidden, "This repository takes no changes."); + } + + if (!await _authorization.AuthorizeAsync(caller, action, name, cancellationToken).ConfigureAwait(false)) + { + return MavenResult.Fail(MavenStatus.Forbidden, $"You are not allowed to {(action == PackageAction.Push ? "deploy to" : "delete from")} {name}."); + } + + return null; + } + + // ---- writes --------------------------------------------------------------------------------------------------------- + + /// + /// The scanning check would make for this file, without storing anything: a replication that replaces a + /// stored file asks first, so a refusal cannot cost the copy it was to replace. + /// + /// The scanning policy refuses the file. + internal async Task PreflightReplacementAsync(MavenRequestPath path, Stream content, CancellationToken cancellationToken) + { + if (path.Kind == MavenPathKind.Metadata || path.ChecksumAlgorithm != null || path.Candidates.Count == 0) return; + if (_scanGate == null || !_scanGate.Enabled || !await _scanGate.BlocksDeploysAsync(cancellationToken).ConfigureAwait(false)) return; + + var coordinate = path.Candidates[0]; + var parts = MavenNames.ParseFileName(coordinate.ArtifactId, coordinate.Version!, path.BaseName); + if (parts == null) return; + + MavenPomInfo? pom = null; + if (parts.Classifier == null && parts.Extension == "pom" && content.Length <= MavenPom.MaxBytes) + { + content.Position = 0; + pom = MavenPom.TryParse(content); + content.Position = 0; + } + + await _scanGate.CheckDeployAsync(MavenScanComponents.Of(coordinate.GroupId, coordinate.ArtifactId, coordinate.Version!, pom), cancellationToken).ConfigureAwait(false); + } + + /// + public async Task PutAsync(BaGetPrincipal? caller, MavenRequestPath path, Stream content, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + if (content == null) throw new ArgumentNullException(nameof(content)); + + if (path.Kind == MavenPathKind.Metadata) + { + // A client uploads its own maven-metadata.xml (and checksums) after the files. The server generates it from what is + // stored, so the upload is acknowledged and dropped; it is still a deploy, so the caller must be allowed to deploy. + MavenResult? denied = null; + foreach (var candidate in path.Candidates.Select(c => c.Name).Distinct()) + { + denied = await DenyAsync(caller, PackageAction.Push, candidate, cancellationToken).ConfigureAwait(false); + if (denied == null) break; + } + + if (path.Candidates.Count == 0) + { + // Group level (plugin prefixes): any deployer may send it; nothing is stored. + denied = caller == null ? MavenResult.Fail(MavenStatus.Unauthorized, "Authentication is required.") : null; + } + + return denied ?? MavenResult.Created("maven-metadata.xml is generated by the repository; the upload was ignored."); + } + + var coordinate = path.Candidates[0]; + var name = coordinate.Name; + var checkOnly = path.ChecksumAlgorithm != null; + + var refusal = await DenyAsync(caller, PackageAction.Push, name, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var parts = MavenNames.ParseFileName(coordinate.ArtifactId, coordinate.Version!, path.BaseName); + if (parts == null) + { + return MavenResult.Fail(MavenStatus.Invalid, $"'{path.BaseName}' is not a file of {coordinate.ArtifactId} {coordinate.Version}: expected {coordinate.ArtifactId}-{coordinate.Version}[-classifier].extension."); + } + + if (checkOnly) return await CheckChecksumAsync(coordinate, path, content, cancellationToken).ConfigureAwait(false); + + return await StoreAsync(caller, coordinate, path.BaseName, parts, content, cancellationToken).ConfigureAwait(false); + } + + // The client sends ".sha1" after the file; it must say what the server computed. A checksum for a file that is not + // stored (yet) is acknowledged: the server serves its own. + private async Task CheckChecksumAsync(MavenCoordinate coordinate, MavenRequestPath path, Stream content, CancellationToken cancellationToken) + { + var buffer = new byte[1024]; + var read = 0; + int n; + while (read < buffer.Length && (n = await content.ReadAsync(buffer.AsMemory(read), cancellationToken).ConfigureAwait(false)) > 0) read += n; + + var sent = Encoding.ASCII.GetString(buffer, 0, read).Trim(); + var space = sent.IndexOfAny(new[] { ' ', '\t', '\r', '\n' }); + if (space > 0) sent = sent.Substring(0, space); + + var artifact = await FindArtifactAsync(coordinate.GroupId, coordinate.ArtifactId, cancellationToken).ConfigureAwait(false); + var version = artifact == null ? null : await _context.MavenVersions!.AsNoTracking().FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == coordinate.Version, cancellationToken).ConfigureAwait(false); + var file = version == null ? null : await _context.MavenFiles!.AsNoTracking().FirstOrDefaultAsync(f => f.VersionKey == version.Key && f.FileName == path.BaseName, cancellationToken).ConfigureAwait(false); + if (file == null) return MavenResult.Created("The file is not stored yet; the repository serves the checksums it computes."); + + if (!string.Equals(sent, HexOf(file, path.ChecksumAlgorithm!), StringComparison.OrdinalIgnoreCase)) + { + return MavenResult.Fail(MavenStatus.Invalid, $"The {path.ChecksumAlgorithm} checksum does not match the stored file {path.BaseName}."); + } + + return MavenResult.Created(); + } + + internal sealed class Spooled : IDisposable + { + public Spooled(FileStream file, long length, string sha1, string md5, string sha256, string sha512) + { + File = file; + Length = length; + Sha1 = sha1; + Md5 = md5; + Sha256 = sha256; + Sha512 = sha512; + } + + public FileStream File { get; } + + public long Length { get; } + + public string Sha1 { get; } + + public string Md5 { get; } + + public string Sha256 { get; } + + public string Sha512 { get; } + + public void Dispose() => File.Dispose(); + } + + // Copies the body to a temporary file (deleted on close) while hashing it; null when it is larger than the limit. + internal static async Task SpoolAsync(Stream body, long limit, CancellationToken cancellationToken) + { + var file = new FileStream( + Path.Combine(Path.GetTempPath(), "baget-maven-" + Guid.NewGuid().ToString("N")), + FileMode.CreateNew, + FileAccess.ReadWrite, + FileShare.None, + bufferSize: 81920, + FileOptions.Asynchronous | FileOptions.DeleteOnClose | FileOptions.SequentialScan); + + try + { + using var sha1 = IncrementalHash.CreateHash(HashAlgorithmName.SHA1); + using var md5 = IncrementalHash.CreateHash(HashAlgorithmName.MD5); + using var sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using var sha512 = IncrementalHash.CreateHash(HashAlgorithmName.SHA512); + + var buffer = new byte[81920]; + long total = 0; + int read; + while ((read = await body.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false)) > 0) + { + total += read; + if (limit > 0 && total > limit) + { + file.Dispose(); + + return null; + } + + sha1.AppendData(buffer, 0, read); + md5.AppendData(buffer, 0, read); + sha256.AppendData(buffer, 0, read); + sha512.AppendData(buffer, 0, read); + await file.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + } + + await file.FlushAsync(cancellationToken).ConfigureAwait(false); + file.Position = 0; + + return new Spooled( + file, + total, + Convert.ToHexString(sha1.GetHashAndReset()).ToLowerInvariant(), + Convert.ToHexString(md5.GetHashAndReset()).ToLowerInvariant(), + Convert.ToHexString(sha256.GetHashAndReset()).ToLowerInvariant(), + Convert.ToHexString(sha512.GetHashAndReset()).ToLowerInvariant()); + } + catch + { + file.Dispose(); + throw; + } + } + + private async Task StoreAsync( + BaGetPrincipal? caller, + MavenCoordinate coordinate, + string fileName, + MavenFileParts parts, + Stream body, + CancellationToken cancellationToken) + { + var version = coordinate.Version!; + var name = coordinate.Name; + var settings = await GetSettingsAsync(cancellationToken).ConfigureAwait(false); + + if (!settings.Accepts(version)) + { + return MavenResult.Fail( + MavenStatus.Conflict, + MavenNames.IsSnapshot(version) + ? "This repository takes release versions only; a -SNAPSHOT version was refused." + : "This repository takes -SNAPSHOT versions only; a release version was refused."); + } + + var artifact = await FindArtifactAsync(coordinate.GroupId, coordinate.ArtifactId, cancellationToken).ConfigureAwait(false); + var existed = false; + if (artifact == null) + { + // Names are case-sensitive, but a file system that is not (Windows, macOS) would keep both spellings in one folder: + // a name that differs from an existing one only in letter case is refused, whatever the store. + var group = coordinate.GroupId.ToLowerInvariant(); + var artifactId = coordinate.ArtifactId.ToLowerInvariant(); + if (await _context.MavenArtifacts!.AsNoTracking().AnyAsync(a => a.GroupId!.ToLower() == group && a.ArtifactId!.ToLower() == artifactId, cancellationToken).ConfigureAwait(false)) + { + return MavenResult.Fail(MavenStatus.Conflict, $"{name} differs only in letter case from an artifact that exists in this repository."); + } + } + else + { + var versionKey = await _context.MavenVersions!.AsNoTracking().Where(v => v.ArtifactKey == artifact.Key && v.Version == version).Select(v => (int?)v.Key).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (versionKey == null) + { + var lowerVersion = version.ToLowerInvariant(); + if (await _context.MavenVersions!.AsNoTracking().AnyAsync(v => v.ArtifactKey == artifact.Key && v.Version!.ToLower() == lowerVersion, cancellationToken).ConfigureAwait(false)) + { + return MavenResult.Fail(MavenStatus.Conflict, $"Version {version} of {name} differs only in letter case from a version that exists."); + } + } + else + { + existed = await _context.MavenFiles!.AsNoTracking().AnyAsync(f => f.VersionKey == versionKey && f.FileName == fileName, cancellationToken).ConfigureAwait(false); + var lowerFile = fileName.ToLowerInvariant(); + if (!existed && await _context.MavenFiles!.AsNoTracking().AnyAsync(f => f.VersionKey == versionKey && f.FileName!.ToLower() == lowerFile, cancellationToken).ConfigureAwait(false)) + { + return MavenResult.Fail(MavenStatus.Conflict, $"{fileName} differs only in letter case from a file that exists in {name} {version}."); + } + } + } + + if (existed && !MavenNames.IsSnapshot(version)) + { + if (!settings.AllowRedeploy) + { + return MavenResult.Fail(MavenStatus.Conflict, $"{fileName} already exists in {name} {version}, and this repository does not allow a release to be deployed again."); + } + + // Replacing a released file is a deletion of the old one as well (Artifactory's Delete/Overwrite). + var overwrite = await DenyAsync(caller, PackageAction.Manage, name, cancellationToken).ConfigureAwait(false); + if (overwrite != null) return overwrite; + } + + _gate.ThrowIfClosed(); + + var limit = MaxFileBytes; + using var spooled = await SpoolAsync(body, limit, cancellationToken).ConfigureAwait(false); + if (spooled == null) return MavenResult.Fail(MavenStatus.TooLarge, $"The file is larger than {limit} bytes."); + + MavenPomInfo? pom = null; + if (parts.Classifier == null && parts.Extension == "pom" && spooled.Length <= MavenPom.MaxBytes) + { + pom = MavenPom.TryParse(spooled.File); + spooled.File.Position = 0; + } + + // The scanning policy of the repository may refuse an artifact with known vulnerabilities (ScanBlockedException, 403): a + // POM brings its dependencies, any other file the artifact itself. + if (_scanGate != null && _scanGate.Enabled && await _scanGate.BlocksDeploysAsync(cancellationToken).ConfigureAwait(false)) + { + await _scanGate.CheckDeployAsync(MavenScanComponents.Of(coordinate.GroupId, coordinate.ArtifactId, version, pom), cancellationToken).ConfigureAwait(false); + } + + var path = StoragePath(coordinate.GroupId, coordinate.ArtifactId, version, fileName); + + // One deploy of a file at a time in this process: a deploy that finds a file at the path cannot tell a leftover from a + // concurrent deploy's file whose row is not written yet, and replacing the latter would leave its row with no file (or the + // loser, refused afterwards, would delete the only copy). Under the lock the row decides, so a loser is refused untouched. + // Deploys on other nodes sharing the store are not fenced (docs/maven-repositories.md). + using var deployLock = await FileLocks.LockAsync(path, cancellationToken).ConfigureAwait(false); + if (!existed && !MavenNames.IsSnapshot(version)) + { + var rowNow = await (from f in _context.MavenFiles!.AsNoTracking() + join v in _context.MavenVersions!.AsNoTracking() on f.VersionKey equals v.Key + join a in _context.MavenArtifacts!.AsNoTracking() on v.ArtifactKey equals a.Key + where f.FileName == fileName && v.Version == version && a.GroupId == coordinate.GroupId && a.ArtifactId == coordinate.ArtifactId + select f.Key).AnyAsync(cancellationToken).ConfigureAwait(false); + if (rowNow) + { + if (!settings.AllowRedeploy) + { + return MavenResult.Fail(MavenStatus.Conflict, $"{fileName} already exists in {name} {version}, and this repository does not allow a release to be deployed again."); + } + + var overwriteNow = await DenyAsync(caller, PackageAction.Manage, name, cancellationToken).ConfigureAwait(false); + if (overwriteNow != null) return overwriteNow; + existed = true; + } + } + + var put = await _storage.PutAsync(path, spooled.File, MavenNames.ContentTypeOf(LastExtension(parts.Extension)), cancellationToken).ConfigureAwait(false); + if (put == StoragePutResult.Conflict) + { + // An earlier file at the path (a replaced release, or a leftover of an attempt that never got its row). + await _storage.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + spooled.File.Position = 0; + put = await _storage.PutAsync(path, spooled.File, MavenNames.ContentTypeOf(LastExtension(parts.Extension)), cancellationToken).ConfigureAwait(false); + } + + var storedByThisCall = put == StoragePutResult.Success; + var now = _time.UtcNow; + var isNewArtifact = false; + MavenVersion? versionRow = null; + + for (var attempt = 0; ; attempt++) + { + try + { + await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + + var row = await _context.MavenArtifacts!.FirstOrDefaultAsync(a => a.GroupId == coordinate.GroupId && a.ArtifactId == coordinate.ArtifactId, cancellationToken).ConfigureAwait(false); + isNewArtifact = row == null; + if (row == null) + { + row = new MavenArtifact { GroupId = coordinate.GroupId, ArtifactId = coordinate.ArtifactId, Created = now, Modified = now }; + _context.MavenArtifacts!.Add(row); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + versionRow = await _context.MavenVersions!.FirstOrDefaultAsync(v => v.ArtifactKey == row.Key && v.Version == version, cancellationToken).ConfigureAwait(false); + if (versionRow == null) + { + versionRow = new MavenVersion { ArtifactKey = row.Key, Version = version, IsSnapshot = MavenNames.IsSnapshot(version), Created = now, Modified = now }; + _context.MavenVersions!.Add(versionRow); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + var file = await _context.MavenFiles!.FirstOrDefaultAsync(f => f.VersionKey == versionRow.Key && f.FileName == fileName, cancellationToken).ConfigureAwait(false); + if (file != null && !MavenNames.IsSnapshot(version) && !settings.AllowRedeploy) + { + // A concurrent deploy of the same release file won. + if (storedByThisCall && !existed) await TryDeleteAsync(path).ConfigureAwait(false); + + return MavenResult.Fail(MavenStatus.Conflict, $"{fileName} already exists in {name} {version}."); + } + + if (file == null) + { + file = new MavenFile { VersionKey = versionRow.Key, FileName = fileName }; + _context.MavenFiles!.Add(file); + } + + file.Classifier = parts.Classifier; + file.Extension = parts.Extension; + file.SnapshotTimestamp = parts.SnapshotTimestamp; + file.SnapshotBuild = parts.SnapshotBuild; + file.Size = spooled.Length; + file.Sha1 = spooled.Sha1; + file.Md5 = spooled.Md5; + file.Sha256 = spooled.Sha256; + file.Sha512 = spooled.Sha512; + file.Created = now; + + if (pom != null) + { + versionRow.Packaging = Cut(pom.Packaging, Ctx.MaxMavenPackagingLength); + versionRow.Name = Cut(pom.Name, Ctx.MaxMavenNameLength); + versionRow.Description = Cut(pom.Description, Ctx.MaxMavenDescriptionLength); + } + + versionRow.Modified = now; + row.Modified = now; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + break; + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e) && attempt < 2) + { + // A concurrent deploy created the artifact or version first: the rolled-back attempt left tracked entities + // that no longer exist, so look again and add to the winner's rows. + (_context as DbContext)?.ChangeTracker.Clear(); + } + catch + { + if (storedByThisCall && !existed) await TryDeleteAsync(path).ConfigureAwait(false); + + throw; + } + } + + if (isNewArtifact) await _authorization.OnPushedAsync(caller!, name, isNewId: true, cancellationToken).ConfigureAwait(false); + + if (parts.SnapshotTimestamp != null && settings.MaxSnapshotBuilds > 0) + { + await PruneSnapshotsAsync(coordinate, versionRow!.Key, settings.MaxSnapshotBuilds, cancellationToken).ConfigureAwait(false); + } + + if (_scanGate != null) await _scanGate.RegisterStoredAsync(name, version, cancellationToken, contentChanged: IsScannedFile(parts)).ConfigureAwait(false); + + return MavenResult.Created($"Deployed {fileName}.", name); + } + + /// The scan reads only the main POM, so any other file of the version says nothing new to the scanner. + private static bool IsScannedFile(MavenFileParts parts) => parts.Classifier == null && parts.Extension == "pom"; + + private static string? Cut(string? value, int length) + => string.IsNullOrWhiteSpace(value) ? null : value.Length <= length ? value : value.Substring(0, length); + + private async Task TryDeleteAsync(string path) + { + try + { + await _storage.DeleteAsync(path, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "Could not delete the Maven file {Path}", path); + } + } + + /// + public async Task DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken) + { + if (deployment == null) throw new ArgumentNullException(nameof(deployment)); + + var groupId = deployment.GroupId?.Trim() ?? string.Empty; + var artifactId = deployment.ArtifactId?.Trim() ?? string.Empty; + var version = deployment.Version?.Trim() ?? string.Empty; + if (!MavenNames.IsValidGroupId(groupId)) return MavenResult.Fail(MavenStatus.Invalid, "The group id is not valid: use letters, digits, '_' and '-' in dot-separated parts."); + if (!MavenNames.IsValidArtifactId(artifactId)) return MavenResult.Fail(MavenStatus.Invalid, "The artifact id is not valid."); + if (!MavenNames.IsValidVersion(version)) return MavenResult.Fail(MavenStatus.Invalid, "The version is not valid."); + if (deployment.File == null && deployment.Pom == null) return MavenResult.Fail(MavenStatus.Invalid, "Choose a file or a POM to deploy."); + + var packaging = string.IsNullOrWhiteSpace(deployment.Packaging) ? "jar" : deployment.Packaging.Trim(); + var extension = string.IsNullOrWhiteSpace(deployment.Extension) ? packaging : deployment.Extension.Trim().TrimStart('.'); + var classifier = string.IsNullOrWhiteSpace(deployment.Classifier) ? null : deployment.Classifier.Trim(); + var coordinate = new MavenCoordinate(groupId, artifactId, version); + + // A snapshot is stored as a timestamped build, as 'mvn deploy' stores it; the build number follows the stored ones. + string stem; + if (MavenNames.IsSnapshot(version)) + { + var build = 1; + var artifact = await FindArtifactAsync(groupId, artifactId, cancellationToken).ConfigureAwait(false); + var versionKey = artifact == null ? null : await _context.MavenVersions!.AsNoTracking().Where(v => v.ArtifactKey == artifact.Key && v.Version == version).Select(v => (int?)v.Key).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (versionKey != null) + { + build = (await _context.MavenFiles!.AsNoTracking().Where(f => f.VersionKey == versionKey).Select(f => (int?)f.SnapshotBuild).MaxAsync(cancellationToken).ConfigureAwait(false) ?? 0) + 1; + } + + stem = $"{version.Substring(0, version.Length - MavenNames.SnapshotSuffix.Length)}-{_time.UtcNow.ToString("yyyyMMdd.HHmmss", CultureInfo.InvariantCulture)}-{build.ToString(CultureInfo.InvariantCulture)}"; + } + else + { + stem = version; + } + + var files = new List<(string Name, Stream Content)>(); + MemoryStream? generated = null; + try + { + if (deployment.File != null) files.Add(($"{artifactId}-{stem}{(classifier == null ? string.Empty : "-" + classifier)}.{extension}", deployment.File)); + + if (deployment.Pom != null) + { + files.Add(($"{artifactId}-{stem}.pom", deployment.Pom)); + } + else if (classifier == null && !(extension == "pom" && deployment.File != null)) + { + generated = new MemoryStream(new UTF8Encoding(false).GetBytes(MavenPom.Generate(groupId, artifactId, version, packaging))); + files.Add(($"{artifactId}-{stem}.pom", generated)); + } + + MavenResult last = MavenResult.Fail(MavenStatus.Invalid, "Nothing to deploy."); + foreach (var (fileName, content) in files) + { + var parts = MavenNames.ParseFileName(artifactId, version, fileName); + if (parts == null) return MavenResult.Fail(MavenStatus.Invalid, $"'{fileName}' is not a valid Maven file name: check the classifier and the extension."); + + var denied = await DenyAsync(caller, PackageAction.Push, coordinate.Name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + last = await StoreAsync(caller, coordinate, fileName, parts, content, cancellationToken).ConfigureAwait(false); + if (!last.Succeeded) return last; + } + + return MavenResult.Created($"Deployed {coordinate.Name} {version}.", coordinate.Name); + } + finally + { + generated?.Dispose(); + } + } + + // ---- cache support (RemoteMavenRepository) ---------------------------------------------------------------------------- + + /// + /// Keeps a file a remote repository fetched from its upstream: the bytes under maven/… and the artifact, version and file + /// rows, exactly as a deployed file is kept (so counting, search, the pages, access and the database copy need nothing new). + /// No caller, policy or ownership applies: the upstream decides what exists. A file that is already stored (a concurrent request + /// won) is left as it is. Refused while the maintenance gate is closed, before anything is written. + /// + internal async Task StoreCachedAsync(MavenCoordinate coordinate, string fileName, MavenFileParts parts, Spooled spooled, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + + var version = coordinate.Version!; + MavenPomInfo? pom = null; + if (parts.Classifier == null && parts.Extension == "pom" && spooled.Length <= MavenPom.MaxBytes) + { + pom = MavenPom.TryParse(spooled.File); + } + + spooled.File.Position = 0; + + var path = StoragePath(coordinate.GroupId, coordinate.ArtifactId, version, fileName); + var contentType = MavenNames.ContentTypeOf(LastExtension(parts.Extension)); + var put = await _storage.PutAsync(path, spooled.File, contentType, cancellationToken).ConfigureAwait(false); + if (put == StoragePutResult.Conflict) + { + // A leftover of an attempt that never got its row. + await _storage.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + spooled.File.Position = 0; + put = await _storage.PutAsync(path, spooled.File, contentType, cancellationToken).ConfigureAwait(false); + } + + var storedByThisCall = put == StoragePutResult.Success; + var now = _time.UtcNow; + + for (var attempt = 0; ; attempt++) + { + try + { + await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + + var artifact = await _context.MavenArtifacts!.FirstOrDefaultAsync(a => a.GroupId == coordinate.GroupId && a.ArtifactId == coordinate.ArtifactId, cancellationToken).ConfigureAwait(false); + if (artifact == null) + { + artifact = new MavenArtifact { GroupId = coordinate.GroupId, ArtifactId = coordinate.ArtifactId, Created = now, Modified = now }; + _context.MavenArtifacts!.Add(artifact); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + var versionRow = await _context.MavenVersions!.FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == version, cancellationToken).ConfigureAwait(false); + if (versionRow == null) + { + versionRow = new MavenVersion { ArtifactKey = artifact.Key, Version = version, IsSnapshot = MavenNames.IsSnapshot(version), Created = now, Modified = now }; + _context.MavenVersions!.Add(versionRow); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + if (await _context.MavenFiles!.AnyAsync(f => f.VersionKey == versionRow.Key && f.FileName == fileName, cancellationToken).ConfigureAwait(false)) + { + // A concurrent request stored the same file first; its bytes are the upstream's too. + return; + } + + _context.MavenFiles!.Add(new MavenFile + { + VersionKey = versionRow.Key, + FileName = fileName, + Classifier = parts.Classifier, + Extension = parts.Extension, + SnapshotTimestamp = parts.SnapshotTimestamp, + SnapshotBuild = parts.SnapshotBuild, + Size = spooled.Length, + Sha1 = spooled.Sha1, + Md5 = spooled.Md5, + Sha256 = spooled.Sha256, + Sha512 = spooled.Sha512, + Created = now, + }); + + if (pom != null) + { + versionRow.Packaging = Cut(pom.Packaging, Ctx.MaxMavenPackagingLength); + versionRow.Name = Cut(pom.Name, Ctx.MaxMavenNameLength); + versionRow.Description = Cut(pom.Description, Ctx.MaxMavenDescriptionLength); + } + + versionRow.Modified = now; + artifact.Modified = now; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + if (_scanGate != null) await _scanGate.RegisterStoredAsync(coordinate.Name, version, cancellationToken, contentChanged: IsScannedFile(parts)).ConfigureAwait(false); + + return; + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e) && attempt < 2) + { + (_context as DbContext)?.ChangeTracker.Clear(); + } + catch + { + if (storedByThisCall) await TryDeleteAsync(path).ConfigureAwait(false); + + throw; + } + } + } + + /// + /// Whether the repository stores the version (some file of it), without asking any upstream: what the resolution preview of a + /// virtual repository shows for a member another member already shadows. + /// + internal async Task HasVersionAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) + { + var artifact = await FindArtifactAsync(groupId, artifactId, cancellationToken).ConfigureAwait(false); + + return artifact != null + && await _context.MavenVersions!.AsNoTracking().AnyAsync(v => v.ArtifactKey == artifact.Key && v.Version == version, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes what a remote repository cached, rows and files together: everything, one artifact ( + /// group:artifact), or one version of it. No caller check: the administration that asks has done it. Closed gate: refused. + /// + /// The number of files deleted. + internal async Task PurgeAsync(string? artifactName, string? version, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + + var artifacts = _context.MavenArtifacts!.AsQueryable(); + if (artifactName != null) + { + if (!MavenNames.TryParseArtifactName(artifactName, out var group, out var artifactId)) return 0; + + artifacts = artifacts.Where(a => a.GroupId == group && a.ArtifactId == artifactId); + } + + var deleted = 0; + while (true) + { + var batch = await artifacts.OrderBy(a => a.Key).Take(100).ToListAsync(cancellationToken).ConfigureAwait(false); + if (batch.Count == 0) return deleted; + + foreach (var artifact in batch) + { + var versions = _context.MavenVersions!.Where(v => v.ArtifactKey == artifact.Key); + if (version != null) versions = versions.Where(v => v.Version == version); + + var rows = await versions.ToListAsync(cancellationToken).ConfigureAwait(false); + var keys = rows.Select(v => v.Key).ToList(); + var files = await _context.MavenFiles!.Where(f => keys.Contains(f.VersionKey)).Select(f => new { f.VersionKey, f.FileName }).ToListAsync(cancellationToken).ConfigureAwait(false); + + _context.MavenVersions!.RemoveRange(rows); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (!await _context.MavenVersions!.AnyAsync(v => v.ArtifactKey == artifact.Key, cancellationToken).ConfigureAwait(false)) + { + _context.MavenArtifacts!.Remove(artifact); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + foreach (var file in files) + { + var owner = rows.First(v => v.Key == file.VersionKey).Version!; + await TryDeleteAsync(StoragePath(artifact.GroupId!, artifact.ArtifactId!, owner, file.FileName!)).ConfigureAwait(false); + } + + deleted += files.Count; + } + + // One artifact at most is filtered by name, and a version filter only exists with one: a single pass. + if (artifactName != null) return deleted; + } + } + + // ---- deletes -------------------------------------------------------------------------------------------------------- + + /// + public async Task DeleteFileAsync(BaGetPrincipal? caller, MavenCoordinate version, string fileName, CancellationToken cancellationToken) + { + if (version?.Version == null) throw new ArgumentException("A version is required.", nameof(version)); + + var denied = await DenyAsync(caller, PackageAction.Manage, version.Name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + var artifact = await _context.MavenArtifacts!.FirstOrDefaultAsync(a => a.GroupId == version.GroupId && a.ArtifactId == version.ArtifactId, cancellationToken).ConfigureAwait(false); + var row = artifact == null ? null : await _context.MavenVersions!.FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == version.Version, cancellationToken).ConfigureAwait(false); + var file = row == null ? null : await _context.MavenFiles!.FirstOrDefaultAsync(f => f.VersionKey == row.Key && f.FileName == fileName, cancellationToken).ConfigureAwait(false); + if (artifact == null || row == null || file == null) return MavenResult.Fail(MavenStatus.NotFound, $"There is no file {fileName} in {version.Name} {version.Version}."); + + _gate.ThrowIfClosed(); + + _context.MavenFiles!.Remove(file); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + await RemoveIfEmptyAsync(artifact, row, cancellationToken).ConfigureAwait(false); + await TryDeleteAsync(StoragePath(version.GroupId, version.ArtifactId, version.Version, fileName)).ConfigureAwait(false); + + return MavenResult.Ok($"Deleted {fileName}.", 1, version.Name); + } + + // The version goes with its last file (when one is given), the artifact with its last version. + private async Task RemoveIfEmptyAsync(MavenArtifact artifact, MavenVersion? version, CancellationToken cancellationToken) + { + if (version != null) + { + if (!await _context.MavenFiles!.AnyAsync(f => f.VersionKey == version.Key, cancellationToken).ConfigureAwait(false)) + { + _context.MavenVersions!.Remove(version); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + else + { + version.Modified = _time.UtcNow; + } + } + + if (!await _context.MavenVersions!.AnyAsync(v => v.ArtifactKey == artifact.Key, cancellationToken).ConfigureAwait(false)) + { + _context.MavenArtifacts!.Remove(artifact); + } + else + { + artifact.Modified = _time.UtcNow; + } + + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public async Task DeleteVersionAsync(BaGetPrincipal? caller, MavenCoordinate version, CancellationToken cancellationToken) + { + if (version?.Version == null) throw new ArgumentException("A version is required.", nameof(version)); + + var denied = await DenyAsync(caller, PackageAction.Manage, version.Name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + var artifact = await _context.MavenArtifacts!.FirstOrDefaultAsync(a => a.GroupId == version.GroupId && a.ArtifactId == version.ArtifactId, cancellationToken).ConfigureAwait(false); + var row = artifact == null ? null : await _context.MavenVersions!.FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == version.Version, cancellationToken).ConfigureAwait(false); + if (artifact == null || row == null) return MavenResult.Fail(MavenStatus.NotFound, $"There is no version {version.Version} of {version.Name}."); + + _gate.ThrowIfClosed(); + + var names = await _context.MavenFiles!.Where(f => f.VersionKey == row.Key).Select(f => f.FileName!).ToListAsync(cancellationToken).ConfigureAwait(false); + _context.MavenVersions!.Remove(row); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // The version and its files are gone; the artifact goes with its last version. + await RemoveIfEmptyAsync(artifact, version: null, cancellationToken).ConfigureAwait(false); + foreach (var name in names) await TryDeleteAsync(StoragePath(version.GroupId, version.ArtifactId, version.Version, name)).ConfigureAwait(false); + + return MavenResult.Ok($"Deleted {version.Name} {version.Version}.", names.Count, version.Name); + } + + /// + public async Task DeleteArtifactAsync(BaGetPrincipal? caller, string groupId, string artifactId, CancellationToken cancellationToken) + { + var name = MavenNames.ArtifactName(groupId, artifactId); + var denied = await DenyAsync(caller, PackageAction.Manage, name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + var artifact = await _context.MavenArtifacts!.FirstOrDefaultAsync(a => a.GroupId == groupId && a.ArtifactId == artifactId, cancellationToken).ConfigureAwait(false); + if (artifact == null) return MavenResult.Fail(MavenStatus.NotFound, $"There is no artifact {name}."); + + _gate.ThrowIfClosed(); + + var versions = await _context.MavenVersions!.Where(v => v.ArtifactKey == artifact.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var keys = versions.Select(v => v.Key).ToList(); + var files = await _context.MavenFiles!.Where(f => keys.Contains(f.VersionKey)).Select(f => new { f.VersionKey, f.FileName }).ToListAsync(cancellationToken).ConfigureAwait(false); + + _context.MavenArtifacts!.Remove(artifact); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + foreach (var file in files) + { + var version = versions.First(v => v.Key == file.VersionKey).Version!; + await TryDeleteAsync(StoragePath(groupId, artifactId, version, file.FileName!)).ConfigureAwait(false); + } + + return MavenResult.Ok($"Deleted {name}.", files.Count, name); + } + + /// + public async Task CleanupSnapshotsAsync(BaGetPrincipal? caller, MavenCoordinate version, int keep, CancellationToken cancellationToken) + { + if (version?.Version == null) throw new ArgumentException("A version is required.", nameof(version)); + if (keep < 1) return MavenResult.Fail(MavenStatus.Invalid, "Keep at least one build."); + + var denied = await DenyAsync(caller, PackageAction.Manage, version.Name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + if (!MavenNames.IsSnapshot(version.Version)) return MavenResult.Fail(MavenStatus.Invalid, $"{version.Version} is not a snapshot version."); + + var artifact = await FindArtifactAsync(version.GroupId, version.ArtifactId, cancellationToken).ConfigureAwait(false); + var row = artifact == null ? null : await _context.MavenVersions!.AsNoTracking().FirstOrDefaultAsync(v => v.ArtifactKey == artifact.Key && v.Version == version.Version, cancellationToken).ConfigureAwait(false); + if (row == null) return MavenResult.Fail(MavenStatus.NotFound, $"There is no version {version.Version} of {version.Name}."); + + _gate.ThrowIfClosed(); + + var removed = await PruneSnapshotsAsync(version, row.Key, keep, cancellationToken).ConfigureAwait(false); + + return MavenResult.Ok($"Deleted {removed} file{(removed == 1 ? string.Empty : "s")} of older builds.", removed, version.Name); + } + + // Keeps the newest 'keep' timestamped builds (every file of a build goes together) and deletes the rest. + private async Task PruneSnapshotsAsync(MavenCoordinate version, int versionKey, int keep, CancellationToken cancellationToken) + { + var builds = await _context.MavenFiles!.Where(f => f.VersionKey == versionKey && f.SnapshotTimestamp != null).ToListAsync(cancellationToken).ConfigureAwait(false); + var old = builds + .GroupBy(f => (f.SnapshotTimestamp, f.SnapshotBuild)) + .OrderByDescending(g => g.Key.SnapshotTimestamp, StringComparer.Ordinal).ThenByDescending(g => g.Key.SnapshotBuild) + .Skip(keep) + .SelectMany(g => g) + .ToList(); + if (old.Count == 0) return 0; + + _context.MavenFiles!.RemoveRange(old); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + foreach (var file in old) await TryDeleteAsync(StoragePath(version.GroupId, version.ArtifactId, version.Version!, file.FileName!)).ConfigureAwait(false); + + return old.Count; + } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenRepositorySettings.cs b/src/BaGet.Core/Formats/Maven/MavenRepositorySettings.cs new file mode 100644 index 000000000..48c3411db --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenRepositorySettings.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace BaGet.Core; + +/// Which versions a local Maven repository accepts. +public enum MavenPolicy +{ + /// Release versions only; a -SNAPSHOT deploy is refused (409). + Releases = 0, + + /// Snapshot versions only; a release deploy is refused (409). + Snapshots = 1, + + /// Both. + Both = 2, +} + +/// +/// The settings of a local Maven repository, kept as JSON in (no schema of their own). +/// +public sealed class MavenRepositorySettings +{ + /// The largest the form accepts. + public const int MaxSnapshotBuildsLimit = 1000; + + private static readonly JsonSerializerOptions Json = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }, + DefaultIgnoreCondition = JsonIgnoreCondition.Never, + }; + + /// Which versions are accepted. Default: releases only, as Maven Central's layout expects. + public MavenPolicy Policy { get; set; } = MavenPolicy.Releases; + + /// + /// Whether a release file that exists may be deployed again (replaced). The caller then also needs the Delete action, as + /// Artifactory's Delete/Overwrite does. Default false: a release is immutable. Snapshots are never refused for this. + /// + public bool AllowRedeploy { get; set; } + + /// + /// How many timestamped builds of a snapshot version are kept: when a deploy brings a newer build, older ones beyond this + /// number are deleted. Zero keeps all (clean up on the artifact's page). + /// + public int MaxSnapshotBuilds { get; set; } + + /// Whether may be deployed under . + public bool Accepts(string version) => Policy switch + { + MavenPolicy.Releases => !MavenNames.IsSnapshot(version), + MavenPolicy.Snapshots => MavenNames.IsSnapshot(version), + _ => true, + }; + + /// The settings stored in ; the defaults when it is null, empty or unreadable. + public static MavenRepositorySettings Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return new MavenRepositorySettings(); + + try + { + var settings = JsonSerializer.Deserialize(json, Json) ?? new MavenRepositorySettings(); + settings.MaxSnapshotBuilds = Math.Clamp(settings.MaxSnapshotBuilds, 0, MaxSnapshotBuildsLimit); + + return settings; + } + catch (JsonException) + { + return new MavenRepositorySettings(); + } + } + + /// The JSON to store. + public string ToJson() => JsonSerializer.Serialize(this, Json); + + /// + /// Checks the values (the form's keys: policy, redeploy, snapshotBuilds) and builds the settings. + /// + /// A value is not valid; the message is shown to the administrator. + public static MavenRepositorySettings FromFields(IReadOnlyDictionary fields) + { + if (fields == null) throw new ArgumentNullException(nameof(fields)); + + var settings = new MavenRepositorySettings(); + var policy = Get(fields, "policy"); + if (!string.IsNullOrEmpty(policy)) + { + if (!Enum.TryParse(policy, ignoreCase: true, out var parsed) || !Enum.IsDefined(parsed)) + { + throw new ArgumentException("The version policy must be Releases, Snapshots or Both."); + } + + settings.Policy = parsed; + } + + var redeploy = Get(fields, "redeploy"); + if (!string.IsNullOrEmpty(redeploy)) + { + if (redeploy.Equals("true", StringComparison.OrdinalIgnoreCase) || redeploy.Equals("yes", StringComparison.OrdinalIgnoreCase)) settings.AllowRedeploy = true; + else if (redeploy.Equals("false", StringComparison.OrdinalIgnoreCase) || redeploy.Equals("no", StringComparison.OrdinalIgnoreCase)) settings.AllowRedeploy = false; + else throw new ArgumentException("Redeploying releases must be Yes or No."); + } + + var builds = Get(fields, "snapshotBuilds"); + if (!string.IsNullOrEmpty(builds)) + { + if (!int.TryParse(builds, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var count) || count > MaxSnapshotBuildsLimit) + { + throw new ArgumentException($"Snapshot builds kept must be a number from 0 (all) to {MaxSnapshotBuildsLimit}."); + } + + settings.MaxSnapshotBuilds = count; + } + + return settings; + } + + private static string? Get(IReadOnlyDictionary fields, string key) + => fields.TryGetValue(key, out var value) ? value?.Trim() : null; +} diff --git a/src/BaGet.Core/Formats/Maven/MavenRetentionHooks.cs b/src/BaGet.Core/Formats/Maven/MavenRetentionHooks.cs new file mode 100644 index 000000000..e6c95f616 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenRetentionHooks.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Maven's : a version is one of a group:artifact with all its +/// files (a snapshot with its timestamped builds), a snapshot being the prerelease. Deleting is +/// : rows and files together, the artifact going with its last version. +/// +public sealed class MavenRetentionHooks : IFormatRetentionHooks +{ + private readonly IContext _context; + private readonly MavenRepositoryService _repository; + + public MavenRetentionHooks(IContext context, MavenRepositoryService repository) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Maven; + + /// + public async Task> ListVersionsAsync(CancellationToken cancellationToken) + { + var usage = await ArtifactUsageMap.LoadAsync(_context, cancellationToken).ConfigureAwait(false); + var rows = await (from v in _context.MavenVersions!.AsNoTracking() + join a in _context.MavenArtifacts!.AsNoTracking() on v.ArtifactKey equals a.Key + select new { v.Key, a.GroupId, a.ArtifactId, v.Version, v.Created, v.IsSnapshot }).ToListAsync(cancellationToken).ConfigureAwait(false); + var sizes = (await (from f in _context.MavenFiles!.AsNoTracking() + join v in _context.MavenVersions!.AsNoTracking() on f.VersionKey equals v.Key + join a in _context.MavenArtifacts!.AsNoTracking() on v.ArtifactKey equals a.Key + group f.Size by f.VersionKey into g + select new { VersionKey = g.Key, Bytes = g.Sum() }).ToListAsync(cancellationToken).ConfigureAwait(false)) + .ToDictionary(x => x.VersionKey, x => x.Bytes); + + return rows + .Select(r => + { + var name = MavenNames.ArtifactName(r.GroupId!, r.ArtifactId!); + + return new FormatVersion(name, r.Version!, DateTime.SpecifyKind(r.Created, DateTimeKind.Utc), usage.Get(name, r.Version!), sizes.TryGetValue(r.Key, out var bytes) ? bytes : 0, r.IsSnapshot); + }) + .ToList(); + } + + /// + public async Task DeleteVersionAsync(string name, string version, CancellationToken cancellationToken) + => await _repository.PurgeAsync(name, version, cancellationToken).ConfigureAwait(false); + + /// + public (string Name, string Version)? Canonical(string name, string? version) + { + if (!MavenNames.TryParseArtifactName(name?.Trim(), out var group, out var artifact)) return null; + if (string.IsNullOrWhiteSpace(version)) return (MavenNames.ArtifactName(group, artifact), string.Empty); + + return MavenNames.IsValidVersion(version.Trim()) ? (MavenNames.ArtifactName(group, artifact), version.Trim()) : null; + } +} diff --git a/src/BaGet.Core/Formats/Maven/MavenUpstreamClient.cs b/src/BaGet.Core/Formats/Maven/MavenUpstreamClient.cs new file mode 100644 index 000000000..567e08dd8 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/MavenUpstreamClient.cs @@ -0,0 +1,386 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using System.Xml.Linq; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// How asking the upstream of a remote Maven repository for a small document (metadata, a checksum) ended. +public enum MavenUpstreamStatus +{ + /// The document is there (). + Found, + + /// The upstream does not have it (a real 404, possibly remembered). + NotFound, + + /// Offline mode: the upstream is never contacted, and nothing is remembered about the path. + Offline, + + /// The upstream could not be asked (down, refused the credentials, not a Maven repository) and nothing remembered can answer. + Unavailable, +} + +/// An upstream's answer about one small document. +/// How it ended. +/// The bytes (a private copy the caller may keep), or null. +/// When the upstream sent them (UTC). +/// Whether it is an expired answer served because the upstream could not be reached. +/// What failed, for . +public sealed record MavenUpstreamAnswer(MavenUpstreamStatus Status, byte[]? Content = null, DateTime Fetched = default, bool Stale = false, string? Message = null); + +/// A file being downloaded from the upstream; disposing releases the connection. +public sealed class MavenUpstreamDownload : IDisposable +{ + private readonly HttpResponseMessage _response; + + internal MavenUpstreamDownload(HttpResponseMessage response, Stream content) + { + _response = response; + Content = content; + } + + /// The bytes. + public Stream Content { get; } + + /// The size the upstream announced, or null. + public long? Length => _response.Content.Headers.ContentLength; + + /// The media type the upstream announced, or null. + public string? MediaType => _response.Content.Headers.ContentType?.MediaType; + + /// When the upstream says the file last changed (UTC), or null. + public DateTime? LastModified => _response.Content.Headers.LastModified?.UtcDateTime; + + /// + public void Dispose() + { + Content.Dispose(); + _response.Dispose(); + } +} + +/// +/// Asks the upstream of the current remote Maven repository (): the small documents +/// (maven-metadata.xml and checksums) and the bytes of a file. Applies what every remote repository has +/// (): offline mode, the metadata period, the negative period (only a real 404 is remembered +/// as "not found"), an expired answer served when the upstream cannot be reached, the health the status page shows, credentials +/// sent to the upstream's own origin only (the HTTP client's handler) and Remote:BlockPrivateAddresses (its connect +/// callback). The answers are kept in , under keys that carry the request path after a +/// three-character kind (mm: metadata, mc: a checksum, mf: a file the upstream does not have), so a purge +/// finds everything about an artifact by the path prefix (). +/// +public sealed class MavenUpstreamClient +{ + /// The largest maven-metadata.xml accepted; the biggest real ones are well under a megabyte. + public const long MaxMetadataBytes = 16L * 1024 * 1024; + + /// The largest checksum file accepted (a SHA-512 in hex is 128 characters). + public const long MaxChecksumBytes = 4096; + + private readonly IRepositoryContext? _repository; + private readonly IRemoteUpstreamSource _source; + private readonly RemoteRepositoryState _state; + private readonly IRemoteHttpClientFactory _http; + private readonly ILogger _logger; + + public MavenUpstreamClient( + IRepositoryContext? repository, + IRemoteUpstreamSource source, + RemoteRepositoryState state, + IRemoteHttpClientFactory http, + ILogger logger) + { + _repository = repository; + _source = source ?? throw new ArgumentNullException(nameof(source)); + _state = state ?? throw new ArgumentNullException(nameof(state)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// The upstream of the request's repository, or null when it has none (not remote, or its settings are not usable). + public Task ResolveAsync(CancellationToken cancellationToken) + => _source.ResolveAsync(_repository?.Current ?? RepositoryInfo.Default, cancellationToken); + + private const string MetadataKind = "mm:"; + private const string ChecksumKind = "mc:"; + private const string AbsentKind = "mf:"; + + /// + /// Whether a cache key (any kind) is about the artifact folder (org/acme/lib) or below it + /// (a version folder, files, checksums, metadata). + /// + public static bool PathPrefix(string cacheKey, string relativeFolder) + => cacheKey.Length > 3 && cacheKey.AsSpan(3).StartsWith((relativeFolder.TrimEnd('/') + "/").AsSpan(), StringComparison.Ordinal); + + /// + /// The upstream's maven-metadata.xml at (artifact, version or group level), validated as + /// Maven metadata. + /// + public Task GetMetadataAsync(ResolvedUpstream upstream, string relativePath, CancellationToken cancellationToken) + => GetDocumentAsync(upstream, MetadataKind, relativePath, MaxMetadataBytes, ValidateMetadata, cancellationToken); + + /// + /// The upstream's checksum file at (….jar.sha1), reduced to its hex digest. + /// + public Task GetChecksumAsync(ResolvedUpstream upstream, string relativePath, CancellationToken cancellationToken) + => GetDocumentAsync(upstream, ChecksumKind, relativePath, MaxChecksumBytes, ValidateChecksum, cancellationToken); + + private async Task GetDocumentAsync( + ResolvedUpstream upstream, + string kind, + string relativePath, + long limit, + Func validate, + CancellationToken cancellationToken) + { + var key = upstream.Key; + var settings = upstream.Settings; + var cacheKey = kind + relativePath; + var cached = _state.TryGet(key, cacheKey, out var value, out var negative, out var fresh); + + // Offline: whatever is remembered, however old; else nothing. The upstream is not contacted. + if (settings.Offline) + { + if (cached && !negative && value is CachedDocument remembered) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return new MavenUpstreamAnswer(MavenUpstreamStatus.Found, (byte[])remembered.Content.Clone(), remembered.Fetched, Stale: !fresh); + } + + return new MavenUpstreamAnswer(MavenUpstreamStatus.Offline); + } + + if (cached && fresh) + { + if (negative) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return new MavenUpstreamAnswer(MavenUpstreamStatus.NotFound); + } + + if (value is CachedDocument hit) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return new MavenUpstreamAnswer(MavenUpstreamStatus.Found, (byte[])hit.Content.Clone(), hit.Fetched); + } + } + + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + + try + { + using var response = await SendAsync(upstream, HttpMethod.Get, FileUri(settings, relativePath), "application/xml, text/plain, */*", cancellationToken).ConfigureAwait(false); + + if (response.StatusCode == HttpStatusCode.NotFound) + { + _state.Succeeded(key); + _state.Set(key, cacheKey, null, negative: true, TimeSpan.FromSeconds(settings.NegativeTtlSeconds)); + + return new MavenUpstreamAnswer(MavenUpstreamStatus.NotFound); + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + byte[] content; + await using (var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) + { + content = validate(await ReadCappedAsync(response, body, limit, cancellationToken).ConfigureAwait(false)); + } + + var fetched = _state.UtcNow; + _state.Succeeded(key); + _state.Set(key, cacheKey, new CachedDocument(content, fetched), negative: false, TimeSpan.FromSeconds(settings.MetadataTtlSeconds)); + + return new MavenUpstreamAnswer(MavenUpstreamStatus.Found, (byte[])content.Clone(), fetched); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + var what = Fail(upstream, e); + + if (cached && !negative && value is CachedDocument stale) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Stale); + + return new MavenUpstreamAnswer(MavenUpstreamStatus.Found, (byte[])stale.Content.Clone(), stale.Fetched, Stale: true); + } + + return new MavenUpstreamAnswer(MavenUpstreamStatus.Unavailable, Message: what); + } + } + + /// + /// Whether a download of must not be tried now: a fresh 404 is remembered for it (counted as a + /// negative hit). Offline is the caller's own check. + /// + public bool IsKnownAbsent(ResolvedUpstream upstream, string relativePath) + { + if (_state.TryGet(upstream.Key, AbsentKind + relativePath, out _, out var negative, out var fresh) && negative && fresh) + { + _state.Count(upstream.Key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return true; + } + + return false; + } + + /// + /// Downloads the file at ; null when the upstream says 404 (remembered for the negative period). + /// With only the headers are asked (the download then has no content worth reading). + /// + /// The upstream could not be reached or refused. + public async Task DownloadAsync(ResolvedUpstream upstream, string relativePath, bool headOnly, CancellationToken cancellationToken) + { + var key = upstream.Key; + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + + HttpResponseMessage? response = null; + try + { + response = await SendAsync(upstream, headOnly ? HttpMethod.Head : HttpMethod.Get, FileUri(upstream.Settings, relativePath), "*/*", cancellationToken).ConfigureAwait(false); + + // A server whose catch-all route answers 200 with a web page for a path it does not have has no such file: an artifact is + // never an HTML page, and keeping the page would put it in front of every build. + if (response.StatusCode == HttpStatusCode.NotFound || IsWebPageForAFile(response, relativePath)) + { + _state.Succeeded(key); + _state.Set(key, AbsentKind + relativePath, null, negative: true, TimeSpan.FromSeconds(upstream.Settings.NegativeTtlSeconds)); + response.Dispose(); + + return null; + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + var content = headOnly ? Stream.Null : await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + _state.Succeeded(key); + + return new MavenUpstreamDownload(response, content); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + response?.Dispose(); + + throw new MavenUpstreamException(Fail(upstream, e)); + } + } + + private static bool IsWebPageForAFile(HttpResponseMessage response, string relativePath) + => response.IsSuccessStatusCode + && string.Equals(response.Content.Headers.ContentType?.MediaType, "text/html", StringComparison.OrdinalIgnoreCase) + && !relativePath.EndsWith(".html", StringComparison.OrdinalIgnoreCase) + && !relativePath.EndsWith(".htm", StringComparison.OrdinalIgnoreCase); + + /// Records that what the upstream sent was not what it announced (a file whose checksum differs): a failure of the upstream. + public string Rejected(ResolvedUpstream upstream, string what) + { + _state.Failed(upstream.Key, what); + _logger.LogWarning("The upstream of repository {Repository} sent something unusable: {Error}", upstream.Name, what); + + return what; + } + + /// Records that the upstream answered (a successful probe of its own). + internal void Reached(ResolvedUpstream upstream) => _state.Succeeded(upstream.Key); + + private static Uri FileUri(RemoteRepositorySettings settings, string relativePath) + { + var text = settings.UrlOrNull!.GetLeftPart(UriPartial.Path); + + return new Uri((text.EndsWith('/') ? text : text + "/") + relativePath); + } + + private async Task SendAsync(ResolvedUpstream upstream, HttpMethod method, Uri uri, string accept, CancellationToken cancellationToken) + { + var transport = _state.GetTransport( + upstream.Key, + upstream.Settings, + () => new UpstreamTransport(upstream.Settings.TransportKey(), _http.Create(upstream.Settings), null)); + + using var request = new HttpRequestMessage(method, uri); + request.Headers.TryAddWithoutValidation("Accept", accept); + + return await transport.Http!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + } + + private static async Task ReadCappedAsync(HttpResponseMessage response, Stream body, long limit, CancellationToken cancellationToken) + { + if (response.Content.Headers.ContentLength > limit) throw new InvalidDataException("The answer is too large."); + + using var buffer = new MemoryStream(); + var chunk = new byte[16 * 1024]; + int read; + while ((read = await body.ReadAsync(chunk, cancellationToken).ConfigureAwait(false)) > 0) + { + if (buffer.Length + read > limit) throw new InvalidDataException("The answer is larger than " + limit + " bytes."); + + buffer.Write(chunk, 0, read); + } + + return buffer.ToArray(); + } + + // A server that answers 200 with an HTML page for a missing file is not a Maven repository's answer. + private static byte[] ValidateMetadata(byte[] content) + { + try + { + using var reader = XmlReader.Create(new MemoryStream(content), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); + var document = XDocument.Load(reader); + if (document.Root?.Name.LocalName != "metadata") throw new InvalidDataException("The upstream did not send Maven metadata."); + } + catch (XmlException) + { + throw new InvalidDataException("The upstream did not send Maven metadata."); + } + + return content; + } + + // " [file name]" or "": the digest only. + private static byte[] ValidateChecksum(byte[] content) + { + var text = Encoding.ASCII.GetString(content).Trim(); + var end = text.IndexOfAny(new[] { ' ', '\t', '\r', '\n' }); + var digest = (end < 0 ? text : text.Substring(0, end)).ToLowerInvariant(); + if (digest.Length < 32 || digest.Length > 128 || digest.Length % 2 != 0 || !IsHex(digest)) + { + throw new InvalidDataException("The upstream did not send a checksum."); + } + + return Encoding.ASCII.GetBytes(digest); + } + + private static bool IsHex(string text) + { + foreach (var c in text) + { + if (!(c is >= '0' and <= '9' or >= 'a' and <= 'f')) return false; + } + + return true; + } + + private string Fail(ResolvedUpstream upstream, Exception e) + { + var what = RemoteUpstreamClient.Describe(e); + _state.Failed(upstream.Key, what); + + // The exception itself is not logged: its message can carry the upstream's URL with a query string. + _logger.LogWarning("The upstream of repository {Repository} could not be reached: {Error}", upstream.Name, what); + + return what; + } + + private sealed record CachedDocument(byte[] Content, DateTime Fetched); +} diff --git a/src/BaGet.Core/Formats/Maven/RemoteMavenRepository.cs b/src/BaGet.Core/Formats/Maven/RemoteMavenRepository.cs new file mode 100644 index 000000000..bfd41ae2e --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/RemoteMavenRepository.cs @@ -0,0 +1,484 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using System.Xml.Linq; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// of a Maven repository: a caching proxy of an upstream +/// repository (Maven Central, https://repo.maven.apache.org/maven2/; another BaGet, Artifactory, Nexus...). +/// +/// +/// Files. A stored file is served from storage, checksums from its row. Otherwise it is downloaded, hashed while it is +/// written to a temporary file, compared with the checksum the upstream publishes beside it (.sha1, else .sha256, else +/// .md5; a mismatch is neither stored nor served: , HTTP 502) and, with +/// , kept in the repository's storage with its artifact, version and file rows, so +/// it is served locally from then on, also while the upstream is down. Without it the download is streamed through and nothing is +/// kept. Concurrent requests for the same file download it once. A -SNAPSHOT file under its plain name +/// (lib-1.0-SNAPSHOT.jar) moves, so it is always streamed from the upstream and never kept (the timestamped build it names is, +/// when asked for by that name); a stored build only answers it while the upstream cannot. +/// Metadata and checksums of metadata (maven-metadata.xml, artifact, version and group level, so plugin prefixes +/// resolve too) come from the upstream (: cached for the metadata period, 404s for the negative +/// period, an expired answer when the upstream is down, nothing in offline mode). When the upstream cannot answer, the metadata +/// generated from the versions this repository stored answers instead; when neither can, the upstream's failure is raised (HTTP 502). +/// Writes are refused (403): a remote repository takes no changes. Pages and search cover the stored artifacts only. +/// +public sealed class RemoteMavenRepository : IMavenRepository +{ + private const string NoChanges = "This repository caches an upstream repository and takes no changes."; + + private static readonly KeyedLocks Downloads = new(); + + private readonly MavenRepositoryService _local; + private readonly MavenUpstreamClient _upstream; + private readonly ILogger _logger; + private readonly IOptionsSnapshot? _options; + + public RemoteMavenRepository(MavenRepositoryService local, MavenUpstreamClient upstream, ILogger logger, IOptionsSnapshot? options = null) + { + _local = local ?? throw new ArgumentNullException(nameof(local)); + _upstream = upstream ?? throw new ArgumentNullException(nameof(upstream)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _options = options; + } + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + /// + /// A file names its artifact. Metadata one folder deeper than the group (a/b/c/maven-metadata.xml) is the artifact + /// b:c or version c of a:b; the upstream's own document says which (its groupId and + /// artifactId), else what is stored decides, else the artifact level. + /// + public async Task ResolveAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + if (path.Candidates.Count == 0) return null; + if (path.Kind == MavenPathKind.File) return path.Candidates[0]; + + // A single candidate (a path two folders deep) can still be a group's plugin list, which names no artifact. + var single = path.Candidates.Count == 1; + if (single && (path.GroupOnly == null || path.Candidates[0].Version != null)) return path.Candidates[0]; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream != null) + { + var answer = await _upstream.GetMetadataAsync(upstream, path.Plain.RelativePath, cancellationToken).ConfigureAwait(false); + if (answer.Status == MavenUpstreamStatus.Found) + { + if (Identify(answer.Content!, path.Candidates) is { } match) return match; + + // Not about the artifact: a group-level document is judged by the repository's Read, not by an unrelated artifact's. + if (single && IsGroupLevel(answer.Content!)) return null; + } + } + + if (single) return path.Candidates[0]; + + return await _local.ResolveAsync(path, cancellationToken).ConfigureAwait(false); + } + + // A group-level document: a plugin list with no artifactId of its own. + internal static bool IsGroupLevel(byte[] metadata) + { + try + { + using var reader = XmlReader.Create(new MemoryStream(metadata), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); + var root = XDocument.Load(reader).Root; + + return root?.Element("plugins") != null && string.IsNullOrWhiteSpace(root.Element("artifactId")?.Value); + } + catch (XmlException) + { + return false; + } + } + + // The candidate a metadata document is about: the artifact its groupId and artifactId name; the version level when it names a version. + internal static MavenCoordinate? Identify(byte[] metadata, System.Collections.Generic.IReadOnlyList candidates) + { + try + { + using var reader = XmlReader.Create(new MemoryStream(metadata), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); + var root = XDocument.Load(reader).Root; + var group = root?.Element("groupId")?.Value.Trim(); + var artifact = root?.Element("artifactId")?.Value.Trim(); + var version = root?.Element("version")?.Value.Trim(); + + return candidates.FirstOrDefault(c => c.GroupId == group && c.ArtifactId == artifact && (c.Version == null) == string.IsNullOrEmpty(version)); + } + catch (XmlException) + { + return null; + } + } + + /// + public Task OpenAsync(MavenRequestPath path, CancellationToken cancellationToken) => OpenCoreAsync(path, head: false, cancellationToken); + + /// + public Task HeadAsync(MavenRequestPath path, CancellationToken cancellationToken) => OpenCoreAsync(path, head: true, cancellationToken); + + private async Task OpenCoreAsync(MavenRequestPath path, bool head, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + + return path.Kind == MavenPathKind.Metadata + ? await OpenMetadataAsync(upstream, path, cancellationToken).ConfigureAwait(false) + : await OpenFileAsync(upstream, path, head, cancellationToken).ConfigureAwait(false); + } + + // ---- metadata ------------------------------------------------------------------------------------------------------- + + private async Task OpenMetadataAsync(ResolvedUpstream? upstream, MavenRequestPath path, CancellationToken cancellationToken) + { + if (upstream == null) return await _local.OpenAsync(path, cancellationToken).ConfigureAwait(false); + + var plain = path.Plain; + var answer = await _upstream.GetMetadataAsync(upstream, plain.RelativePath, cancellationToken).ConfigureAwait(false); + if (answer.Status == MavenUpstreamStatus.Found) + { + var content = answer.Content!; + if (path.ChecksumAlgorithm != null) + { + var text = Encoding.ASCII.GetBytes(Hex(path.ChecksumAlgorithm, content)); + + return new MavenDownload(new MemoryStream(text, writable: false), text.Length, "text/plain", path.FileName, answer.Fetched); + } + + return new MavenDownload(new MemoryStream(content, writable: false), content.Length, "application/xml", path.FileName, answer.Fetched) + { + Sha1 = Hex("sha1", content), + Md5 = Hex("md5", content), + Sha256 = Hex("sha256", content), + }; + } + + // The upstream has nothing to say (404, offline, down): the versions this repository stored still answer. + var stored = await _local.OpenAsync(path, cancellationToken).ConfigureAwait(false); + if (stored != null || answer.Status != MavenUpstreamStatus.Unavailable) return stored; + + throw new MavenUpstreamException(answer.Message ?? "The upstream repository could not be reached."); + } + + internal static string Hex(string algorithm, byte[] content) + { + var hash = algorithm switch + { + "md5" => System.Security.Cryptography.MD5.HashData(content), + "sha256" => System.Security.Cryptography.SHA256.HashData(content), + "sha512" => System.Security.Cryptography.SHA512.HashData(content), + _ => System.Security.Cryptography.SHA1.HashData(content), + }; + + return Convert.ToHexString(hash).ToLowerInvariant(); + } + + // ---- files ---------------------------------------------------------------------------------------------------------- + + private async Task OpenFileAsync(ResolvedUpstream? upstream, MavenRequestPath path, bool head, CancellationToken cancellationToken) + { + var coordinate = path.Candidates[0]; + var parts = MavenNames.ParseFileName(coordinate.ArtifactId, coordinate.Version!, path.BaseName); + + // A snapshot under its plain name moves: the upstream answers first, and a stored build only when it cannot. + var moving = MavenNames.IsSnapshot(coordinate.Version) && (parts == null || parts.SnapshotTimestamp == null); + if (!moving) + { + var stored = await _local.OpenAsync(path, cancellationToken).ConfigureAwait(false); + if (stored != null) return stored; + } + + if (upstream == null || upstream.Settings.Offline) return moving ? await _local.OpenAsync(path, cancellationToken).ConfigureAwait(false) : null; + + try + { + var fetched = path.ChecksumAlgorithm != null + ? await ProxyChecksumAsync(upstream, path, cancellationToken).ConfigureAwait(false) + : await FetchFileAsync(upstream, path, coordinate, parts, moving, head, cancellationToken).ConfigureAwait(false); + if (fetched != null || !moving) return fetched; + } + catch (MavenUpstreamException) when (moving) + { + // Falls through to a stored build. + } + + return await _local.OpenAsync(path, cancellationToken).ConfigureAwait(false); + } + + // The upstream's checksum of a file this repository does not store (or of a moving snapshot): small, remembered like metadata. + private async Task ProxyChecksumAsync(ResolvedUpstream upstream, MavenRequestPath path, CancellationToken cancellationToken) + { + var answer = await _upstream.GetChecksumAsync(upstream, path.RelativePath, cancellationToken).ConfigureAwait(false); + switch (answer.Status) + { + case MavenUpstreamStatus.Found: + return new MavenDownload(new MemoryStream(answer.Content!, writable: false), answer.Content!.Length, "text/plain", path.FileName, answer.Fetched); + case MavenUpstreamStatus.Unavailable: + throw new MavenUpstreamException(answer.Message ?? "The upstream repository could not be reached."); + default: + return null; + } + } + + private async Task FetchFileAsync( + ResolvedUpstream upstream, + MavenRequestPath path, + MavenCoordinate coordinate, + MavenFileParts? parts, + bool moving, + bool head, + CancellationToken cancellationToken) + { + var relative = path.RelativePath; + if (_upstream.IsKnownAbsent(upstream, relative)) return null; + + var cacheable = upstream.Settings.StoreLocally && parts != null && !moving; + if (head) + { + // Only the headers are asked; nothing is stored for a HEAD. + using var probe = await _upstream.DownloadAsync(upstream, relative, headOnly: true, cancellationToken).ConfigureAwait(false); + + return probe == null ? null : Streamed(probe, path, Stream.Null); + } + + if (!cacheable) + { + var passthrough = await _upstream.DownloadAsync(upstream, relative, headOnly: false, cancellationToken).ConfigureAwait(false); + + return passthrough == null ? null : Streamed(passthrough, path, new DisposingStream(passthrough)); + } + + // One download per file at a time: the second request finds the first one's stored copy. + using var turn = await Downloads.LockAsync($"{upstream.Key}|{relative}", cancellationToken).ConfigureAwait(false); + + var already = await _local.OpenAsync(path, cancellationToken).ConfigureAwait(false); + if (already != null) return already; + + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.MirrorFetch); + activity?.SetTag(BaGetDiagnostics.Tags.PackageId, coordinate.Name); + activity?.SetTag(BaGetDiagnostics.Tags.PackageVersion, coordinate.Version); + + try + { + using var download = await _upstream.DownloadAsync(upstream, relative, headOnly: false, cancellationToken).ConfigureAwait(false); + if (download == null) + { + activity?.SetTag(BaGetDiagnostics.Tags.Result, "NotFound"); + + return null; + } + + var limit = _options?.Value.MaxFileBytes ?? 1024L * 1024 * 1024; + if (limit > 0 && download.Length > limit) + { + throw new MavenUpstreamException(_upstream.Rejected(upstream, $"{path.FileName} is larger than {limit} bytes.")); + } + + MavenRepositoryService.Spooled? spooled; + try + { + spooled = await MavenRepositoryService.SpoolAsync(download.Content, limit, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is IOException or System.Net.Http.HttpRequestException) + { + throw new MavenUpstreamException(_upstream.Rejected(upstream, "The download from the upstream was cut off.")); + } + + if (spooled == null) throw new MavenUpstreamException(_upstream.Rejected(upstream, $"{path.FileName} is larger than {limit} bytes.")); + + using (spooled) + { + // What arrived must be what the upstream's own checksum promises; a mismatch is never stored or served. + await VerifyAsync(upstream, path, spooled, cancellationToken).ConfigureAwait(false); + + await _local.StoreCachedAsync(coordinate, path.BaseName, parts!, spooled, cancellationToken).ConfigureAwait(false); + } + + activity?.SetTag(BaGetDiagnostics.Tags.Result, "Success"); + } + catch (Exception e) when (e is not MaintenanceException and not OperationCanceledException) + { + BaGetDiagnostics.Fail(activity, e); + + throw; + } + + return await _local.OpenAsync(path, cancellationToken).ConfigureAwait(false); + } + + private async Task VerifyAsync(ResolvedUpstream upstream, MavenRequestPath path, MavenRepositoryService.Spooled spooled, CancellationToken cancellationToken) + { + foreach (var (algorithm, actual) in new[] { ("sha1", spooled.Sha1), ("sha256", spooled.Sha256), ("md5", spooled.Md5) }) + { + var answer = await _upstream.GetChecksumAsync(upstream, path.RelativePath + "." + algorithm, cancellationToken).ConfigureAwait(false); + if (answer.Status == MavenUpstreamStatus.Found) + { + if (!string.Equals(Encoding.ASCII.GetString(answer.Content!), actual, StringComparison.OrdinalIgnoreCase)) + { + throw new MavenUpstreamException(_upstream.Rejected(upstream, $"{path.FileName} does not match the {algorithm} checksum the upstream publishes.")); + } + + return; + } + + // The first checksum the upstream publishes decides; one it cannot be asked for leaves the file unverified. + if (answer.Status != MavenUpstreamStatus.NotFound) + { + _logger.LogDebug("No checksum of {File} could be fetched from the upstream of repository {Repository}; it is stored unverified.", path.FileName, upstream.Name); + + return; + } + } + } + + private static MavenDownload Streamed(MavenUpstreamDownload download, MavenRequestPath path, Stream content) + { + var extension = path.BaseName.Substring(path.BaseName.LastIndexOf('.') + 1); + + return new MavenDownload(content, download.Length ?? 0, MavenNames.ContentTypeOf(extension), path.FileName, download.LastModified ?? DateTime.UtcNow); + } + + // Disposing the stream releases the download (its connection) too. + private sealed class DisposingStream : Stream + { + private readonly MavenUpstreamDownload _download; + + public DisposingStream(MavenUpstreamDownload download) + { + _download = download; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => _download.Content.Read(buffer, offset, count); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => _download.Content.ReadAsync(buffer, cancellationToken); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) _download.Dispose(); + + base.Dispose(disposing); + } + } + + // ---- listings and pages: what was stored ---------------------------------------------------------------------------- + + /// + /// Only the artifacts this repository stored: a repository's whole catalogue is not searched through a cache. + public Task SearchAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) + => _local.SearchAsync(text, skip, take, canRead, cancellationToken); + + /// + public Task GetArtifactAsync(string groupId, string artifactId, CancellationToken cancellationToken) + => _local.GetArtifactAsync(groupId, artifactId, cancellationToken); + + /// + public Task GetVersionAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) + => _local.GetVersionAsync(groupId, artifactId, version, cancellationToken); + + /// + public Task GetSettingsAsync(CancellationToken cancellationToken) + => Task.FromResult(new MavenRepositorySettings { Policy = MavenPolicy.Both }); + + /// + public async Task ProbeAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) + { + if (await _local.HasVersionAsync(groupId, artifactId, version, cancellationToken).ConfigureAwait(false)) return ResolutionOutcome.Stored; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return ResolutionOutcome.NotFound; + + // The same gate a download applies, so the preview cannot disagree with a real request. + if (upstream.Settings.Offline) return ResolutionOutcome.Offline; + + var folder = MavenNames.GroupPath(groupId) + "/" + artifactId; + var answer = await _upstream.GetMetadataAsync(upstream, folder + "/" + MavenNames.MetadataFileName, cancellationToken).ConfigureAwait(false); + if (answer.Status == MavenUpstreamStatus.Found && Lists(answer.Content!, version)) return ResolutionOutcome.WouldFetch; + if (answer.Status == MavenUpstreamStatus.Unavailable) return ResolutionOutcome.Unavailable; + + // A repository without artifact-level metadata still has the POM of a version it holds. + var pom = $"{folder}/{version}/{artifactId}-{version}.pom"; + if (_upstream.IsKnownAbsent(upstream, pom)) return ResolutionOutcome.NotFound; + + try + { + using var found = await _upstream.DownloadAsync(upstream, pom, headOnly: true, cancellationToken).ConfigureAwait(false); + + return found == null ? ResolutionOutcome.NotFound : ResolutionOutcome.WouldFetch; + } + catch (MavenUpstreamException) + { + return ResolutionOutcome.Unavailable; + } + } + + private static bool Lists(byte[] metadata, string version) + { + try + { + using var reader = XmlReader.Create(new MemoryStream(metadata), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); + + return XDocument.Load(reader).Root?.Element("versioning")?.Element("versions")?.Elements("version").Any(v => v.Value.Trim() == version) == true; + } + catch (XmlException) + { + return false; + } + } + + // ---- writes: none --------------------------------------------------------------------------------------------------- + + private static Task Refuse(BaGetPrincipal? caller) + => Task.FromResult(caller == null ? MavenResult.Fail(MavenStatus.Unauthorized, "Authentication is required.") : MavenResult.Fail(MavenStatus.Forbidden, NoChanges)); + + /// + public Task PutAsync(BaGetPrincipal? caller, MavenRequestPath path, Stream content, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task DeleteFileAsync(BaGetPrincipal? caller, MavenCoordinate version, string fileName, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task DeleteVersionAsync(BaGetPrincipal? caller, MavenCoordinate version, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task DeleteArtifactAsync(BaGetPrincipal? caller, string groupId, string artifactId, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task CleanupSnapshotsAsync(BaGetPrincipal? caller, MavenCoordinate version, int keep, CancellationToken cancellationToken) => Refuse(caller); +} diff --git a/src/BaGet.Core/Formats/Maven/VirtualMavenRepository.cs b/src/BaGet.Core/Formats/Maven/VirtualMavenRepository.cs new file mode 100644 index 000000000..79bcc06d1 --- /dev/null +++ b/src/BaGet.Core/Formats/Maven/VirtualMavenRepository.cs @@ -0,0 +1,419 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using System.Xml.Linq; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Core; + +/// +/// of a Maven repository: one repository made of its members, +/// local or remote, in resolution order (: only the members the caller may read, each asked in +/// its own scope, so its storage, upstream and rules apply; a member that fails is logged and skipped). +/// +/// +/// Files and their checksums come from the first member that has them, so a file and its .sha1 always agree. +/// Metadata. Artifact-level maven-metadata.xml is merged: versions is the union (ordered as Maven orders +/// versions), latest and release are the first member's own that the merged list contains (so they follow the member +/// order, not the highest version; when no member names one, the highest), lastUpdated the latest. The version-level +/// document (a snapshot's timestamped builds) is the first member's that has it, because the builds it names are that member's files. +/// A group-level document (plugin prefixes) is the union of the members' plugins, a prefix once. The checksums of metadata are those +/// of the merged document. +/// Pages and search merge the members' artifacts by group:artifact (the first member's entry wins a version). +/// Writes go to the deploy repository, with that repository's rules and the caller's rights there: the HTTP routes and pages are +/// moved to it before they reach this class (RepositoryResolutionMiddleware, RepositoryPageGate); a caller of the service +/// gets the same through this class. Without a deploy repository they are refused (403). +/// +public sealed class VirtualMavenRepository : IMavenRepository +{ + // The most search hits read from one member for a page: a merged page of skip+take needs at most that many from each. + internal const int MaxScanPerMember = 1000; + + private readonly IRepositoryContext _repository; + private readonly VirtualRepositoryReader _reader; + private readonly IVirtualRepositories _virtuals; + + public VirtualMavenRepository(IRepositoryContext repository, VirtualRepositoryReader reader, IVirtualRepositories virtuals) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + } + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + /// A metadata path that can name a version or an artifact is the version when a member says so (its own resolution), else the artifact. + public async Task ResolveAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + if (path.Candidates.Count == 0) return null; + if (path.Kind == MavenPathKind.File) return path.Candidates[0]; + + // A single candidate (a path two folders deep) can still be a group's plugin list: a member that says so (null) makes the + // document a group-level one, judged by the repository's Read only. + var single = path.Candidates.Count == 1; + if (single && (path.GroupOnly == null || path.Candidates[0].Version != null)) return path.Candidates[0]; + + foreach (var member in await _reader.ReadableMembersAsync(null, cancellationToken).ConfigureAwait(false)) + { + MavenCoordinate? resolved; + try + { + resolved = await _reader.InMemberAsync(member, sp => sp.GetRequiredService().ResolveAsync(path, cancellationToken)).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + continue; + } + + if (single && resolved == null) return null; + + // A member answers the artifact level when it knows nothing; only the first candidate is a positive answer. + if (resolved != null && resolved == path.Candidates[0]) return resolved; + } + + return path.Candidates[^1]; + } + + /// + public async Task OpenAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + + if (path.Kind == MavenPathKind.File) + { + return await _reader.FirstAsync( + path.Candidates[0].Name, + sp => sp.GetRequiredService().OpenAsync(path, cancellationToken), + cancellationToken).ConfigureAwait(false); + } + + return await OpenMetadataAsync(path, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task HeadAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + + if (path.Kind == MavenPathKind.File) + { + return await _reader.FirstAsync( + path.Candidates[0].Name, + sp => sp.GetRequiredService().HeadAsync(path, cancellationToken), + cancellationToken).ConfigureAwait(false); + } + + // Metadata is small and merged: the same work as a GET. + return await OpenMetadataAsync(path, cancellationToken).ConfigureAwait(false); + } + + private async Task OpenMetadataAsync(MavenRequestPath path, CancellationToken cancellationToken) + { + var plain = path.Plain; + var coordinate = await ResolveAsync(path, cancellationToken).ConfigureAwait(false); + + // Each readable member's own document, in member order (a member that has none or fails contributes nothing). + var documents = new List<(XElement Root, DateTime Modified)>(); + foreach (var member in await _reader.ReadableMembersAsync(coordinate?.Name, cancellationToken).ConfigureAwait(false)) + { + try + { + var found = await _reader.InMemberAsync(member, async sp => + { + using var download = await sp.GetRequiredService().OpenAsync(plain, cancellationToken).ConfigureAwait(false); + if (download == null) return ((XElement, DateTime)?)null; + + using var buffer = new MemoryStream(); + await download.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); + buffer.Position = 0; + using var reader = XmlReader.Create(buffer, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); + + return (XDocument.Load(reader).Root!, download.LastModified); + }).ConfigureAwait(false); + + if (found != null) documents.Add(found.Value); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + // A member that cannot answer, or answers with something that is not metadata, is skipped like any failing member. + } + } + + if (documents.Count == 0) return null; + + var modified = documents.Max(d => d.Modified); + var roots = documents.Select(d => d.Root).ToList(); + + // What a document is follows from its content, not from the path (a path can be read several ways): plugin prefixes, a + // version's (a snapshot's builds), or an artifact's list of versions. + string xml; + if (roots.Any(r => r.Element("plugins") != null)) + { + xml = MergePlugins(roots); + } + else if (roots[0].Element("version") != null) + { + // The builds a snapshot document names are files of the member that wrote it: the first member's document, as is. + xml = MetadataDocument(roots[0].ToString()); + } + else + { + var group = roots.Select(r => r.Element("groupId")?.Value.Trim()).FirstOrDefault(g => !string.IsNullOrEmpty(g)) ?? coordinate?.GroupId ?? string.Empty; + var artifact = roots.Select(r => r.Element("artifactId")?.Value.Trim()).FirstOrDefault(a => !string.IsNullOrEmpty(a)) ?? coordinate?.ArtifactId ?? string.Empty; + xml = MergeVersions(new MavenCoordinate(group, artifact, null), roots, modified); + } + + var content = System.Text.Encoding.UTF8.GetBytes(xml); + if (path.ChecksumAlgorithm != null) + { + var text = System.Text.Encoding.ASCII.GetBytes(RemoteMavenRepository.Hex(path.ChecksumAlgorithm, content)); + + return new MavenDownload(new MemoryStream(text, writable: false), text.Length, "text/plain", path.FileName, modified); + } + + return new MavenDownload(new MemoryStream(content, writable: false), content.Length, "application/xml", path.FileName, modified) + { + Sha1 = RemoteMavenRepository.Hex("sha1", content), + Md5 = RemoteMavenRepository.Hex("md5", content), + Sha256 = RemoteMavenRepository.Hex("sha256", content), + }; + } + + private static string MetadataDocument(string root) => new XDeclaration("1.0", "UTF-8", null) + Environment.NewLine + root + Environment.NewLine; + + /// The artifact-level document of the members' documents: see . + internal static string MergeVersions(MavenCoordinate artifact, IReadOnlyList documents, DateTime lastUpdated) + { + var versions = new List(); + string? latest = null, release = null; + foreach (var document in documents) + { + var versioning = document.Element("versioning"); + versions.AddRange(versioning?.Element("versions")?.Elements("version").Select(v => v.Value.Trim()).Where(v => v.Length > 0) ?? Enumerable.Empty()); + } + + var merged = new HashSet(versions, StringComparer.Ordinal); + foreach (var document in documents) + { + var versioning = document.Element("versioning"); + var documentLatest = versioning?.Element("latest")?.Value.Trim(); + var documentRelease = versioning?.Element("release")?.Value.Trim(); + if (latest == null && documentLatest != null && merged.Contains(documentLatest)) latest = documentLatest; + if (release == null && documentRelease != null && merged.Contains(documentRelease)) release = documentRelease; + } + + return MavenMetadata.ForArtifact(artifact.GroupId, artifact.ArtifactId, merged, lastUpdated, latest, release); + } + + // Plugin prefixes: the first member's entry for a prefix and artifact wins. + private static string MergePlugins(IReadOnlyList documents) + { + var plugins = new List(); + var seen = new HashSet(StringComparer.Ordinal); + foreach (var plugin in documents.SelectMany(d => d.Element("plugins")?.Elements("plugin") ?? Enumerable.Empty())) + { + var key = (plugin.Element("prefix")?.Value.Trim() ?? string.Empty) + "|" + (plugin.Element("artifactId")?.Value.Trim() ?? string.Empty); + if (seen.Add(key)) plugins.Add(new XElement(plugin)); + } + + return MetadataDocument(new XElement("metadata", new XElement("plugins", plugins)).ToString()); + } + + /// + public async Task SearchAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) + { + skip = Math.Max(skip, 0); + take = Math.Clamp(take, 0, 250); + var window = Math.Min(skip + take, MaxScanPerMember); + + var byName = new SortedDictionary(StringComparer.Ordinal); + var complete = true; + var upperBound = 0; + + foreach (var member in await _reader.ReadableMembersAsync(null, cancellationToken).ConfigureAwait(false)) + { + MavenSearchPage? page; + try + { + var asked = member; + page = await _reader.InMemberAsync(member, async sp => await sp.GetRequiredService().SearchAsync( + text, + 0, + window, + async (name, token) => await _reader.CanReadInMemberAsync(asked, name, token).ConfigureAwait(false) + && (canRead == null || await canRead(name, token).ConfigureAwait(false)), + cancellationToken).ConfigureAwait(false)).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + complete = false; + continue; + } + + if (page == null) continue; + + upperBound += page.Total; + if (page.Total > page.Hits.Count) complete = false; + foreach (var hit in page.Hits) byName.TryAdd(hit.CoordinateName, hit); + } + + // Exact while every member was read completely; else the most the members could hold together. + var total = complete ? byName.Count : Math.Max(byName.Count, upperBound); + + return new MavenSearchPage(total, byName.Values.Skip(skip).Take(take).ToList()); + } + + /// + public async Task GetArtifactAsync(string groupId, string artifactId, CancellationToken cancellationToken) + { + var members = await _reader.AllAsync( + MavenNames.ArtifactName(groupId, artifactId), + async sp => (await sp.GetRequiredService().GetArtifactAsync(groupId, artifactId, cancellationToken).ConfigureAwait(false))!, + cancellationToken).ConfigureAwait(false); + if (members.Count == 0) return null; + + var versions = new Dictionary(StringComparer.Ordinal); + foreach (var version in members.SelectMany(m => m.Value.Versions)) versions.TryAdd(version.Version, version); + + return new MavenArtifactInfo( + groupId, + artifactId, + members.Min(m => m.Value.Created), + members.Max(m => m.Value.Modified), + versions.Values.OrderByDescending(v => v.Version, Comparer.Create(MavenNames.CompareVersions)).ToList()); + } + + /// + public Task GetVersionAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) + => _reader.FirstAsync( + MavenNames.ArtifactName(groupId, artifactId), + sp => sp.GetRequiredService().GetVersionAsync(groupId, artifactId, version, cancellationToken), + cancellationToken); + + /// + public Task GetSettingsAsync(CancellationToken cancellationToken) + => Task.FromResult(new MavenRepositorySettings { Policy = MavenPolicy.Both }); + + /// + public async Task ProbeAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) + { + var worst = ResolutionOutcome.NotFound; + foreach (var member in await _reader.ReadableMembersAsync(MavenNames.ArtifactName(groupId, artifactId), cancellationToken).ConfigureAwait(false)) + { + var outcome = await _reader.InMemberAsync(member, sp => sp.GetRequiredService().ProbeAsync(groupId, artifactId, version, cancellationToken)).ConfigureAwait(false); + if (outcome is ResolutionOutcome.Stored or ResolutionOutcome.WouldFetch) return outcome; + if (outcome is ResolutionOutcome.Unavailable or ResolutionOutcome.Offline) worst = outcome; + } + + return worst; + } + + // ---- writes: the deploy repository ---------------------------------------------------------------------------------- + + private async Task OnDeployAsync(BaGetPrincipal? caller, Func> write, CancellationToken cancellationToken) + { + if (caller == null) return MavenResult.Fail(MavenStatus.Unauthorized, "Authentication is required."); + + var target = await _virtuals.DeployTargetAsync(_repository.Current, cancellationToken).ConfigureAwait(false); + if (target == null) return MavenResult.Fail(MavenStatus.Forbidden, "This virtual repository has no deploy repository, so it takes no changes."); + + return await _reader.InMemberAsync(target, sp => write(sp.GetRequiredService())).ConfigureAwait(false); + } + + /// + public Task PutAsync(BaGetPrincipal? caller, MavenRequestPath path, Stream content, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.PutAsync(caller, path, content, cancellationToken), cancellationToken); + + /// + public Task DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.DeployAsync(caller, deployment, cancellationToken), cancellationToken); + + /// + public Task DeleteFileAsync(BaGetPrincipal? caller, MavenCoordinate version, string fileName, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.DeleteFileAsync(caller, version, fileName, cancellationToken), cancellationToken); + + /// + public Task DeleteVersionAsync(BaGetPrincipal? caller, MavenCoordinate version, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.DeleteVersionAsync(caller, version, cancellationToken), cancellationToken); + + /// + public Task DeleteArtifactAsync(BaGetPrincipal? caller, string groupId, string artifactId, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.DeleteArtifactAsync(caller, groupId, artifactId, cancellationToken), cancellationToken); + + /// + public Task CleanupSnapshotsAsync(BaGetPrincipal? caller, MavenCoordinate version, int keep, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.CleanupSnapshotsAsync(caller, version, keep, cancellationToken), cancellationToken); +} + +/// +/// The everything resolves: it forwards to the repository that fits the kind of the request's +/// repository ( for a local one, , ), +/// so the routes and pages never ask which. Resolved per call, because a write to a virtual repository continues in its deploy repository. +/// +public sealed class RepositoryMavenRepository : IMavenRepository +{ + private readonly IRepositoryContext _repository; + private readonly IServiceProvider _services; + + public RepositoryMavenRepository(IRepositoryContext repository, IServiceProvider services) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + private IMavenRepository Inner => _repository.Current.Kind switch + { + RepositoryKind.Remote => _services.GetRequiredService(), + RepositoryKind.Virtual => _services.GetRequiredService(), + _ => _services.GetRequiredService(), + }; + + /// + public Task ResolveAsync(MavenRequestPath path, CancellationToken cancellationToken) => Inner.ResolveAsync(path, cancellationToken); + + /// + public Task OpenAsync(MavenRequestPath path, CancellationToken cancellationToken) => Inner.OpenAsync(path, cancellationToken); + + /// + public Task HeadAsync(MavenRequestPath path, CancellationToken cancellationToken) => Inner.HeadAsync(path, cancellationToken); + + /// + public Task PutAsync(BaGetPrincipal? caller, MavenRequestPath path, Stream content, CancellationToken cancellationToken) => Inner.PutAsync(caller, path, content, cancellationToken); + + /// + public Task DeployAsync(BaGetPrincipal? caller, MavenDeployment deployment, CancellationToken cancellationToken) => Inner.DeployAsync(caller, deployment, cancellationToken); + + /// + public Task DeleteFileAsync(BaGetPrincipal? caller, MavenCoordinate version, string fileName, CancellationToken cancellationToken) => Inner.DeleteFileAsync(caller, version, fileName, cancellationToken); + + /// + public Task DeleteVersionAsync(BaGetPrincipal? caller, MavenCoordinate version, CancellationToken cancellationToken) => Inner.DeleteVersionAsync(caller, version, cancellationToken); + + /// + public Task DeleteArtifactAsync(BaGetPrincipal? caller, string groupId, string artifactId, CancellationToken cancellationToken) => Inner.DeleteArtifactAsync(caller, groupId, artifactId, cancellationToken); + + /// + public Task CleanupSnapshotsAsync(BaGetPrincipal? caller, MavenCoordinate version, int keep, CancellationToken cancellationToken) => Inner.CleanupSnapshotsAsync(caller, version, keep, cancellationToken); + + /// + public Task SearchAsync(string? text, int skip, int take, Func>? canRead, CancellationToken cancellationToken) + => Inner.SearchAsync(text, skip, take, canRead, cancellationToken); + + /// + public Task GetArtifactAsync(string groupId, string artifactId, CancellationToken cancellationToken) => Inner.GetArtifactAsync(groupId, artifactId, cancellationToken); + + /// + public Task GetVersionAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) => Inner.GetVersionAsync(groupId, artifactId, version, cancellationToken); + + /// + public Task GetSettingsAsync(CancellationToken cancellationToken) => Inner.GetSettingsAsync(cancellationToken); + + /// + public Task ProbeAsync(string groupId, string artifactId, string version, CancellationToken cancellationToken) => Inner.ProbeAsync(groupId, artifactId, version, cancellationToken); +} diff --git a/src/BaGet.Core/Formats/Npm/INpmRegistry.cs b/src/BaGet.Core/Formats/Npm/INpmRegistry.cs new file mode 100644 index 000000000..ede0e6ebf --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/INpmRegistry.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// How an operation of the npm registry ended; the HTTP routes and the pages map it the same way. +public enum NpmStatus +{ + /// Done. + Ok, + + /// Done, and something new exists (a version was published). + Created, + + /// Nobody is authenticated (HTTP 401). + Unauthorized, + + /// The caller is not allowed (HTTP 403). + Forbidden, + + /// No such package, version, tag or file (HTTP 404). + NotFound, + + /// The request clashes with what exists, such as publishing over a published version (HTTP 409). + Conflict, + + /// The request is not valid (HTTP 400); says why. + Invalid, +} + +/// The outcome of an operation of the registry. +/// How it ended. +/// A sentence for the person or client when it did not succeed (or a note when it did). +/// The package the operation was about, when it succeeded (the name a publish created a version of). +public sealed record NpmResult(NpmStatus Status, string? Message = null, string? Subject = null) +{ + /// Whether the operation was done. + public bool Succeeded => Status is NpmStatus.Ok or NpmStatus.Created; + + internal static NpmResult Ok(string? message = null) => new(NpmStatus.Ok, message); + + internal static NpmResult Created(string? message = null, string? subject = null) => new(NpmStatus.Created, message, subject); + + internal static NpmResult Fail(NpmStatus status, string message) => new(status, message); +} + +/// One published version as stored. +/// The version string as published. +/// When it was published. +/// The deprecation message, or null. +/// Bytes of the tarball. +/// The tarball's SRI string (sha512-…). +/// The tarball's SHA-1 in hex. +/// The version's manifest (package.json content and dist), without the tarball URL. +public sealed record NpmVersionInfo(string Version, DateTime Published, string? Deprecated, long TarballSize, string Integrity, string Shasum, JsonObject Manifest) +{ + /// The manifest's description, or null. + public string? Description => Manifest["description"] is JsonValue value && value.TryGetValue(out var text) ? text : null; + + /// The manifest's readme, or null. + public string? Readme => Manifest["readme"] is JsonValue value && value.TryGetValue(out var text) ? text : null; + + /// The manifest's license when it is a string, or null. + public string? License => Manifest["license"] is JsonValue value && value.TryGetValue(out var text) ? text : null; + + /// The manifest's keywords that are strings. + public IReadOnlyList Keywords => (Manifest["keywords"] as JsonArray)? + .Select(k => k is JsonValue v && v.TryGetValue(out var s) ? s : null) + .Where(s => !string.IsNullOrEmpty(s)).Select(s => s!).ToList() ?? new List(); + + /// The names and ranges of an object-valued manifest field: dependencies, peerDependencies… + public IReadOnlyList> Map(string field) => (Manifest[field] as JsonObject)? + .Select(p => new KeyValuePair(p.Key, p.Value is JsonValue v && v.TryGetValue(out var s) ? s : p.Value?.ToJsonString() ?? string.Empty)) + .OrderBy(p => p.Key, StringComparer.Ordinal).ToList() ?? new List>(); +} + +/// A package with its versions and dist-tags, as stored. +/// The name (@scope/name for a scoped package). +/// The first publish. +/// The last change. +/// Tag to version. +/// Every version, oldest first by semantic version. +public sealed record NpmPackageInfo(string Name, DateTime Created, DateTime Modified, IReadOnlyDictionary DistTags, IReadOnlyList Versions) +{ + /// The version latest points at, or the highest one when there is no such tag. + public NpmVersionInfo? Latest + { + get + { + if (DistTags.TryGetValue("latest", out var tagged)) + { + var found = Versions.FirstOrDefault(v => v.Version == tagged); + if (found != null) return found; + } + + var highest = NpmNames.Highest(Versions.Select(v => v.Version)); + + return highest == null ? null : Versions.First(v => v.Version == highest); + } + } + + /// The document revision clients send back on a write (?write=true reads, /-rev/{rev} writes): changes with every change of the package. + public string Revision => $"{Versions.Count}-{Modified.Ticks:x}"; +} + +/// One package in a search result. +/// The name. +/// The latest version. +/// Its description. +/// Its keywords. +/// The last change. +public sealed record NpmSearchHit(string Name, string? Version, string? Description, IReadOnlyList Keywords, DateTime Modified); + +/// A page of packages. +/// All matches. +/// This page, ordered by name. +public sealed record NpmSearchPage(int Total, IReadOnlyList Hits); + +/// A tarball being served. +/// The bytes; the caller disposes it. +/// Its size. +/// Its SRI string. +public sealed record NpmTarball(Stream Content, long Length, string Integrity); + +/// A version to publish. +/// The package name. +/// The version. +/// The version's manifest as the client sent it (package.json plus what npm adds). +/// The dist-tag to point at the version. +/// The tarball: seekable and readable; it is read from its start, and the caller disposes it. +/// The SRI string the client computed, or null; a mismatch refuses the publish. +/// The SHA-1 the client computed, or null; a mismatch refuses the publish. +/// The size the client declared, or null; a mismatch refuses the publish. +public sealed record NpmPublication( + string Name, + string Version, + JsonObject Manifest, + string Tag, + Stream Tarball, + string? ExpectedIntegrity = null, + string? ExpectedShasum = null, + long? ExpectedLength = null); + +/// +/// The npm registry of the current repository (): what the HTTP routes and the pages do with +/// packages. Reads take no caller (the route or page has already required Read); every write takes the caller and applies the +/// access model and package ownership through , so a route and a page cannot +/// differ in who may do what. Names are the lower-case names accepts. +/// +public interface INpmRegistry +{ + /// The package, or null when the repository has none of that name. + Task GetPackageAsync(string name, CancellationToken cancellationToken); + + /// + /// The packument (the registry's document for a package). With the install-only form + /// (application/vnd.npm.install-v1+json) that clients prefer for npm install. Null when there is no such package. + /// + Task GetPackumentAsync(string name, bool abbreviated, CancellationToken cancellationToken); + + /// The tarball of a version, or null when the package, version or file does not exist. + Task OpenTarballAsync(string name, string file, CancellationToken cancellationToken); + + /// Publishes a version (npm publish). when done. + Task PublishAsync(BaGetPrincipal? caller, NpmPublication publication, CancellationToken cancellationToken); + + /// + /// Publishes a tarball chosen in the browser: the name and version come from its package.json, the tag is + /// . The same checks as . + /// + Task PublishTarballAsync(BaGetPrincipal? caller, Stream tarball, string tag, CancellationToken cancellationToken); + + /// The dist-tags of a package (tag to version), or null when there is no such package. + Task?> GetDistTagsAsync(string name, CancellationToken cancellationToken); + + /// Points at (Deploy). + Task SetDistTagAsync(BaGetPrincipal? caller, string name, string tag, string version, CancellationToken cancellationToken); + + /// Removes (Deploy). + Task RemoveDistTagAsync(BaGetPrincipal? caller, string name, string tag, CancellationToken cancellationToken); + + /// + /// Sets or clears (null or empty message) the deprecation of existing versions (Annotate); versions not in the dictionary + /// are untouched. + /// + Task DeprecateAsync(BaGetPrincipal? caller, string name, IReadOnlyDictionary messages, CancellationToken cancellationToken); + + /// + /// Unpublishes versions and deletes their tarballs. Deploy is enough for a version younger than + /// ; an older one needs Delete. The dist-tags that pointed at a removed version + /// are re-pointed with (tag to version) when it names a remaining version, else removed, and + /// latest falls back to the highest remaining version. Removing the last version removes the package. + /// + Task UnpublishVersionsAsync( + BaGetPrincipal? caller, + string name, + IReadOnlyCollection versions, + IReadOnlyDictionary? newTags, + CancellationToken cancellationToken); + + /// Unpublishes the whole package: every version and tarball, and the package itself. + Task UnpublishPackageAsync(BaGetPrincipal? caller, string name, CancellationToken cancellationToken); + + /// + /// Deletes a tarball file (DELETE /{name}/-/{file}/-rev/{rev}, the last step of npm unpublish). When its + /// version is still published this is ; when the version is already gone it removes the + /// leftover file (Deploy). + /// + Task DeleteTarballAsync(BaGetPrincipal? caller, string name, string file, CancellationToken cancellationToken); + + /// + /// Packages whose name contains (all when null or empty), ordered by name. With + /// only the packages it accepts are listed and counted (the per-package Read of the access model: + /// a listing must not name a package that its page would hide); without it every package of the repository is. + /// + Task SearchAsync( + string? text, + int skip, + int take, + Func>? canRead = null, + CancellationToken cancellationToken = default); + + /// + /// Where of would come from, without fetching or storing anything: + /// when the repository holds it, when it is a + /// remote repository whose upstream has it, / / + /// otherwise. What the resolution preview of a virtual repository asks of each member. + /// + Task ProbeAsync(string name, string version, CancellationToken cancellationToken); +} + +/// +/// The upstream of a remote npm repository could not be reached (or refused the credentials, or sent something that is not a +/// registry's answer) and nothing stored or remembered can answer instead. The HTTP route answers 502; a virtual repository +/// skips the member. The message names no URL and no credential. +/// +public sealed class NpmUpstreamException : Exception +{ + /// What failed, safe to show. + public NpmUpstreamException(string message) + : base(message) + { + } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmEntities.cs b/src/BaGet.Core/Formats/Npm/NpmEntities.cs new file mode 100644 index 000000000..ab9facd5d --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmEntities.cs @@ -0,0 +1,85 @@ +using System; + +namespace BaGet.Core; + +/// +/// An npm package (a packument) of one repository: the name and the facts shared by all its versions. Scoped names keep +/// the scope (@scope/name). Written by the npm format module of a later phase; the tables exist from the format layer +/// on so the data model is settled on all four providers before any protocol code depends on it. +/// +public class NpmPackage : IRepositoryScoped +{ + public int Key { get; set; } + + /// + /// The owning repository; see . + /// + public int RepositoryKey { get; set; } + + /// + /// The full package name, lower-cased (npm only allows lower case for new names): left-pad or + /// @scope/name. At most AbstractContext.MaxNpmNameLength characters, npm's own limit. Unique per repository. + /// + public string? Name { get; set; } + + /// The first publish (the packument's time.created). + public DateTime Created { get; set; } + + /// The last change to any version or dist-tag (the packument's time.modified). + public DateTime Modified { get; set; } +} + +/// +/// One published version of an . The tarball is not in the row: it lives in storage +/// (npm/{name}/-/{file} under the repository's prefix) and this row records what a client verifies it with. +/// +public class NpmVersion +{ + public int Key { get; set; } + + /// The . Required; deleting the package deletes its versions. + public int PackageKey { get; set; } + + /// The semver version as published (npm compares versions as semver, build metadata ignored). Unique per package. + public string? Version { get; set; } + + /// The Subresource Integrity string of the tarball (sha512-…), as clients check it. + public string? Integrity { get; set; } + + /// The SHA-1 of the tarball in hex (dist.shasum), still sent by every npm client. + public string? Shasum { get; set; } + + /// The tarball's size in bytes. + public long TarballSize { get; set; } + + /// + /// The version manifest (the package.json object the client sent for this version, plus the server's dist), as + /// JSON. Unbounded: it carries dependencies, scripts, readme and whatever the publisher put in. The packument is built from + /// these, so the registry answers exactly what was published. + /// + public string? Manifest { get; set; } + + /// The deprecation message set with npm deprecate; null when not deprecated. An empty message un-deprecates, so it is stored as null. + public string? Deprecated { get; set; } + + public DateTime Published { get; set; } +} + +/// +/// A dist-tag of an (latest, next…): a name that points to a version string. Unique per +/// package and tag. There is no foreign key to : the format module keeps the tag and its version in step +/// in one save (unpublishing a version moves or removes its tags). +/// +public class NpmDistTag +{ + public int Key { get; set; } + + /// The . Required; deleting the package deletes its tags. + public int PackageKey { get; set; } + + /// The tag name; npm forbids names that are valid semver ranges. + public string? Tag { get; set; } + + /// The the tag points to. + public string? Version { get; set; } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmFormatModule.cs b/src/BaGet.Core/Formats/Npm/NpmFormatModule.cs new file mode 100644 index 000000000..0f83568f3 --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmFormatModule.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// npm on the format layer: the registry protocol under npm/ of the repository base (/npm/ is never served for +/// default, which is NuGet; a repository web is at /r/web/npm/), tarballs under npm/… in storage. +/// Local repositories hold packages; a remote one caches an upstream registry (); a virtual one merges +/// members (). See . +/// +public class NpmFormatModule : IFormatModule +{ + /// + public RepositoryFormat Format => RepositoryFormat.Npm; + + /// + public string DisplayName => "npm"; + + /// + public string RoutePrefix => "npm"; + + /// + public string FeedPath => "npm/"; + + /// + public IReadOnlyCollection CreatableKinds { get; } = new[] { RepositoryKind.Local, RepositoryKind.Remote }; + + /// + public bool SupportsVirtual => true; + + /// + public IReadOnlyList StorageFolders { get; } = new[] { NpmNames.StorageFolder }; + + /// + /// None: an npm repository is a name. + public IReadOnlyList CreateFields { get; } = Array.Empty(); + + /// + public string? CreateSettings(IReadOnlyDictionary fields) => null; + + /// + public IReadOnlyList RepositoryLinks(RepositoryInfo repository) => new[] + { + FormatLink.ToScreen("browse", "Browse", "NpmBrowse", "Packages"), + FormatLink.ToScreen("upload", "Upload", "NpmBrowse", "Upload", needsUploads: true), + FormatLink.ToPath("registry", "Registry", "npm/"), + }; + + /// + public async Task> CountArtifactsAsync(IContext context, CancellationToken cancellationToken) + => await context.NpmPackages! + .IgnoreQueryFilters() + .GroupBy(p => p.RepositoryKey) + .Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken) + .ConfigureAwait(false); + + /// + public async Task GetUsageAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + var packages = await context.NpmPackages!.IgnoreQueryFilters().CountAsync(e => e.RepositoryKey == repositoryKey, cancellationToken).ConfigureAwait(false); + + return new FormatUsage(packages, PendingWork: false); + } + + /// + /// + /// An empty repository has no packages, so versions and dist-tags (which cascade from a package) are gone already; what + /// is left is the owner rows, which outlive their package as NuGet's do. + /// + public async Task StagePurgeAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + context.NpmPackages!.RemoveRange(await context.NpmPackages!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + context.PackageOwners!.RemoveRange(await context.PackageOwners!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + } +} + +/// npm's : packages whose name contains the query (). +public class NpmFormatSearchProvider : IFormatSearchProvider +{ + private readonly INpmRegistry _registry; + + /// The registry of the request's repository. + public NpmFormatSearchProvider(INpmRegistry registry) + { + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Npm; + + /// + public async Task SearchAsync(FormatSearchQuery query, CancellationToken cancellationToken) + { + if (query == null) throw new ArgumentNullException(nameof(query)); + + var page = await _registry.SearchAsync(query.Query, query.Skip, query.Take, canRead: null, cancellationToken).ConfigureAwait(false); + + return new FormatSearchPage( + page.Total, + page.Hits + .Where(h => query.IncludePrerelease || h.Version == null || !NpmNames.IsPrerelease(h.Version)) + .Select(h => new FormatSearchHit(h.Name, h.Version, h.Description, Downloads: 0)) + .ToList()); + } +} + +/// +/// Issues the tokens npm login stores (_authToken). A token is an API key of the user (so it is listed and revoked +/// on the account's API keys page and carries the same rules), limited to the repository it was issued for. Implemented by the +/// accounts feature; a host without accounts has none, and its npm clients use the global API key as the token. +/// +public interface INpmTokenService +{ + /// + /// Checks the password and issues a token for ; no token when the user name or password is + /// wrong, the account is locked out, or the account needs more than a password (two-factor authentication): such a user + /// creates an API key on the account page instead. + /// + Task LoginAsync(string? userName, string? password, RepositoryInfo repository, CancellationToken cancellationToken); + + /// Revokes when it is an API key of (npm logout). + Task RevokeAsync(BaGetPrincipal caller, string token, CancellationToken cancellationToken); +} + +/// The answer to . +/// The token, or null. +/// Why there is none. +/// Whether the account is locked out (the client is told to wait). +public sealed record NpmLoginResult(string? Token, string? Error = null, bool LockedOut = false); diff --git a/src/BaGet.Core/Formats/Npm/NpmFormatScanner.cs b/src/BaGet.Core/Formats/Npm/NpmFormatScanner.cs new file mode 100644 index 000000000..9ff77b33e --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmFormatScanner.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// What an npm package version is made of for scanning: itself and its dependencies that name one exact version (a range +/// such as ^1.2.0 is resolved by the client at install time and cannot be judged here). +/// +public static class NpmScanComponents +{ + /// The OSV ecosystem name. + public const string Ecosystem = "npm"; + + /// The components of (the version's package.json). + public static IReadOnlyList Of(string name, string version, JsonObject? manifest) + { + var result = new List { new(Ecosystem, name, version) }; + if (manifest?["dependencies"] is JsonObject dependencies) + { + foreach (var dependency in dependencies) + { + if (dependency.Value is not JsonValue value || !value.TryGetValue(out var range)) continue; + + var exact = range.Trim(); + if (exact.Length == 0 || !char.IsDigit(exact[0]) || !NuGetVersion.TryParse(exact, out _)) continue; + + var component = new ScanComponent(Ecosystem, dependency.Key, exact); + if (!result.Contains(component)) result.Add(component); + } + } + + return result; + } +} + +/// npm's : the stored versions and their pinned dependencies against OSV. +public sealed class NpmFormatScanner : IFormatScanner +{ + private readonly IContext _context; + + public NpmFormatScanner(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Npm; + + /// + public async Task> ListComponentsAsync(string name, string version, CancellationToken cancellationToken) + { + if (_context is NullContext) return Array.Empty(); + + var manifest = await _context.NpmVersions! + .AsNoTracking() + .Join(_context.NpmPackages!.Where(p => p.Name == name), v => v.PackageKey, p => p.Key, (v, p) => new { v.Version, v.Manifest }) + .Where(v => v.Version == version) + .Select(v => v.Manifest) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + if (manifest == null) return Array.Empty(); + + JsonObject? json = null; + try + { + json = JsonNode.Parse(manifest) as JsonObject; + } + catch (System.Text.Json.JsonException) + { + // A manifest that does not parse still names the package itself. + } + + return NpmScanComponents.Of(name, version, json); + } + + /// + public async Task> ListArtifactsAsync(CancellationToken cancellationToken) + { + if (_context is NullContext) return Array.Empty(); + + var rows = await _context.NpmVersions! + .AsNoTracking() + .Join(_context.NpmPackages!, v => v.PackageKey, p => p.Key, (v, p) => new { p.Name, v.Version }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + return rows.Select(r => new ScanArtifact(r.Name!, r.Version!)).ToList(); + } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmNames.cs b/src/BaGet.Core/Formats/Npm/NpmNames.cs new file mode 100644 index 000000000..4c9c40d37 --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmNames.cs @@ -0,0 +1,246 @@ +using System; +using System.Text.RegularExpressions; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// The rules for npm package names, versions, tarball file names and storage paths: one definition, used by the routes, the +/// registry service, the pages and the storage layout, so a name that is accepted in one place is accepted everywhere and a +/// name that could become a path outside the package's folder is accepted nowhere. +/// +public static class NpmNames +{ + /// The folder (below the repository's storage prefix) that holds tarballs: npm/{name}/-/{file}. + public const string StorageFolder = "npm"; + + /// The longest name npm accepts, scope included. + public const int MaxLength = AbstractContext.MaxNpmNameLength; + + // One segment of a name: URL safe, lower case, not starting with '.', '_' or '-' ('-' is the literal segment of the + // registry's own routes: /-/ping, /{name}/-/{file}). npm allows more in legacy names; new names are held to this. + private static readonly Regex Part = new("^[a-z0-9~][a-z0-9._~-]*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + // The same shape for a name that is only looked up: npm's legacy names (registry.npmjs.org still serves JSONStream, + // Base64, ...) have upper case letters. Nothing else is relaxed, so the name stays a safe path segment. + private static readonly Regex LookupPart = new("^[A-Za-z0-9~][A-Za-z0-9._~-]*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly Regex TagShape = new("^[A-Za-z0-9._~-]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly string[] Reserved = { "node_modules", "favicon.ico" }; + + /// + /// Validates as a name to publish or look up: left-pad or @scope/name, lower case, + /// at most characters. + /// + /// The name as the client wrote it (an encoded %2f is decoded first). + /// The decoded name when valid. + /// Why not, when invalid. + public static bool TryParse(string? name, out string normalized, out string error) + => TryParse(name, legacy: false, out normalized, out error); + + /// + /// Validates as a name to look up (read, proxy to an upstream, purge from a cache): like + /// but upper case letters are accepted, since packages published + /// long ago under such names still exist upstream. The case is kept (an upstream registry is asked for the name as + /// written). Publishing and every other change keep the strict rule. + /// + /// The name as the client wrote it (an encoded %2f is decoded first). + /// The decoded name when valid. + /// Why not, when invalid. + public static bool TryParseLookup(string? name, out string normalized, out string error) + => TryParse(name, legacy: true, out normalized, out error); + + private static bool TryParse(string? name, bool legacy, out string normalized, out string error) + { + var part = legacy ? LookupPart : Part; + normalized = string.Empty; + error = string.Empty; + + if (string.IsNullOrEmpty(name)) + { + error = "A package name is required."; + return false; + } + + string decoded; + try + { + decoded = Uri.UnescapeDataString(name); + } + catch (UriFormatException) + { + error = "The package name is not valid."; + return false; + } + + if (decoded.Length > MaxLength) + { + error = $"A package name has at most {MaxLength} characters."; + return false; + } + + if (!legacy && decoded != decoded.ToLowerInvariant()) + { + error = "A package name must be lower case."; + return false; + } + + string unscoped; + if (decoded.StartsWith('@')) + { + var slash = decoded.IndexOf('/'); + if (slash < 2 || slash == decoded.Length - 1 || decoded.IndexOf('/', slash + 1) >= 0) + { + error = "A scoped package name looks like @scope/name."; + return false; + } + + if (!part.IsMatch(decoded.Substring(1, slash - 1))) + { + error = "The scope of a package name has only lower case letters, digits and . _ ~ - characters."; + return false; + } + + unscoped = decoded.Substring(slash + 1); + } + else + { + unscoped = decoded; + } + + if (!part.IsMatch(unscoped) || unscoped.StartsWith('.') || unscoped.StartsWith('_')) + { + error = "A package name has only lower case letters, digits and . _ ~ - characters, and starts with a letter or digit."; + return false; + } + + if (Array.IndexOf(Reserved, unscoped.ToLowerInvariant()) >= 0) + { + error = $"'{unscoped}' is not allowed as a package name."; + return false; + } + + normalized = decoded; + return true; + } + + /// The name without its scope: name for @scope/name. + public static string Unscoped(string name) + { + var slash = name.IndexOf('/'); + + return name.StartsWith('@') && slash >= 0 ? name.Substring(slash + 1) : name; + } + + /// The scope with its @ (@scope), or null for an unscoped name. + public static string? Scope(string name) + { + var slash = name.IndexOf('/'); + + return name.StartsWith('@') && slash >= 0 ? name.Substring(0, slash) : null; + } + + /// The tarball's file name: name-1.0.0.tgz (the scope is not repeated). + public static string TarballFileName(string name, string version) => $"{Unscoped(name)}-{version}.tgz"; + + /// The storage path of a tarball, relative to the repository's prefix: npm/@scope/name/-/name-1.0.0.tgz. + public static string TarballPath(string name, string version) => $"{StorageFolder}/{name}/-/{TarballFileName(name, version)}"; + + /// + /// The version a tarball file name carries for (name-1.0.0.tgz gives 1.0.0), or + /// false when the file name does not belong to the package or carries no valid version. + /// + public static bool TryParseTarballFile(string name, string? file, out string version) + { + version = string.Empty; + var prefix = Unscoped(name) + "-"; + if (file == null || !file.StartsWith(prefix, StringComparison.Ordinal) || !file.EndsWith(".tgz", StringComparison.Ordinal)) return false; + + var middle = file.Substring(prefix.Length, file.Length - prefix.Length - ".tgz".Length); + if (!TryParseVersion(middle, out var parsed)) return false; + + version = parsed; + return true; + } + + /// Whether is a semantic version (3 numeric parts, optional prerelease and build), written in its canonical form. + public static bool TryParseVersion(string? version, out string normalized) + { + normalized = string.Empty; + if (string.IsNullOrWhiteSpace(version) || version.Length > AbstractContext.MaxNpmVersionLength) return false; + + if (!SemanticVersion.TryParse(version, out var parsed)) return false; + + // Only the form the client wrote: " 1.0.0" or "v1.0.0" would name a file the client does not ask for. + if (parsed.ToFullString() != version) return false; + + normalized = version; + return true; + } + + /// The version without build metadata, which npm ignores when it compares versions (1.0.0+a is 1.0.0), and in lower case (1.0.0-Beta and 1.0.0-beta share a file on a case-insensitive store, so they are one version). + public static string Comparable(string version) + => SemanticVersion.TryParse(version, out var parsed) ? parsed.ToNormalizedString().ToLowerInvariant() : version.ToLowerInvariant(); + + /// Whether the version carries a prerelease label. + public static bool IsPrerelease(string version) + => SemanticVersion.TryParse(version, out var parsed) && parsed.IsPrerelease; + + /// + /// The highest of by semantic version order, preferring versions without a prerelease label + /// (what latest should point at); null when empty. + /// + public static string? Highest(System.Collections.Generic.IEnumerable versions, bool stableFirst = true) + { + string? best = null; + SemanticVersion? bestParsed = null; + string? bestStable = null; + SemanticVersion? bestStableParsed = null; + + foreach (var version in versions) + { + if (!SemanticVersion.TryParse(version, out var parsed)) continue; + + if (bestParsed == null || parsed > bestParsed) + { + best = version; + bestParsed = parsed; + } + + if (!parsed.IsPrerelease && (bestStableParsed == null || parsed > bestStableParsed)) + { + bestStable = version; + bestStableParsed = parsed; + } + } + + return stableFirst && bestStable != null ? bestStable : best; + } + + /// Whether can be a dist-tag: 1 to 128 URL-safe characters that are not a version. + public static bool IsValidTag(string? tag, out string error) + { + error = string.Empty; + if (string.IsNullOrEmpty(tag) || tag.Length > AbstractContext.MaxNpmTagLength) + { + error = "A tag has 1 to 128 characters."; + return false; + } + + if (!TagShape.IsMatch(tag)) + { + error = "A tag has only letters, digits and . _ ~ - characters."; + return false; + } + + // npm refuses a tag that is a version, since "npm install pkg@1.0.0" must mean the version. + if (SemanticVersion.TryParse(tag, out _)) + { + error = "A tag cannot be a version."; + return false; + } + + return true; + } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmPublishBody.cs b/src/BaGet.Core/Formats/Npm/NpmPublishBody.cs new file mode 100644 index 000000000..523cc0de5 --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmPublishBody.cs @@ -0,0 +1,494 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// The request body of PUT /{name} exceeds . +public sealed class NpmBodyTooLargeException : Exception +{ + /// The limit in bytes. + public NpmBodyTooLargeException(long limit) : base($"The request is larger than {limit} bytes.") + { + Limit = limit; + } + + /// The limit in bytes. + public long Limit { get; } +} + +/// One tarball carried inline in a publish body, decoded to a temporary file. +public sealed class NpmAttachment : IDisposable +{ + internal NpmAttachment(string name, string? contentType, long? declaredLength, string path) + { + Name = name; + ContentType = contentType; + DeclaredLength = declaredLength; + Path = path; + } + + /// The key in _attachments (name-1.0.0.tgz, or @scope/name-1.0.0.tgz). + public string Name { get; } + + /// The content_type the client declared. + public string? ContentType { get; } + + /// The length the client declared, when it did. + public long? DeclaredLength { get; } + + /// The temporary file holding the decoded bytes. + public string Path { get; } + + /// The decoded size. + public long Length { get; internal set; } + + /// Opens the decoded bytes for reading. + public FileStream Open() => new(Path, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan); + + /// + public void Dispose() + { + try + { + File.Delete(Path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } +} + +/// +/// A parsed npm publish body: the JSON without the tarballs, and the tarballs decoded to temporary files. +/// +public sealed class NpmPublishDocument : IDisposable +{ + internal NpmPublishDocument(JsonObject root, IReadOnlyList attachments) + { + Root = root; + Attachments = attachments; + } + + /// The document with every attachment's data emptied. + public JsonObject Root { get; } + + /// The tarballs, in the order they appear. + public IReadOnlyList Attachments { get; } + + /// + public void Dispose() + { + foreach (var attachment in Attachments) attachment.Dispose(); + } +} + +/// +/// Reads the body of PUT /{name} without holding the tarball in memory. npm publish sends one JSON document +/// whose _attachments carry the tarball as a base64 string, so a 100 MB tarball is a 133 MB string. The body is +/// first copied to a temporary file (bounded by the limit), then one pass over it copies every byte except the base64 of +/// an attachment's data into a small buffer and notes where that string is; each attachment is then decoded straight +/// from the file into its own temporary file. Memory use is the size of the metadata (the manifest and readme), never of +/// the tarball. +/// +public static class NpmPublishBody +{ + private const int ChunkSize = 1 << 20; + + /// + /// The most the document may hold apart from the tarballs (the manifest, readme and the rest), which is parsed in memory: + /// a body that is nearly all JSON text and no tarball would otherwise be held whole. + /// + public const long MaxMetadataBytes = 64L * 1024 * 1024; + + /// + /// Reads the body. + /// + /// The request body. + /// The largest body accepted; zero or negative for no limit. + /// The cancellation token. + /// The body is larger than . + /// The body is not the JSON document of a publish, or an attachment is not base64. + public static async Task ParseAsync(Stream body, long maxBytes, CancellationToken cancellationToken) + { + if (body == null) throw new ArgumentNullException(nameof(body)); + + var raw = TempFile(); + var attachments = new List(); + try + { + await CopyBoundedAsync(body, raw, maxBytes, cancellationToken).ConfigureAwait(false); + + var (stripped, ranges) = await StripAsync(raw, cancellationToken).ConfigureAwait(false); + JsonObject root; + try + { + root = JsonNode.Parse(stripped) as JsonObject ?? throw new InvalidDataException("The request is not a JSON object."); + } + catch (JsonException e) + { + throw new InvalidDataException("The request is not valid JSON: " + e.Message, e); + } + + foreach (var range in ranges) + { + var attachmentNode = (root["_attachments"] as JsonObject)?[range.Name] as JsonObject; + var contentType = attachmentNode?["content_type"] is JsonValue typeValue && typeValue.TryGetValue(out var typeText) ? typeText : null; + long? declared = null; + if (attachmentNode?["length"] is JsonValue lengthValue && lengthValue.TryGetValue(out var l)) declared = l; + + var path = TempFile(); + var attachment = new NpmAttachment(range.Name, contentType, declared, path); + attachments.Add(attachment); + attachment.Length = await DecodeAsync(raw, range.Start, range.End, path, cancellationToken).ConfigureAwait(false); + } + + return new NpmPublishDocument(root, attachments); + } + catch + { + foreach (var attachment in attachments) attachment.Dispose(); + throw; + } + finally + { + try + { + File.Delete(raw); + } + catch (IOException) + { + } + } + } + + private static string TempFile() => Path.Combine(Path.GetTempPath(), "baget-npm-" + Guid.NewGuid().ToString("N") + ".tmp"); + + private static async Task CopyBoundedAsync(Stream body, string path, long maxBytes, CancellationToken cancellationToken) + { + await using var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 81920, FileOptions.Asynchronous); + var buffer = new byte[81920]; + long total = 0; + int read; + while ((read = await body.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + total += read; + if (maxBytes > 0 && total > maxBytes) throw new NpmBodyTooLargeException(maxBytes); + + await file.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + } + } + + private readonly record struct DataRange(string Name, long Start, long End); + + private struct Container + { + public bool IsObject; + public bool ExpectKey; + public string? Key; + } + + /// + /// One lexical pass: returns the document with the content of every _attachments.{name}.data string removed, and + /// the file range of that content. Tracks strings, escapes and nesting only; it does not validate the JSON (parsing the + /// stripped copy does). + /// + private static async Task<(byte[] Stripped, List Ranges)> StripAsync(string path, CancellationToken cancellationToken) + { + var output = new MemoryStream(); + var ranges = new List(); + var stack = new List(); + + var inString = false; + var escaped = false; + var stringIsKey = false; + var stringIsData = false; + var keyBytes = new List(); + long dataStart = 0; + string dataName = string.Empty; + + await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan); + var buffer = new byte[ChunkSize]; + long position = 0; + int read; + + while ((read = await file.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + var chunkStart = 0; + for (var i = 0; i < read; i++) + { + var b = buffer[i]; + + if (inString && stringIsData) + { + // The base64 text (possibly with escapes, undone when decoding): leave at the closing quote; everything before it is skipped. + var end = buffer.AsSpan(i, read - i).IndexOf((byte)'"'); + + if (end < 0) + { + i = read - 1; + chunkStart = read; + continue; + } + + i += end; + ranges.Add(new DataRange(dataName, dataStart, position + i)); + inString = false; + stringIsData = false; + output.WriteByte((byte)'"'); + chunkStart = i + 1; + continue; + } + + if (inString) + { + if (stringIsKey && keyBytes.Count < 4096) keyBytes.Add(b); + + if (escaped) + { + escaped = false; + } + else if (b == (byte)'\\') + { + escaped = true; + } + else if (b == (byte)'"') + { + inString = false; + if (stringIsKey) + { + // Drop the closing quote that was collected as part of the key bytes. + var key = DecodeKey(keyBytes); + var top = stack[^1]; + top.Key = key; + stack[^1] = top; + } + } + + continue; + } + + switch (b) + { + case (byte)'"': + inString = true; + escaped = false; + keyBytes.Clear(); + stringIsKey = stack.Count > 0 && stack[^1].IsObject && stack[^1].ExpectKey; + stringIsData = !stringIsKey + && stack.Count == 3 + && stack[0].Key == "_attachments" + && stack[2].Key == "data"; + if (stringIsData) + { + dataName = stack[1].Key ?? string.Empty; + // Flush what precedes, including this opening quote; the content that follows is skipped. + output.Write(buffer, chunkStart, i + 1 - chunkStart); + chunkStart = i + 1; + dataStart = position + i + 1; + } + + break; + + case (byte)'{': + Open(stack, isObject: true); + break; + + case (byte)'[': + Open(stack, isObject: false); + break; + + case (byte)'}': + case (byte)']': + if (stack.Count > 0) stack.RemoveAt(stack.Count - 1); + break; + + case (byte)':': + if (stack.Count > 0 && stack[^1].IsObject) + { + var top = stack[^1]; + top.ExpectKey = false; + stack[^1] = top; + } + + break; + + case (byte)',': + if (stack.Count > 0 && stack[^1].IsObject) + { + var top = stack[^1]; + top.ExpectKey = true; + top.Key = null; + stack[^1] = top; + } + + break; + } + } + + if (chunkStart < read && !(inString && stringIsData)) + { + output.Write(buffer, chunkStart, read - chunkStart); + } + + position += read; + if (output.Length > MaxMetadataBytes) throw new NpmBodyTooLargeException(MaxMetadataBytes); + } + + if (inString) throw new InvalidDataException("The request ends inside a string."); + + return (output.ToArray(), ranges); + } + + // The key as the document means it: a JSON encoder may have escaped characters of a name (the + of a build version). + private static string DecodeKey(List collected) + { + var raw = System.Text.Encoding.UTF8.GetString(collected.ToArray(), 0, Math.Max(collected.Count - 1, 0)); + if (raw.IndexOf('\\') < 0) return raw; + + try + { + return JsonSerializer.Deserialize("\"" + raw + "\"") ?? raw; + } + catch (JsonException) + { + return raw; + } + } + + private static void Open(List stack, bool isObject) + { + stack.Add(new Container { IsObject = isObject, ExpectKey = isObject }); + } + + private static async Task DecodeAsync(string source, long start, long end, string target, CancellationToken cancellationToken) + { + await using var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan); + await using var output = new FileStream(target, FileMode.Create, FileAccess.Write, FileShare.None, 81920, FileOptions.Asynchronous); + input.Seek(start, SeekOrigin.Begin); + + var decoder = new JsonBase64Decoder(output); + var remaining = end - start; + var buffer = new byte[ChunkSize]; + + while (remaining > 0) + { + var want = (int)Math.Min(buffer.Length, remaining); + var filled = 0; + while (filled < want) + { + var got = await input.ReadAsync(buffer.AsMemory(filled, want - filled), cancellationToken).ConfigureAwait(false); + if (got == 0) throw new InvalidDataException("The request ended inside an attachment."); + + filled += got; + } + + remaining -= want; + decoder.Feed(buffer.AsSpan(0, want)); + } + + decoder.Finish(); + + return decoder.Total; + } + + /// + /// Decodes the content of a JSON string that holds base64. JSON encoders differ in what they escape: JavaScript writes the + /// text as it is, but others escape the slash (backslash, slash) or write the plus sign as a Unicode escape, so the escapes are undone before the + /// base64 is decoded (whitespace escapes are skipped, as MIME-wrapped base64 may contain them). State survives chunk + /// boundaries. + /// + private sealed class JsonBase64Decoder + { + private readonly Stream _output; + private readonly byte[] _chars = new byte[1 << 16]; + private readonly byte[] _decoded = new byte[(1 << 16) / 4 * 3 + 3]; + private int _count; + private int _state; + private int _digits; + private int _value; + + public JsonBase64Decoder(Stream output) + { + _output = output; + } + + public long Total { get; private set; } + + public void Feed(ReadOnlySpan input) + { + foreach (var b in input) + { + switch (_state) + { + case 0: + if (b == (byte)'\\') _state = 1; else Emit(b); + break; + + case 1: + _state = 0; + if (b == (byte)'/' || b == (byte)'\\' || b == (byte)'"') Emit(b); + else if (b == (byte)'n' || b == (byte)'r' || b == (byte)'t') { } + else if (b == (byte)'u') { _state = 2; _digits = 0; _value = 0; } + else throw new InvalidDataException("An attachment's data holds an escape sequence that base64 does not."); + break; + + default: + _value = (_value << 4) | HexValue(b); + if (++_digits == 4) + { + _state = 0; + if (_value > 0x7f) throw new InvalidDataException("An attachment's data holds a character that base64 does not."); + + Emit((byte)_value); + } + + break; + } + } + } + + public void Finish() + { + if (_state != 0) throw new InvalidDataException("An attachment's data ends inside an escape sequence."); + + Flush(final: true); + } + + private static int HexValue(byte b) => b switch + { + >= (byte)'0' and <= (byte)'9' => b - '0', + >= (byte)'a' and <= (byte)'f' => b - 'a' + 10, + >= (byte)'A' and <= (byte)'F' => b - 'A' + 10, + _ => throw new InvalidDataException("An attachment's data holds an invalid escape sequence."), + }; + + private void Emit(byte b) + { + _chars[_count++] = b; + if (_count == _chars.Length) Flush(final: false); + } + + private void Flush(bool final) + { + if (_count == 0) return; + + var status = System.Buffers.Text.Base64.DecodeFromUtf8(_chars.AsSpan(0, _count), _decoded, out var consumed, out var written, isFinalBlock: final); + if (status != System.Buffers.OperationStatus.Done || consumed != _count) + { + throw new InvalidDataException("An attachment's data is not valid base64."); + } + + _output.Write(_decoded, 0, written); + Total += written; + _count = 0; + } + } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmRegistryService.cs b/src/BaGet.Core/Formats/Npm/NpmRegistryService.cs new file mode 100644 index 000000000..7286b3fc1 --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmRegistryService.cs @@ -0,0 +1,1181 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// A version a remote repository fetched from its upstream and keeps, with what the upstream said about the package. +/// The package name. +/// The version, as the upstream names it. +/// The version's manifest as the upstream sent it. +/// The upstream's publish time for the version. +/// The upstream's creation time of the package. +/// The upstream's last change of the package. +/// The version's deprecation message, or null. +/// The SRI string of the stored bytes (computed here, not the upstream's claim). +/// The SHA-1 of the stored bytes in hex. +/// The size of the stored bytes. +/// The upstream's dist-tags; those that point at a stored version are kept. +public sealed record NpmCachedVersion( + string Name, + string Version, + JsonObject Manifest, + DateTime Published, + DateTime Created, + DateTime Modified, + string? Deprecated, + string Integrity, + string Shasum, + long Length, + IReadOnlyDictionary Tags); + +/// +/// over the npm tables and the storage service. Rows live in the repository of the request (the +/// context's query filter and stamping), tarballs under npm/{name}/-/{file} of that repository's storage prefix. +/// +public class NpmRegistryService : INpmRegistry +{ + private const string TarballContentType = "application/octet-stream"; + + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IRepositoryContext _repository; + private readonly IPackageAuthorizationService _authorization; + private readonly IUrlGenerator _urls; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly IOptionsSnapshot? _options; + private readonly ArtifactUsageRecorder? _usage; + private readonly IScanGate? _scanGate; + private readonly ILogger _logger; + + /// The database. + /// Where tarballs are kept. + /// The repository of the request. + /// Decides who may publish, tag, deprecate and unpublish. + /// Builds the registry address that tarball URLs start with. + /// The clock. + /// The read-only gate, checked before a tarball is stored. + /// The logger. + /// The Npm:* options. + /// Notes downloads for the retention rules; null records nothing. + /// The vulnerability scanning policy checked before a publish and told of what was stored. + public NpmRegistryService( + IContext context, + IStorageService storage, + IRepositoryContext repository, + IPackageAuthorizationService authorization, + IUrlGenerator urls, + SystemTime time, + MaintenanceGate gate, + ILogger logger, + IOptionsSnapshot? options = null, + ArtifactUsageRecorder? usage = null, + IScanGate? scanGate = null) + { + _usage = usage; + _scanGate = scanGate; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _urls = urls ?? throw new ArgumentNullException(nameof(urls)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _options = options; + } + + private TimeSpan UnpublishWindow => _options?.Value.UnpublishWindow ?? TimeSpan.FromHours(72); + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + public async Task GetPackageAsync(string name, CancellationToken cancellationToken) + { + var package = await _context.NpmPackages!.AsNoTracking().FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (package == null) return null; + + var versions = await _context.NpmVersions!.AsNoTracking().Where(v => v.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var tags = await _context.NpmDistTags!.AsNoTracking().Where(t => t.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + + return new NpmPackageInfo( + package.Name!, + DateTime.SpecifyKind(package.Created, DateTimeKind.Utc), + DateTime.SpecifyKind(package.Modified, DateTimeKind.Utc), + tags.ToDictionary(t => t.Tag!, t => t.Version!, StringComparer.Ordinal), + versions.Select(ToInfo).OrderBy(v => v.Version, new SemanticVersionComparer()).ToList()); + } + + private static NpmVersionInfo ToInfo(NpmVersion row) + { + JsonObject manifest; + try + { + manifest = JsonNode.Parse(row.Manifest ?? "{}") as JsonObject ?? new JsonObject(); + } + catch (JsonException) + { + manifest = new JsonObject(); + } + + return new NpmVersionInfo( + row.Version!, + DateTime.SpecifyKind(row.Published, DateTimeKind.Utc), + row.Deprecated, + row.TarballSize, + row.Integrity!, + row.Shasum!, + manifest); + } + + private sealed class SemanticVersionComparer : IComparer + { + public int Compare(string? x, string? y) + { + var okX = SemanticVersion.TryParse(x ?? string.Empty, out var a); + var okY = SemanticVersion.TryParse(y ?? string.Empty, out var b); + if (okX && okY) return a!.CompareTo(b!); + + return string.CompareOrdinal(x, y); + } + } + + /// + public async Task GetPackumentAsync(string name, bool abbreviated, CancellationToken cancellationToken) + { + var package = await GetPackageAsync(name, cancellationToken).ConfigureAwait(false); + + return package == null ? null : BuildPackument(package, abbreviated); + } + + // The fields `npm install` reads (the registry's "corgi" document); everything else is dropped to keep the answer small. + private static readonly string[] InstallFields = + { + "name", "version", "dependencies", "optionalDependencies", "peerDependencies", "peerDependenciesMeta", "bundleDependencies", + "bundledDependencies", "bin", "directories", "engines", "funding", "os", "cpu", "libc", "dist", "deprecated", + "hasInstallScript", "_hasShrinkwrap", + }; + + private JsonObject BuildPackument(NpmPackageInfo package, bool abbreviated) + { + var registry = _urls.GetNpmRegistryUrl(); + var versions = new JsonObject(); + var time = new JsonObject + { + ["created"] = Iso(package.Created), + ["modified"] = Iso(package.Modified), + }; + + foreach (var version in package.Versions) + { + var manifest = abbreviated ? Pick(version.Manifest) : (JsonObject)version.Manifest.DeepClone(); + + var dist = manifest["dist"] as JsonObject ?? new JsonObject(); + dist["tarball"] = $"{registry}{package.Name}/-/{NpmNames.TarballFileName(package.Name, version.Version)}"; + dist["integrity"] = version.Integrity; + dist["shasum"] = version.Shasum; + manifest["dist"] = dist; + manifest["name"] = package.Name; + manifest["version"] = version.Version; + if (version.Deprecated != null) manifest["deprecated"] = version.Deprecated; else manifest.Remove("deprecated"); + if (!abbreviated) manifest["_id"] = $"{package.Name}@{version.Version}"; + + versions[version.Version] = manifest; + time[version.Version] = Iso(version.Published); + } + + var tags = new JsonObject(); + foreach (var tag in package.DistTags.OrderBy(t => t.Key, StringComparer.Ordinal)) tags[tag.Key] = tag.Value; + + if (abbreviated) + { + return new JsonObject + { + ["name"] = package.Name, + ["modified"] = Iso(package.Modified), + ["dist-tags"] = tags, + ["versions"] = versions, + }; + } + + var latest = package.Latest; + var packument = new JsonObject + { + ["_id"] = package.Name, + ["_rev"] = package.Revision, + ["name"] = package.Name, + ["dist-tags"] = tags, + ["versions"] = versions, + ["time"] = time, + }; + + if (latest?.Description != null) packument["description"] = latest.Description; + if (latest?.Readme != null) packument["readme"] = latest.Readme; + foreach (var field in new[] { "license", "homepage", "keywords", "repository", "author", "maintainers", "bugs" }) + { + if (latest?.Manifest[field] is JsonNode node) packument[field] = node.DeepClone(); + } + + return packument; + } + + private static JsonObject Pick(JsonObject manifest) + { + var picked = new JsonObject(); + foreach (var field in InstallFields) + { + if (manifest[field] is JsonNode node) picked[field] = node.DeepClone(); + } + + return picked; + } + + private static string Iso(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc).ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture); + + /// + public async Task OpenTarballAsync(string name, string file, CancellationToken cancellationToken) + { + if (!NpmNames.TryParseTarballFile(name, file, out var version)) return null; + + var row = await _context.NpmVersions!.AsNoTracking() + .Join(_context.NpmPackages!.Where(p => p.Name == name), v => v.PackageKey, p => p.Key, (v, p) => v) + .FirstOrDefaultAsync(v => v.Version == version, cancellationToken).ConfigureAwait(false); + if (row == null) return null; + + try + { + var content = await _storage.GetAsync(StoragePath(name, version), cancellationToken).ConfigureAwait(false); + + // For the retention rules: the version was just downloaded. + _usage?.Touch(_repository.Current.Key, name, version); + + return new NpmTarball(content, row.TarballSize, row.Integrity!); + } + catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) + { + _logger.LogError("The tarball of {Package}@{Version} is missing from storage.", name, version); + + return null; + } + } + + /// + public async Task ProbeAsync(string name, string version, CancellationToken cancellationToken) + { + var stored = await _context.NpmVersions!.AsNoTracking() + .Join(_context.NpmPackages!.Where(p => p.Name == name), v => v.PackageKey, p => p.Key, (v, p) => v.Version!) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return stored.Any(v => NpmNames.Comparable(v) == NpmNames.Comparable(version)) ? ResolutionOutcome.Stored : ResolutionOutcome.NotFound; + } + + private static readonly KeyedLocks PublishLocks = new(); + + // Versions that npm (or a case-insensitive store) treats as one share a lock: build metadata and prerelease case ignored. + private string LockKey(string name, string version) => StoragePath(name, NpmNames.Comparable(version)).ToLowerInvariant(); + + private string StoragePath(string name, string version) => RepositoryStorage.Scope(_repository.Current, NpmNames.TarballPath(name, version)); + + /// + public async Task?> GetDistTagsAsync(string name, CancellationToken cancellationToken) + { + var package = await _context.NpmPackages!.AsNoTracking().FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (package == null) return null; + + var tags = await _context.NpmDistTags!.AsNoTracking().Where(t => t.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + + return tags.ToDictionary(t => t.Tag!, t => t.Version!, StringComparer.Ordinal); + } + + /// + public async Task SearchAsync( + string? text, + int skip, + int take, + Func>? canRead = null, + CancellationToken cancellationToken = default) + { + IQueryable query = _context.NpmPackages!.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(text)) + { + var needle = text.Trim().ToLowerInvariant(); + query = query.Where(p => p.Name!.Contains(needle)); + } + + skip = Math.Max(skip, 0); + take = Math.Clamp(take, 0, 250); + + int total; + List page; + if (canRead == null) + { + total = await query.CountAsync(cancellationToken).ConfigureAwait(false); + page = await query.OrderBy(p => p.Name).Skip(skip).Take(take).ToListAsync(cancellationToken).ConfigureAwait(false); + } + else + { + // Only the packages the caller may read count: the names are ordered, filtered and paged here, and only the + // page's packages are loaded in full. + var visible = new List(); + foreach (var name in await query.OrderBy(p => p.Name).Select(p => p.Name!).ToListAsync(cancellationToken).ConfigureAwait(false)) + { + if (await canRead(name, cancellationToken).ConfigureAwait(false)) visible.Add(name); + } + + total = visible.Count; + var names = visible.Skip(skip).Take(take).ToList(); + page = (await _context.NpmPackages!.AsNoTracking().Where(p => names.Contains(p.Name!)).ToListAsync(cancellationToken).ConfigureAwait(false)) + .OrderBy(p => p.Name, StringComparer.Ordinal).ToList(); + } + + var keys = page.Select(p => p.Key).ToList(); + var tags = await _context.NpmDistTags!.AsNoTracking().Where(t => keys.Contains(t.PackageKey) && t.Tag == "latest").ToListAsync(cancellationToken).ConfigureAwait(false); + var wanted = page.Select(p => (p.Key, Version: tags.FirstOrDefault(t => t.PackageKey == p.Key)?.Version)).ToList(); + var versions = await _context.NpmVersions!.AsNoTracking().Where(v => keys.Contains(v.PackageKey)).ToListAsync(cancellationToken).ConfigureAwait(false); + + var hits = new List(); + foreach (var package in page) + { + var own = versions.Where(v => v.PackageKey == package.Key).ToList(); + var taggedVersion = wanted.First(w => w.Key == package.Key).Version; + var chosen = own.FirstOrDefault(v => v.Version == taggedVersion) + ?? own.FirstOrDefault(v => v.Version == NpmNames.Highest(own.Select(o => o.Version!))); + var info = chosen == null ? null : ToInfo(chosen); + + hits.Add(new NpmSearchHit(package.Name!, info?.Version, info?.Description, info?.Keywords ?? Array.Empty(), DateTime.SpecifyKind(package.Modified, DateTimeKind.Utc))); + } + + return new NpmSearchPage(total, hits); + } + + // ---- authorization -------------------------------------------------------------------------------------------------- + + private async Task DenyAsync(BaGetPrincipal? caller, PackageAction action, string name, CancellationToken cancellationToken) + { + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + if (_repository.Current.Kind != RepositoryKind.Local) + { + return NpmResult.Fail(NpmStatus.Forbidden, "This repository takes no changes."); + } + + if (!await _authorization.AuthorizeAsync(caller, action, name, cancellationToken).ConfigureAwait(false)) + { + return NpmResult.Fail(NpmStatus.Forbidden, $"You are not allowed to {Describe(action)} {name}."); + } + + return null; + } + + /// Null when the caller may do at least one of , else the last refusal. + private async Task DenyAnyAsync(BaGetPrincipal? caller, string name, CancellationToken cancellationToken, params PackageAction[] actions) + { + NpmResult? refusal = null; + foreach (var action in actions) + { + refusal = await DenyAsync(caller, action, name, cancellationToken).ConfigureAwait(false); + if (refusal == null) return null; + } + + return refusal; + } + + private static string Describe(PackageAction action) => action switch + { + PackageAction.Push => "publish to", + PackageAction.Annotate => "deprecate", + _ => "delete from", + }; + + private static bool TryName(string name, out string normalized, out NpmResult? failure) + { + failure = null; + if (NpmNames.TryParse(name, out normalized, out var error)) return true; + + failure = NpmResult.Fail(NpmStatus.Invalid, error); + return false; + } + + // ---- remote cache --------------------------------------------------------------------------------------------------- + + /// + /// Keeps a version a remote repository fetched: the tarball file, the package and version rows and the tags that point at + /// stored versions, in one transaction. No authorization (the request only read), but the maintenance gate applies and + /// nothing is stored if a concurrent request stored the version first (its file stays). Called by + /// . + /// + /// What to keep. + /// The bytes, seekable; read from the start, the caller disposes it. + /// Cancellation. + /// True when this call stored the version, false when it was already stored. + /// The gate is closed. + internal async Task StoreCachedAsync(NpmCachedVersion cached, Stream tarball, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + + var name = cached.Name; + var version = cached.Version; + var path = StoragePath(name, version); + + using var publishLock = await PublishLocks.LockAsync(LockKey(name, version), cancellationToken).ConfigureAwait(false); + var package = await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + var storedRows = package == null + ? new List() + : await _context.NpmVersions!.Where(v => v.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + if (storedRows.Any(v => string.Equals(v.Version, version, StringComparison.Ordinal))) return false; + + // A row that differs only in case or build metadata is a copy cached under another spelling (by an earlier release); + // the upstream's spelling replaces it so the file name that is asked for can be served. + var lookalikes = storedRows.Where(v => NpmNames.Comparable(v.Version!) == NpmNames.Comparable(version)).ToList(); + var stored = storedRows.Except(lookalikes).Select(v => v.Version!).ToList(); + + tarball.Position = 0; + var put = await _storage.PutAsync(path, tarball, TarballContentType, cancellationToken).ConfigureAwait(false); + if (put == StoragePutResult.Conflict) + { + // A file of an earlier attempt that never got its row. + await _storage.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + tarball.Position = 0; + put = await _storage.PutAsync(path, tarball, TarballContentType, cancellationToken).ConfigureAwait(false); + } + + try + { + await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + + if (lookalikes.Count > 0) + { + var lookalikeNames = lookalikes.Select(l => l.Version!).ToHashSet(StringComparer.Ordinal); + _context.NpmDistTags!.RemoveRange(await _context.NpmDistTags!.Where(t => t.PackageKey == package!.Key && lookalikeNames.Contains(t.Version!)).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.NpmVersions!.RemoveRange(lookalikes); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + if (package == null) + { + package = new NpmPackage { Name = name, Created = cached.Created, Modified = cached.Modified }; + _context.NpmPackages!.Add(package); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + _context.NpmVersions!.Add(new NpmVersion + { + PackageKey = package.Key, + Version = version, + Integrity = cached.Integrity, + Shasum = cached.Shasum, + TarballSize = cached.Length, + Manifest = BuildStoredManifest(cached.Manifest, name, version, cached.Integrity, cached.Shasum).ToJsonString(), + Deprecated = string.IsNullOrWhiteSpace(cached.Deprecated) ? null : cached.Deprecated, + Published = cached.Published, + }); + + // The upstream's tags, for the versions this repository holds; "latest" always exists (the highest held version + // when the upstream's own is not held, which moves up as higher ones are kept), so the stored copy can answer a packument by itself. + stored.Add(version); + var tags = cached.Tags + .Where(t => NpmNames.IsValidTag(t.Key, out _) && stored.Contains(t.Value, StringComparer.Ordinal)) + .ToDictionary(t => t.Key, t => t.Value, StringComparer.Ordinal); + foreach (var tag in tags) await SetTagAsync(package.Key, tag.Key, tag.Value, cancellationToken).ConfigureAwait(false); + + if (!tags.ContainsKey("latest")) + { + var highest = NpmNames.Highest(stored); + if (highest != null) await SetTagAsync(package.Key, "latest", highest, cancellationToken).ConfigureAwait(false); + } + + if (cached.Modified > package.Modified) package.Modified = cached.Modified; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + + foreach (var lookalike in lookalikes) + { + var old = StoragePath(name, lookalike.Version!); + if (!string.Equals(old, path, StringComparison.OrdinalIgnoreCase)) await TryDeleteAsync(old).ConfigureAwait(false); + } + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e)) + { + // A concurrent request stored the same version; its file is the one at the path. + return false; + } + catch + { + if (put == StoragePutResult.Success) await TryDeleteAsync(path).ConfigureAwait(false); + + throw; + } + + if (_scanGate != null) await _scanGate.RegisterStoredAsync(name, version, cancellationToken).ConfigureAwait(false); + + return true; + } + + /// + /// Deletes what a remote repository stored (rows and files), without authorization: the administrator's purge. One package + /// (every version, or the one given, matched by semantic version) or, with no name, every package. Tags that pointed at a + /// deleted version are removed, and latest moves to the highest version left. Called by + /// . + /// + /// The versions deleted. + internal async Task PurgeAsync(string? name, string? version, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + if (name == null && version != null) throw new ArgumentException("A version needs the package it belongs to.", nameof(version)); + + var deleted = 0; + while (true) + { + var query = _context.NpmPackages!.AsQueryable(); + if (name != null) query = query.Where(p => p.Name == name); + + // A purge of everything empties 100 packages per round (each round removes the packages it handled); one package is a single round. + var packages = await query.OrderBy(p => p.Key).Take(100).ToListAsync(cancellationToken).ConfigureAwait(false); + if (packages.Count == 0) return deleted; + + foreach (var package in packages) + { + var rows = await _context.NpmVersions!.Where(v => v.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var removed = version == null + ? rows + : rows.Where(r => NpmNames.Comparable(r.Version!) == NpmNames.Comparable(version)).ToList(); + if (removed.Count == 0) continue; + + var tags = await _context.NpmDistTags!.Where(t => t.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + _context.NpmVersions!.RemoveRange(removed); + var kept = rows.Except(removed).Select(r => r.Version!).ToHashSet(StringComparer.Ordinal); + if (kept.Count == 0) + { + _context.NpmDistTags!.RemoveRange(tags); + _context.NpmPackages!.Remove(package); + } + else + { + foreach (var tag in tags.Where(t => t.Tag != "latest" && !kept.Contains(t.Version!))) _context.NpmDistTags!.Remove(tag); + + // "latest" always points at a version that is still held. + var latest = tags.FirstOrDefault(t => t.Tag == "latest"); + if (latest != null && !kept.Contains(latest.Version!)) latest.Version = NpmNames.Highest(kept); + package.Modified = _time.UtcNow; + } + + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + foreach (var row in removed) await TryDeleteAsync(StoragePath(package.Name!, row.Version!)).ConfigureAwait(false); + + deleted += removed.Count; + } + + if (name != null) return deleted; + } + } + + // ---- publish -------------------------------------------------------------------------------------------------------- + + /// + /// What would decide from the tarball alone (the same scanning check), without storing anything: a + /// replication that replaces a stored version asks first, so a refusal cannot cost the copy it was to replace. + /// + /// The scanning policy refuses the package. + internal async Task PreflightReplacementAsync(string name, string version, JsonObject manifest, Stream tarball, string? integrity, CancellationToken cancellationToken) + { + tarball.Position = 0; + var (_, actual, _) = await HashAsync(tarball, cancellationToken).ConfigureAwait(false); + if (integrity != null && !string.Equals(integrity, actual, StringComparison.Ordinal)) + { + throw new InvalidDataException("The tarball does not match the integrity (sha512) the peer announced."); + } + + tarball.Position = 0; + var inner = await NpmTarballReader.ReadPackageJsonAsync(tarball, cancellationToken).ConfigureAwait(false); + tarball.Position = 0; + if (inner == null || _scanGate == null || !_scanGate.Enabled || !await _scanGate.BlocksDeploysAsync(cancellationToken).ConfigureAwait(false)) return; + + var components = NpmScanComponents.Of(name, version, inner).Union(NpmScanComponents.Of(name, version, manifest)).ToList(); + await _scanGate.CheckDeployAsync(components, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task PublishAsync(BaGetPrincipal? caller, NpmPublication publication, CancellationToken cancellationToken) + { + if (publication == null) throw new ArgumentNullException(nameof(publication)); + + if (!TryName(publication.Name, out var name, out var failure)) return failure!; + + if (!NpmNames.TryParseVersion(publication.Version, out var version)) + { + return NpmResult.Fail(NpmStatus.Invalid, $"'{publication.Version}' is not a valid semantic version."); + } + + if (!NpmNames.IsValidTag(publication.Tag, out var tagError)) return NpmResult.Fail(NpmStatus.Invalid, tagError); + + var denied = await DenyAsync(caller, PackageAction.Push, name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + // Hash and check the bytes before anything is stored: what the client computed must be what arrived. + var tarball = publication.Tarball; + tarball.Position = 0; + var (length, integrity, shasum) = await HashAsync(tarball, cancellationToken).ConfigureAwait(false); + + if (publication.ExpectedLength is long declared && declared != length) + { + return NpmResult.Fail(NpmStatus.Invalid, $"The tarball has {length} bytes, not the {declared} the request declares."); + } + + if (publication.ExpectedIntegrity != null && !string.Equals(publication.ExpectedIntegrity, integrity, StringComparison.Ordinal)) + { + return NpmResult.Fail(NpmStatus.Invalid, "The tarball does not match the integrity (sha512) the request declares."); + } + + if (publication.ExpectedShasum != null && !string.Equals(publication.ExpectedShasum, shasum, StringComparison.OrdinalIgnoreCase)) + { + return NpmResult.Fail(NpmStatus.Invalid, "The tarball does not match the shasum (sha1) the request declares."); + } + + // The tarball is the package it says it is. + tarball.Position = 0; + var inner = await NpmTarballReader.ReadPackageJsonAsync(tarball, cancellationToken).ConfigureAwait(false); + if (inner == null) return NpmResult.Fail(NpmStatus.Invalid, "The tarball is not a gzip-compressed tar with a package.json in its top folder."); + + var innerName = inner["name"] is JsonValue n && n.TryGetValue(out var innerNameText) ? innerNameText : null; + var innerVersion = inner["version"] is JsonValue v && v.TryGetValue(out var innerVersionText) ? innerVersionText : null; + if (!string.Equals(innerName, name, StringComparison.Ordinal) || !string.Equals(innerVersion, version, StringComparison.Ordinal)) + { + return NpmResult.Fail(NpmStatus.Invalid, $"The tarball's package.json is {innerName}@{innerVersion}, not {name}@{version}."); + } + + // The scanning policy of the repository may refuse a package with known vulnerabilities (ScanBlockedException, 403). + if (_scanGate != null && _scanGate.Enabled && await _scanGate.BlocksDeploysAsync(cancellationToken).ConfigureAwait(false)) + { + // What the tarball declares and what the packument will tell clients (the request's version object) are both checked. + var components = NpmScanComponents.Of(name, version, inner).Union(NpmScanComponents.Of(name, version, publication.Manifest)).ToList(); + await _scanGate.CheckDeployAsync(components, cancellationToken).ConfigureAwait(false); + } + + _gate.ThrowIfClosed(); + + // One publish of a version (build metadata and prerelease case ignored) at a time in this process: the clash check and + // the file write must not interleave with a concurrent publish, or the loser would replace the winner's file. Under the + // lock the rows decide, so a loser is refused without touching storage. Other nodes sharing the store are not fenced. + using var publishLock = await PublishLocks.LockAsync(LockKey(name, version), cancellationToken).ConfigureAwait(false); + + var package = await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + var isNewPackage = package == null; + if (package != null) + { + var existing = await _context.NpmVersions!.AsNoTracking().Where(x => x.PackageKey == package.Key).Select(x => x.Version!).ToListAsync(cancellationToken).ConfigureAwait(false); + var clash = existing.FirstOrDefault(x => NpmNames.Comparable(x) == NpmNames.Comparable(version)); + if (clash != null) + { + return NpmResult.Fail(NpmStatus.Conflict, $"You cannot publish over the previously published version {clash}."); + } + } + + var path = StoragePath(name, version); + tarball.Position = 0; + var stored = await _storage.PutAsync(path, tarball, TarballContentType, cancellationToken).ConfigureAwait(false); + if (stored == StoragePutResult.Conflict) + { + // A file of an earlier attempt that never got its row: the version is free, so the file is replaced. + await _storage.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + tarball.Position = 0; + stored = await _storage.PutAsync(path, tarball, TarballContentType, cancellationToken).ConfigureAwait(false); + } + + var now = _time.UtcNow; + var storedByThisCall = stored == StoragePutResult.Success; + + // Two first publishes of different versions of one new package both find no package row; the loser's insert of the + // package hits the unique (repository, name) index. It then publishes onto the winner's row: only a clash on the + // version itself is a conflict. + for (var attempt = 0; ; attempt++) + { + try + { + await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + + if (package == null) + { + package = new NpmPackage { Name = name, Created = now, Modified = now }; + _context.NpmPackages!.Add(package); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + _context.NpmVersions!.Add(new NpmVersion + { + PackageKey = package.Key, + Version = version, + Integrity = integrity, + Shasum = shasum, + TarballSize = length, + Manifest = BuildStoredManifest(publication.Manifest, name, version, integrity, shasum, inner).ToJsonString(), + Published = now, + }); + + await SetTagAsync(package.Key, publication.Tag, version, cancellationToken).ConfigureAwait(false); + + // The first version of a package is always "latest", whatever tag it was published with: a package without it + // cannot be installed by name. + if (isNewPackage && publication.Tag != "latest") await SetTagAsync(package.Key, "latest", version, cancellationToken).ConfigureAwait(false); + + package.Modified = now; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + break; + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e)) + { + // The rolled-back attempt left tracked entities that no longer exist in the database. + (_context as DbContext)?.ChangeTracker.Clear(); + + var winner = isNewPackage && attempt == 0 + ? await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false) + : null; + if (winner != null) + { + package = winner; + isNewPackage = false; + continue; + } + + // A clash on the version: a concurrent publish of the same version won. Its file is the one at the path while + // its row exists; when no row has this version the file is this call's own leftover, and goes. + var taken = package != null + && await _context.NpmVersions!.AsNoTracking().AnyAsync(v => v.PackageKey == package.Key && v.Version == version, cancellationToken).ConfigureAwait(false); + if (storedByThisCall && !taken) await TryDeleteAsync(path).ConfigureAwait(false); + + return NpmResult.Fail(NpmStatus.Conflict, $"You cannot publish over the previously published version {version}."); + } + catch + { + if (storedByThisCall) await TryDeleteAsync(path).ConfigureAwait(false); + + throw; + } + } + + await _authorization.OnPushedAsync(caller!, name, isNewPackage, cancellationToken).ConfigureAwait(false); + if (_scanGate != null) await _scanGate.RegisterStoredAsync(name, version, cancellationToken).ConfigureAwait(false); + + return NpmResult.Created($"Published {name}@{version}.", name); + } + + /// + public async Task PublishTarballAsync(BaGetPrincipal? caller, Stream tarball, string tag, CancellationToken cancellationToken) + { + if (tarball == null) throw new ArgumentNullException(nameof(tarball)); + + tarball.Position = 0; + var inner = await NpmTarballReader.ReadPackageJsonAsync(tarball, cancellationToken).ConfigureAwait(false); + if (inner == null) return NpmResult.Fail(NpmStatus.Invalid, "The file is not an npm tarball: a gzip-compressed tar with a package.json in its top folder."); + + var name = inner["name"] is JsonValue n && n.TryGetValue(out var nameText) ? nameText : null; + var version = inner["version"] is JsonValue v && v.TryGetValue(out var versionText) ? versionText : null; + if (name == null || version == null) return NpmResult.Fail(NpmStatus.Invalid, "The package.json has no name or no version."); + + // Authorize before reading the file again: an unauthorized caller learns nothing about the repository. + if (!TryName(name, out var normalized, out var failure)) return failure!; + + return await PublishAsync(caller, new NpmPublication(normalized, version, inner, string.IsNullOrWhiteSpace(tag) ? "latest" : tag.Trim(), tarball), cancellationToken).ConfigureAwait(false); + } + + // The fields npm acts on at install time come from the tarball's own package.json when there is one (a publisher cannot + // declare harmless dependencies or no install script in the request and ship others); the registry owns name, version and dist. + private static readonly string[] TarballOwnedFields = + { + "dependencies", "optionalDependencies", "peerDependencies", "peerDependenciesMeta", "bundleDependencies", "bundledDependencies", + "bin", "directories", "engines", "funding", "os", "cpu", "libc", "scripts", + }; + + private static JsonObject BuildStoredManifest(JsonObject sent, string name, string version, string integrity, string shasum, JsonObject? tarballPackageJson = null) + { + var manifest = (JsonObject)sent.DeepClone(); + + if (tarballPackageJson != null) + { + foreach (var field in TarballOwnedFields) + { + if (tarballPackageJson[field] is { } value) manifest[field] = value.DeepClone(); else manifest.Remove(field); + } + + // npm normalizes at publish time what the tarball's own package.json lacks: a binding.gyp becomes + // scripts.install = "node-gyp rebuild" (+ gypfile), directories.bin becomes bin. The tarball is not scanned for + // binding.gyp; the client's normalized value is kept only in these two exact shapes, which can over-report an + // install script but never hide one. + var tarballScripts = tarballPackageJson["scripts"] as JsonObject; + if (!(tarballScripts?.ContainsKey("install") ?? false) && !(tarballScripts?.ContainsKey("preinstall") ?? false) + && sent["scripts"] is JsonObject sentScripts + && sentScripts["install"] is JsonValue gypInstall && gypInstall.TryGetValue(out var gypText) && gypText == "node-gyp rebuild") + { + var merged = tarballScripts != null ? (JsonObject)tarballScripts.DeepClone() : new JsonObject(); + merged["install"] = gypText; + manifest["scripts"] = merged; + manifest["gypfile"] = true; + } + else + { + manifest.Remove("gypfile"); + } + + if (tarballPackageJson["bin"] == null && tarballPackageJson["directories"] is JsonObject tarballDirectories + && tarballDirectories["bin"] != null && sent["bin"] is { } sentBin) + { + manifest["bin"] = sentBin.DeepClone(); + } + + var finalScripts = manifest["scripts"] as JsonObject; + var hasInstallScript = finalScripts != null + && (finalScripts.ContainsKey("preinstall") || finalScripts.ContainsKey("install") || finalScripts.ContainsKey("postinstall")); + if (hasInstallScript) manifest["hasInstallScript"] = true; else manifest.Remove("hasInstallScript"); + } + + // The registry decides these; the client's copies are discarded. + manifest.Remove("_attachments"); + manifest.Remove("deprecated"); + manifest.Remove("dist-tags"); + manifest["name"] = name; + manifest["version"] = version; + + var dist = new JsonObject(); + if (sent["dist"] is JsonObject sentDist) + { + foreach (var property in sentDist) + { + if (property.Key is "tarball" or "integrity" or "shasum") continue; + + dist[property.Key] = property.Value?.DeepClone(); + } + } + + dist["integrity"] = integrity; + dist["shasum"] = shasum; + manifest["dist"] = dist; + + return manifest; + } + + private static async Task<(long Length, string Integrity, string Shasum)> HashAsync(Stream stream, CancellationToken cancellationToken) + { + using var sha512 = IncrementalHash.CreateHash(HashAlgorithmName.SHA512); + using var sha1 = IncrementalHash.CreateHash(HashAlgorithmName.SHA1); + var buffer = new byte[81920]; + long length = 0; + int read; + while ((read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + sha512.AppendData(buffer, 0, read); + sha1.AppendData(buffer, 0, read); + length += read; + } + + return (length, "sha512-" + Convert.ToBase64String(sha512.GetHashAndReset()), Convert.ToHexString(sha1.GetHashAndReset()).ToLowerInvariant()); + } + + private async Task TryDeleteAsync(string path) + { + try + { + await _storage.DeleteAsync(path, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(e, "Could not delete {Path}.", path); + } + } + + // Points a tag at a version, keeping one row per (package, tag) as the unique index demands. + private async Task SetTagAsync(int packageKey, string tag, string version, CancellationToken cancellationToken) + { + var existing = await _context.NpmDistTags!.FirstOrDefaultAsync(t => t.PackageKey == packageKey && t.Tag == tag, cancellationToken).ConfigureAwait(false); + if (existing != null) + { + existing.Version = version; + } + else + { + _context.NpmDistTags!.Add(new NpmDistTag { PackageKey = packageKey, Tag = tag, Version = version }); + } + } + + // ---- dist-tags ------------------------------------------------------------------------------------------------------ + + /// + public async Task SetDistTagAsync(BaGetPrincipal? caller, string name, string tag, string version, CancellationToken cancellationToken) + { + if (!TryName(name, out name, out var failure)) return failure!; + if (!NpmNames.IsValidTag(tag, out var tagError)) return NpmResult.Fail(NpmStatus.Invalid, tagError); + + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + var denied = await DenyAsync(caller, PackageAction.Push, name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + var package = await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (package == null) return NpmResult.Fail(NpmStatus.NotFound, $"There is no package {name}."); + + var rows = await _context.NpmVersions!.AsNoTracking().Where(v => v.PackageKey == package.Key).Select(v => v.Version!).ToListAsync(cancellationToken).ConfigureAwait(false); + var stored = rows.FirstOrDefault(v => v == version) ?? rows.FirstOrDefault(v => NpmNames.Comparable(v) == NpmNames.Comparable(version ?? string.Empty)); + if (stored == null) return NpmResult.Fail(NpmStatus.NotFound, $"{name} has no version {version}."); + + await SetTagAsync(package.Key, tag, stored, cancellationToken).ConfigureAwait(false); + package.Modified = _time.UtcNow; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return NpmResult.Ok($"+{tag}: {name}@{stored}"); + } + + /// + public async Task RemoveDistTagAsync(BaGetPrincipal? caller, string name, string tag, CancellationToken cancellationToken) + { + if (!TryName(name, out name, out var failure)) return failure!; + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + var denied = await DenyAsync(caller, PackageAction.Push, name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + var package = await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (package == null) return NpmResult.Fail(NpmStatus.NotFound, $"There is no package {name}."); + + var row = await _context.NpmDistTags!.FirstOrDefaultAsync(t => t.PackageKey == package.Key && t.Tag == tag, cancellationToken).ConfigureAwait(false); + if (row == null) return NpmResult.Fail(NpmStatus.NotFound, $"{name} has no tag {tag}."); + + _context.NpmDistTags!.Remove(row); + package.Modified = _time.UtcNow; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return NpmResult.Ok($"-{tag}: {name}"); + } + + // ---- deprecate ------------------------------------------------------------------------------------------------------ + + /// + public async Task DeprecateAsync(BaGetPrincipal? caller, string name, IReadOnlyDictionary messages, CancellationToken cancellationToken) + { + if (!TryName(name, out name, out var failure)) return failure!; + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + var denied = await DenyAsync(caller, PackageAction.Annotate, name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + var package = await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (package == null) return NpmResult.Fail(NpmStatus.NotFound, $"There is no package {name}."); + + var rows = await _context.NpmVersions!.Where(v => v.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var changed = 0; + foreach (var message in messages) + { + var row = rows.FirstOrDefault(r => r.Version == message.Key); + if (row == null) return NpmResult.Fail(NpmStatus.NotFound, $"{name} has no version {message.Key}."); + + var text = string.IsNullOrWhiteSpace(message.Value) ? null : message.Value; + if (row.Deprecated == text) continue; + + row.Deprecated = text; + changed++; + } + + if (changed > 0) + { + package.Modified = _time.UtcNow; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + return NpmResult.Ok(); + } + + // ---- unpublish ------------------------------------------------------------------------------------------------------ + + /// + public async Task UnpublishVersionsAsync( + BaGetPrincipal? caller, + string name, + IReadOnlyCollection versions, + IReadOnlyDictionary? newTags, + CancellationToken cancellationToken) + { + if (!TryName(name, out name, out var failure)) return failure!; + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + // Authorize before looking the package up, so a caller who may not change it learns nothing about it. + var preliminary = await DenyAnyAsync(caller, name, cancellationToken, PackageAction.Push, PackageAction.Manage).ConfigureAwait(false); + if (preliminary != null) return preliminary; + + var package = await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (package == null) return NpmResult.Fail(NpmStatus.NotFound, $"There is no package {name}."); + + // Nothing to remove is an authorization probe: allowed, and nothing happens. + if (versions.Count == 0) return NpmResult.Ok(); + + var rows = await _context.NpmVersions!.Where(v => v.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var removed = new List(); + foreach (var version in versions.Distinct(StringComparer.Ordinal)) + { + var row = rows.FirstOrDefault(r => r.Version == version); + if (row == null) return NpmResult.Fail(NpmStatus.NotFound, $"{name} has no version {version}."); + + removed.Add(row); + } + + return await RemoveAsync(caller, package, rows, removed, newTags, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task UnpublishPackageAsync(BaGetPrincipal? caller, string name, CancellationToken cancellationToken) + { + if (!TryName(name, out name, out var failure)) return failure!; + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + var preliminary = await DenyAnyAsync(caller, name, cancellationToken, PackageAction.Push, PackageAction.Manage).ConfigureAwait(false); + if (preliminary != null) return preliminary; + + var package = await _context.NpmPackages!.FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + if (package == null) return NpmResult.Fail(NpmStatus.NotFound, $"There is no package {name}."); + + var rows = await _context.NpmVersions!.Where(v => v.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + + return await RemoveAsync(caller, package, rows, rows.ToList(), newTags: null, cancellationToken).ConfigureAwait(false); + } + + private async Task RemoveAsync( + BaGetPrincipal caller, + NpmPackage package, + List all, + List removed, + IReadOnlyDictionary? newTags, + CancellationToken cancellationToken) + { + var name = package.Name!; + + // Deploy lets an owner take back a recent mistake (npmjs allows it for 72 hours); anything older is a deletion. + // Only a key that may push whole packages (the push scope) takes that shortcut: a key limited to pushing new + // versions (package:pushversion) never deletes, so it is judged as for a deletion (the unlist scope). + var window = UnpublishWindow; + var now = _time.UtcNow; + var young = window > TimeSpan.Zero + && caller.HasScope(ApiKeyScopes.Push) + && removed.All(r => now - DateTime.SpecifyKind(r.Published, DateTimeKind.Utc) <= window); + var denied = await DenyAsync(caller, young ? PackageAction.Push : PackageAction.Manage, name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + _gate.ThrowIfClosed(); + + // The publish lock of every removed version (in a stable order) is held until the files are gone, so a republish of + // the same version cannot have its new file deleted by this unpublish. + var locks = new List(); + try + { + foreach (var key in removed.Select(r => LockKey(name, r.Version!)).Distinct(StringComparer.Ordinal).OrderBy(k => k, StringComparer.Ordinal)) + { + locks.Add(await PublishLocks.LockAsync(key, cancellationToken).ConfigureAwait(false)); + } + + return await RemoveLockedAsync(package, all, removed, newTags, now, cancellationToken).ConfigureAwait(false); + } + finally + { + foreach (var held in locks) held.Dispose(); + } + } + + private async Task RemoveLockedAsync( + NpmPackage package, + List all, + List removed, + IReadOnlyDictionary? newTags, + DateTime now, + CancellationToken cancellationToken) + { + var name = package.Name!; + var remaining = all.Where(r => !removed.Contains(r)).ToList(); + var tags = await _context.NpmDistTags!.Where(t => t.PackageKey == package.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + + _context.NpmVersions!.RemoveRange(removed); + + if (remaining.Count == 0) + { + _context.NpmDistTags!.RemoveRange(tags); + _context.NpmPackages!.Remove(package); + } + else + { + var kept = remaining.Select(r => r.Version!).ToHashSet(StringComparer.Ordinal); + foreach (var tag in tags.ToList()) + { + if (kept.Contains(tag.Version!)) continue; + + if (newTags != null && newTags.TryGetValue(tag.Tag!, out var target) && kept.Contains(target)) + { + tag.Version = target; + } + else + { + _context.NpmDistTags!.Remove(tag); + tags.Remove(tag); + } + } + + // "latest" must point somewhere, or the package cannot be installed by name. + if (!tags.Any(t => t.Tag == "latest")) + { + var highest = NpmNames.Highest(kept); + if (highest != null) _context.NpmDistTags!.Add(new NpmDistTag { PackageKey = package.Key, Tag = "latest", Version = highest }); + } + + package.Modified = now; + } + + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // The rows are gone; a failing file delete leaves an unreferenced tarball, not a broken package. + foreach (var row in removed) await TryDeleteAsync(StoragePath(name, row.Version!)).ConfigureAwait(false); + + return NpmResult.Ok(remaining.Count == 0 ? $"Unpublished {name}." : $"Unpublished {string.Join(", ", removed.Select(r => name + "@" + r.Version))}."); + } + + /// + public async Task DeleteTarballAsync(BaGetPrincipal? caller, string name, string file, CancellationToken cancellationToken) + { + if (!TryName(name, out name, out var failure)) return failure!; + if (!NpmNames.TryParseTarballFile(name, file, out var version)) return NpmResult.Fail(NpmStatus.NotFound, "There is no such file."); + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + var preliminary = await DenyAnyAsync(caller, name, cancellationToken, PackageAction.Push, PackageAction.Manage).ConfigureAwait(false); + if (preliminary != null) return preliminary; + + var package = await _context.NpmPackages!.AsNoTracking().FirstOrDefaultAsync(p => p.Name == name, cancellationToken).ConfigureAwait(false); + var published = package != null && await _context.NpmVersions!.AnyAsync(v => v.PackageKey == package.Key && v.Version == version, cancellationToken).ConfigureAwait(false); + if (published) return await UnpublishVersionsAsync(caller, name, new[] { version }, null, cancellationToken).ConfigureAwait(false); + + // A row whose version differs only in case or build metadata owns the file on a case-insensitive store: untouched. + var lookalike = package != null && (await _context.NpmVersions!.AsNoTracking().Where(v => v.PackageKey == package.Key).Select(v => v.Version!).ToListAsync(cancellationToken).ConfigureAwait(false)) + .Any(v => NpmNames.Comparable(v) == NpmNames.Comparable(version)); + if (lookalike) return NpmResult.Fail(NpmStatus.NotFound, "There is no such file."); + + // The version is already unpublished (the earlier step of the client's sequence): only the file is left. + var denied = await DenyAsync(caller, PackageAction.Push, name, cancellationToken).ConfigureAwait(false); + if (denied != null) return denied; + + _gate.ThrowIfClosed(); + + // Under the version's lock, and only if no row claims the version now: a publish that finished meanwhile owns the file. + using var publishLock = await PublishLocks.LockAsync(LockKey(name, version), cancellationToken).ConfigureAwait(false); + var claimed = package != null && (await _context.NpmVersions!.AsNoTracking().Where(v => v.PackageKey == package.Key).Select(v => v.Version!).ToListAsync(cancellationToken).ConfigureAwait(false)) + .Any(v => NpmNames.Comparable(v) == NpmNames.Comparable(version)); + if (claimed) return NpmResult.Fail(NpmStatus.NotFound, "There is no such file."); + + await _storage.DeleteAsync(StoragePath(name, version), cancellationToken).ConfigureAwait(false); + + return NpmResult.Ok(); + } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmRetentionHooks.cs b/src/BaGet.Core/Formats/Npm/NpmRetentionHooks.cs new file mode 100644 index 000000000..a6c4da215 --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmRetentionHooks.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// npm's : a version is one (with its tarball). Deleting is +/// , the administrator's unauthorised unpublish: the tags that pointed at the version go +/// and latest moves to the highest version left; the last version takes the package with it. +/// +public sealed class NpmRetentionHooks : IFormatRetentionHooks +{ + private readonly IContext _context; + private readonly NpmRegistryService _registry; + + public NpmRetentionHooks(IContext context, NpmRegistryService registry) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Npm; + + /// + public async Task> ListVersionsAsync(CancellationToken cancellationToken) + { + var usage = await ArtifactUsageMap.LoadAsync(_context, cancellationToken).ConfigureAwait(false); + var rows = await (from v in _context.NpmVersions!.AsNoTracking() + join p in _context.NpmPackages!.AsNoTracking() on v.PackageKey equals p.Key + select new { p.Name, v.Version, v.Published, v.TarballSize }).ToListAsync(cancellationToken).ConfigureAwait(false); + + return rows + .Select(r => new FormatVersion(r.Name!, r.Version!, DateTime.SpecifyKind(r.Published, DateTimeKind.Utc), usage.Get(r.Name!, r.Version!), r.TarballSize, NpmNames.IsPrerelease(r.Version!))) + .ToList(); + } + + /// + public async Task DeleteVersionAsync(string name, string version, CancellationToken cancellationToken) + => await _registry.PurgeAsync(name, version, cancellationToken).ConfigureAwait(false); + + /// + public (string Name, string Version)? Canonical(string name, string? version) + { + // npm names are lower case (the registry refuses new upper-case ones), so a typed name is folded before it is checked. + if (!NpmNames.TryParse(name?.Trim().ToLowerInvariant(), out var normalized, out _)) return null; + if (string.IsNullOrWhiteSpace(version)) return (normalized, string.Empty); + + return NpmNames.TryParseVersion(version.Trim(), out var v) ? (normalized, v) : null; + } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmTarballReader.cs b/src/BaGet.Core/Formats/Npm/NpmTarballReader.cs new file mode 100644 index 000000000..4b48c143b --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmTarballReader.cs @@ -0,0 +1,122 @@ +using System; +using System.Formats.Tar; +using System.IO; +using System.IO.Compression; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Reads the package.json of an npm tarball (a gzip-compressed tar whose files sit under one top folder, usually +/// package/). The registry uses it to check that the tarball a client sends is the package and version it claims +/// to be, and the browser upload builds the version's manifest from it. +/// +public static class NpmTarballReader +{ + // A tarball is untrusted: what it expands to is read only as far as package.json (usually its first entry), and never + // further than this, so a compression bomb costs bounded time. + private const long MaxExpandedBytes = 1L << 30; + private const int MaxEntries = 100_000; + private const long MaxManifestBytes = 4 * 1024 * 1024; + + /// + /// The package.json object of the tarball, or null when the stream is not a gzip-compressed tar, holds no + /// package.json at the root of its top folder, or that file is not a JSON object. + /// + /// A readable stream positioned at the start; it is not closed. + /// The cancellation token. + public static async Task ReadPackageJsonAsync(Stream tarball, CancellationToken cancellationToken) + { + if (tarball == null) throw new ArgumentNullException(nameof(tarball)); + + try + { + using var gzip = new GZipStream(tarball, CompressionMode.Decompress, leaveOpen: true); + using var limited = new LimitedStream(gzip, MaxExpandedBytes); + using var reader = new TarReader(limited, leaveOpen: true); + + for (var count = 0; count < MaxEntries; count++) + { + var entry = await reader.GetNextEntryAsync(copyData: false, cancellationToken).ConfigureAwait(false); + if (entry == null) return null; + if (entry.EntryType != TarEntryType.RegularFile && entry.EntryType != TarEntryType.V7RegularFile) continue; + if (!IsRootPackageJson(entry.Name)) continue; + if (entry.DataStream == null || entry.Length > MaxManifestBytes) return null; + + using var buffer = new MemoryStream(); + await entry.DataStream.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); + buffer.Position = 0; + + return JsonNode.Parse(buffer) as JsonObject; + } + + return null; + } + catch (Exception e) when (e is InvalidDataException or System.Text.Json.JsonException or FormatException or IOException or EndOfStreamException) + { + return null; + } + } + + // /package.json: npm packs everything below one folder (conventionally "package"), whatever the package is called. + private static bool IsRootPackageJson(string path) + { + var normalized = path.Replace('\\', '/').TrimStart('.', '/'); + var slash = normalized.IndexOf('/'); + + return slash > 0 && string.Equals(normalized.Substring(slash + 1), "package.json", StringComparison.Ordinal); + } + + /// Reads at most a fixed number of bytes from the inner stream, then fails as a corrupt archive. + private sealed class LimitedStream : Stream + { + private readonly Stream _inner; + private long _remaining; + + public LimitedStream(Stream inner, long limit) + { + _inner = inner; + _remaining = limit; + } + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var read = _inner.Read(buffer.Slice(0, (int)Math.Min(buffer.Length, Math.Max(_remaining, 0) + 1))); + Account(read); + return read; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = await _inner.ReadAsync(buffer.Slice(0, (int)Math.Min(buffer.Length, Math.Max(_remaining, 0) + 1)), cancellationToken).ConfigureAwait(false); + Account(read); + return read; + } + + private void Account(int read) + { + _remaining -= read; + if (_remaining < 0) throw new InvalidDataException("The tarball expands to more than the registry reads."); + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} diff --git a/src/BaGet.Core/Formats/Npm/NpmUpstreamClient.cs b/src/BaGet.Core/Formats/Npm/NpmUpstreamClient.cs new file mode 100644 index 000000000..22522ef3d --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/NpmUpstreamClient.cs @@ -0,0 +1,377 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// How asking the upstream of a remote npm repository for a packument ended. +public enum NpmUpstreamStatus +{ + /// The document is there (). + Found, + + /// The upstream does not have the package (a real 404, possibly remembered). + NotFound, + + /// Offline mode: the upstream is never contacted, and nothing is remembered about the package. + Offline, + + /// The upstream could not be asked (down, refused the credentials, not a registry) and nothing remembered can answer. + Unavailable, +} + +/// An upstream's answer about one package. +/// How it ended. +/// The packument (a private copy the caller may change), or null. +/// Whether it is an expired answer served because the upstream could not be reached. +/// What failed, for . +public sealed record NpmUpstreamAnswer(NpmUpstreamStatus Status, JsonObject? Document = null, bool Stale = false, string? Message = null); + +/// A tarball being downloaded from the upstream; disposing releases the connection. +public sealed class NpmUpstreamDownload : IDisposable +{ + private readonly HttpResponseMessage _response; + + internal NpmUpstreamDownload(HttpResponseMessage response, Stream content) + { + _response = response; + Content = content; + } + + /// The bytes. + public Stream Content { get; } + + /// The size the upstream announced, or null. + public long? Length => _response.Content.Headers.ContentLength; + + /// + public void Dispose() + { + Content.Dispose(); + _response.Dispose(); + } +} + +/// +/// Asks the upstream registry of the current remote npm repository (): the packument of a +/// package and the bytes of a tarball. Applies what every remote repository has (): +/// offline mode, the metadata period, the negative period (only a real 404 is remembered as "not found"), an expired answer +/// served when the upstream cannot be reached, the health the status page shows, credentials sent to the upstream's own origin +/// only (the HTTP client's handler) and Remote:BlockPrivateAddresses (its connect callback). The answers are kept in +/// , under keys that name the package with / written %2f +/// ( splits keys at the first /). +/// +public sealed class NpmUpstreamClient +{ + /// The largest packument accepted: some real ones are tens of megabytes; more is not a registry's answer. + public const long MaxPackumentBytes = 128L * 1024 * 1024; + + /// The most packuments (and remembered 404s) kept per repository, far below NuGet's: a packument can be megabytes. + public const int MaxCachedAnswers = 1000; + + private const string AbbreviatedType = "application/vnd.npm.install-v1+json"; + + private readonly IRepositoryContext? _repository; + private readonly IRemoteUpstreamSource _source; + private readonly RemoteRepositoryState _state; + private readonly IRemoteHttpClientFactory _http; + private readonly ILogger _logger; + + public NpmUpstreamClient( + IRepositoryContext? repository, + IRemoteUpstreamSource source, + RemoteRepositoryState state, + IRemoteHttpClientFactory http, + ILogger logger) + { + _repository = repository; + _source = source ?? throw new ArgumentNullException(nameof(source)); + _state = state ?? throw new ArgumentNullException(nameof(state)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// The upstream of the request's repository, or null when it has none (not remote, or its settings are not usable). + public Task ResolveAsync(CancellationToken cancellationToken) + => _source.ResolveAsync(_repository?.Current ?? RepositoryInfo.Default, cancellationToken); + + /// The cache key part for a package: the name with the slash of a scope written %2f. + internal static string KeyName(string name) => name.Replace("/", "%2f", StringComparison.Ordinal); + + private static string PackumentKey(string name, bool abbreviated) => (abbreviated ? "na:" : "nf:") + KeyName(name); + + private static string TarballKey(string name, string version) => "nd:" + KeyName(name) + "/" + version.ToLowerInvariant(); + + /// The upstream's packument of , abbreviated (install-only) or full. + public async Task GetPackumentAsync(ResolvedUpstream upstream, string name, bool abbreviated, CancellationToken cancellationToken) + { + var key = upstream.Key; + var settings = upstream.Settings; + var cacheKey = PackumentKey(name, abbreviated); + var cached = _state.TryGet(key, cacheKey, out var value, out var negative, out var fresh); + + // The full document has everything the abbreviated one has: whichever is remembered can answer an install-only question. + if (!cached && abbreviated) + { + cached = _state.TryGet(key, PackumentKey(name, abbreviated: false), out value, out negative, out fresh); + } + + // Offline: whatever is remembered, however old; else nothing. The upstream is not contacted. + if (settings.Offline) + { + if (cached && !negative && value is JsonObject remembered) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return new NpmUpstreamAnswer(NpmUpstreamStatus.Found, (JsonObject)remembered.DeepClone(), Stale: !fresh); + } + + return new NpmUpstreamAnswer(NpmUpstreamStatus.Offline); + } + + if (cached && fresh) + { + if (negative) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return new NpmUpstreamAnswer(NpmUpstreamStatus.NotFound); + } + + if (value is JsonObject hit) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return new NpmUpstreamAnswer(NpmUpstreamStatus.Found, (JsonObject)hit.DeepClone()); + } + } + + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + + try + { + using var response = await SendAsync(upstream, PackumentUri(settings, name), abbreviated ? AbbreviatedType + "; q=1.0, application/json; q=0.8, */*" : "application/json", cancellationToken).ConfigureAwait(false); + + if (response.StatusCode == HttpStatusCode.NotFound) + { + _state.Succeeded(key); + _state.Set(key, cacheKey, null, negative: true, TimeSpan.FromSeconds(settings.NegativeTtlSeconds), MaxCachedAnswers); + + return new NpmUpstreamAnswer(NpmUpstreamStatus.NotFound); + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + JsonObject document; + await using (var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) + { + document = await ParseAsync(response, body, cancellationToken).ConfigureAwait(false); + } + + _state.Succeeded(key); + _state.Set(key, cacheKey, document, negative: false, TimeSpan.FromSeconds(settings.MetadataTtlSeconds), MaxCachedAnswers); + + return new NpmUpstreamAnswer(NpmUpstreamStatus.Found, (JsonObject)document.DeepClone()); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + var what = Fail(upstream, e); + + if (cached && !negative && value is JsonObject stale) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Stale); + + return new NpmUpstreamAnswer(NpmUpstreamStatus.Found, (JsonObject)stale.DeepClone(), Stale: true); + } + + return new NpmUpstreamAnswer(NpmUpstreamStatus.Unavailable, Message: what); + } + } + + /// + /// Whether a download of must not be tried now: a fresh 404 is remembered for it (counted as a + /// negative hit). Offline is the caller's own check. + /// + public bool IsKnownAbsent(ResolvedUpstream upstream, string name, string version) + { + if (_state.TryGet(upstream.Key, TarballKey(name, version), out _, out var negative, out var fresh) && negative && fresh) + { + _state.Count(upstream.Key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return true; + } + + return false; + } + + /// + /// Downloads a tarball from ; null when the upstream says 404 (remembered for the negative period). + /// + /// The upstream could not be reached or refused. + public async Task DownloadAsync(ResolvedUpstream upstream, string name, string version, Uri url, CancellationToken cancellationToken) + { + var key = upstream.Key; + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + + HttpResponseMessage? response = null; + try + { + response = await SendAsync(upstream, url, "application/octet-stream, */*", cancellationToken).ConfigureAwait(false); + + if (response.StatusCode == HttpStatusCode.NotFound) + { + _state.Succeeded(key); + _state.Set(key, TarballKey(name, version), null, negative: true, TimeSpan.FromSeconds(upstream.Settings.NegativeTtlSeconds), MaxCachedAnswers); + response.Dispose(); + + return null; + } + + if (!response.IsSuccessStatusCode) throw new HttpRequestException(null, null, response.StatusCode); + + var content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + _state.Succeeded(key); + + return new NpmUpstreamDownload(response, content); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + response?.Dispose(); + + throw new NpmUpstreamException(Fail(upstream, e)); + } + } + + /// Records that what the upstream sent was not what it announced (a tarball whose hash differs): a failure of the upstream. + public string Rejected(ResolvedUpstream upstream, string what) + { + _state.Failed(upstream.Key, what); + _logger.LogWarning("The upstream of repository {Repository} sent something unusable: {Error}", upstream.Name, what); + + return what; + } + + /// The URL a version's tarball is fetched from: the packument's own when it is on the upstream's origin, else the conventional path. + public static Uri TarballUri(RemoteRepositorySettings settings, string name, string version, string? announced) + { + var baseUri = settings.UrlOrNull!; + if (Uri.TryCreate(announced, UriKind.Absolute, out var given) + && string.Equals(given.GetLeftPart(UriPartial.Authority), baseUri.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase)) + { + // Same origin only: the packument is the upstream's word, and a tarball URL on another host would make this server + // fetch whatever address a registry names (the HTTP client sends credentials to the typed origin only, but the + // request itself would still go there). + return given; + } + + return new Uri(Base(settings) + EncodeName(name) + "/-/" + NpmNames.TarballFileName(name, version)); + } + + private static Uri PackumentUri(RemoteRepositorySettings settings, string name) => new(Base(settings) + EncodeName(name)); + + private static string Base(RemoteRepositorySettings settings) + { + var text = settings.UrlOrNull!.GetLeftPart(UriPartial.Path); + + return text.EndsWith('/') ? text : text + "/"; + } + + private static string EncodeName(string name) => name.Replace("/", "%2f", StringComparison.Ordinal); + + private async Task SendAsync(ResolvedUpstream upstream, Uri uri, string accept, CancellationToken cancellationToken) + { + var transport = _state.GetTransport( + upstream.Key, + upstream.Settings, + () => new UpstreamTransport(upstream.Settings.TransportKey(), _http.Create(upstream.Settings), null)); + + using var request = new HttpRequestMessage(HttpMethod.Get, uri); + request.Headers.TryAddWithoutValidation("Accept", accept); + + return await transport.Http!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + } + + private static async Task ParseAsync(HttpResponseMessage response, Stream body, CancellationToken cancellationToken) + { + if (response.Content.Headers.ContentLength > MaxPackumentBytes) throw new InvalidDataException("The packument is too large."); + + JsonNode? node; + try + { + node = await JsonNode.ParseAsync(new CappedStream(body, MaxPackumentBytes), cancellationToken: cancellationToken).ConfigureAwait(false); + } + catch (System.Text.Json.JsonException) + { + throw new InvalidDataException("The upstream did not send JSON."); + } + + return node as JsonObject ?? throw new InvalidDataException("The upstream did not send a packument."); + } + + private string Fail(ResolvedUpstream upstream, Exception e) + { + var what = RemoteUpstreamClient.Describe(e); + _state.Failed(upstream.Key, what); + + // The exception itself is not logged: its message can carry the upstream's URL with a query string. + _logger.LogWarning("The upstream of repository {Repository} could not be reached: {Error}", upstream.Name, what); + + return what; + } + + // Fails a read that goes past a limit, so a hostile upstream cannot fill the memory with one answer. + private sealed class CappedStream : Stream + { + private readonly Stream _inner; + private readonly long _limit; + private long _read; + + public CappedStream(Stream inner, long limit) + { + _inner = inner; + _limit = limit; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Count(_inner.Read(buffer, offset, count)); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + => Count(await _inner.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)); + + private int Count(int read) + { + _read += read; + if (_read > _limit) throw new InvalidDataException("The answer is larger than " + _limit + " bytes."); + + return read; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} diff --git a/src/BaGet.Core/Formats/Npm/RemoteNpmRegistry.cs b/src/BaGet.Core/Formats/Npm/RemoteNpmRegistry.cs new file mode 100644 index 000000000..dcf1bb7e4 --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/RemoteNpmRegistry.cs @@ -0,0 +1,450 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// of a npm repository: a caching proxy of an upstream registry +/// (https://registry.npmjs.org/, another BaGet, Artifactory, Verdaccio...). +/// +/// +/// Metadata. Packuments come from the upstream (: cached for the metadata period, +/// 404s for the negative period, an expired answer when the upstream is down, nothing in offline mode) with every +/// dist.tarball rewritten to this server, so clients download through the repository. When the upstream cannot answer +/// (down, offline, or it no longer has the package) the versions this repository stored answer instead; when neither can, the +/// upstream's failure is raised (, HTTP 502). +/// Tarballs. A stored version is served from storage. Otherwise it is downloaded, hashed while it is written to a +/// temporary file, checked against the upstream's own integrity / shasum, and (with +/// ) kept in the repository's storage with its package and version rows, so +/// it is served locally from then on, also while the upstream is down. Without it the download is streamed through and nothing is +/// kept. Concurrent requests for the same version download it once. +/// Writes are refused (403): a remote repository takes no changes. Search covers the stored packages only. +/// +public sealed class RemoteNpmRegistry : INpmRegistry +{ + private const string NoChanges = "This repository caches an upstream registry and takes no changes."; + + private static readonly KeyedLocks Downloads = new(); + + private readonly NpmRegistryService _local; + private readonly NpmUpstreamClient _upstream; + private readonly IUrlGenerator _urls; + private readonly ILogger _logger; + + public RemoteNpmRegistry(NpmRegistryService local, NpmUpstreamClient upstream, IUrlGenerator urls, ILogger logger) + { + _local = local ?? throw new ArgumentNullException(nameof(local)); + _upstream = upstream ?? throw new ArgumentNullException(nameof(upstream)); + _urls = urls ?? throw new ArgumentNullException(nameof(urls)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + public async Task GetPackumentAsync(string name, bool abbreviated, CancellationToken cancellationToken) + { + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return await _local.GetPackumentAsync(name, abbreviated, cancellationToken).ConfigureAwait(false); + + var answer = await _upstream.GetPackumentAsync(upstream, name, abbreviated, cancellationToken).ConfigureAwait(false); + if (answer.Status == NpmUpstreamStatus.Found) + { + return Rewrite(answer.Document!, name); + } + + // The upstream has nothing to say (404, offline, down): what this repository stored still answers. + var stored = await _local.GetPackumentAsync(name, abbreviated, cancellationToken).ConfigureAwait(false); + if (stored != null || answer.Status != NpmUpstreamStatus.Unavailable) return stored; + + throw new NpmUpstreamException(answer.Message ?? "The upstream registry could not be reached."); + } + + /// + public async Task GetPackageAsync(string name, CancellationToken cancellationToken) + { + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream != null) + { + var answer = await _upstream.GetPackumentAsync(upstream, name, abbreviated: false, cancellationToken).ConfigureAwait(false); + if (answer.Status == NpmUpstreamStatus.Found) return ToInfo(answer.Document!, name); + + var stored = await _local.GetPackageAsync(name, cancellationToken).ConfigureAwait(false); + if (stored == null && answer.Status == NpmUpstreamStatus.Unavailable) + { + throw new NpmUpstreamException(answer.Message ?? "The upstream registry could not be reached."); + } + + return stored; + } + + return await _local.GetPackageAsync(name, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task?> GetDistTagsAsync(string name, CancellationToken cancellationToken) + => (await GetPackageAsync(name, cancellationToken).ConfigureAwait(false))?.DistTags; + + /// + /// Only the packages this repository stored: a registry's whole catalogue is not searched through a cache. + public Task SearchAsync(string? text, int skip, int take, Func>? canRead = null, CancellationToken cancellationToken = default) + => _local.SearchAsync(text, skip, take, canRead, cancellationToken); + + /// + public async Task OpenTarballAsync(string name, string file, CancellationToken cancellationToken) + { + if (!NpmNames.TryParseTarballFile(name, file, out var version)) return null; + + var stored = await _local.OpenTarballAsync(name, file, cancellationToken).ConfigureAwait(false); + if (stored != null) return stored; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null || upstream.Settings.Offline || _upstream.IsKnownAbsent(upstream, name, version)) return null; + + // One download per version at a time: the second request finds the first one's stored copy. + using var turn = await Downloads.LockAsync($"{upstream.Key}|{name}|{NpmNames.Comparable(version)}", cancellationToken).ConfigureAwait(false); + + stored = await _local.OpenTarballAsync(name, file, cancellationToken).ConfigureAwait(false); + if (stored != null) return stored; + + var answer = await _upstream.GetPackumentAsync(upstream, name, abbreviated: true, cancellationToken).ConfigureAwait(false); + if (answer.Status == NpmUpstreamStatus.Unavailable) throw new NpmUpstreamException(answer.Message ?? "The upstream registry could not be reached."); + if (answer.Status != NpmUpstreamStatus.Found) return null; + + var document = answer.Document!; + var manifest = FindVersion(document, version, out var upstreamVersion); + if (manifest == null) return null; + // Stored under the upstream's spelling only: a file name with other build metadata (or case) is a different URL, not a second copy. + if (!string.Equals(upstreamVersion, version, StringComparison.Ordinal)) return null; + + var dist = manifest["dist"] as JsonObject; + var announcedIntegrity = Text(dist?["integrity"]); + var announcedShasum = Text(dist?["shasum"]); + var url = NpmUpstreamClient.TarballUri(upstream.Settings, name, upstreamVersion!, Text(dist?["tarball"])); + + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.MirrorFetch); + activity?.SetTag(BaGetDiagnostics.Tags.PackageId, name); + activity?.SetTag(BaGetDiagnostics.Tags.PackageVersion, version); + + try + { + var download = await _upstream.DownloadAsync(upstream, name, version, url, cancellationToken).ConfigureAwait(false); + if (download == null) + { + activity?.SetTag(BaGetDiagnostics.Tags.Result, "NotFound"); + _logger.LogWarning("The upstream of repository {Repository} lists {Package}@{Version} but has no tarball for it.", upstream.Name, name, version); + + return null; + } + + if (!upstream.Settings.StoreLocally) + { + // Pass-through: the client verifies the integrity it has from the packument. + activity?.SetTag(BaGetDiagnostics.Tags.Result, "PassThrough"); + + return new NpmTarball(new OwningStream(download), download.Length ?? 0, announcedIntegrity ?? string.Empty); + } + + using (download) + { + await using var temporary = new FileStream( + Path.Combine(Path.GetTempPath(), "baget-npm-" + Guid.NewGuid().ToString("N")), + FileMode.CreateNew, + FileAccess.ReadWrite, + FileShare.None, + 81920, + FileOptions.DeleteOnClose | FileOptions.Asynchronous); + + long length; + string integrity, shasum; + try + { + (length, integrity, shasum) = await CopyAndHashAsync(download.Content, temporary, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is IOException or System.Net.Http.HttpRequestException) + { + throw new NpmUpstreamException(_upstream.Rejected(upstream, "The download from the upstream was cut off.")); + } + + // What arrived must be what the upstream's own packument promised; a mismatch is never stored or served. + if ((announcedIntegrity != null && announcedIntegrity.StartsWith("sha512-", StringComparison.Ordinal) && !string.Equals(announcedIntegrity, integrity, StringComparison.Ordinal)) + || (announcedShasum != null && !string.Equals(announcedShasum, shasum, StringComparison.OrdinalIgnoreCase))) + { + throw new NpmUpstreamException(_upstream.Rejected(upstream, $"The tarball of {name}@{version} does not match the integrity its packument announces.")); + } + + var time = document["time"] as JsonObject; + var published = ParseTime(Text(time?[upstreamVersion!])) ?? DateTime.UtcNow; + var created = ParseTime(Text(time?["created"])) ?? published; + var modified = ParseTime(Text(document["modified"])) ?? ParseTime(Text(time?["modified"])) ?? published; + + await _local.StoreCachedAsync( + new NpmCachedVersion(name, version, manifest, published, created, modified, Text(manifest["deprecated"]), integrity, shasum, length, Tags(document)), + temporary, + cancellationToken).ConfigureAwait(false); + } + + activity?.SetTag(BaGetDiagnostics.Tags.Result, "Success"); + } + catch (Exception e) when (e is not MaintenanceException and not OperationCanceledException) + { + BaGetDiagnostics.Fail(activity, e); + + throw; + } + + return await _local.OpenTarballAsync(name, file, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task ProbeAsync(string name, string version, CancellationToken cancellationToken) + { + if (await _local.ProbeAsync(name, version, cancellationToken).ConfigureAwait(false) == ResolutionOutcome.Stored) return ResolutionOutcome.Stored; + + var upstream = await _upstream.ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return ResolutionOutcome.NotFound; + + // The same gate a download applies, so the preview cannot disagree with a real request. + if (upstream.Settings.Offline) return ResolutionOutcome.Offline; + if (_upstream.IsKnownAbsent(upstream, name, version)) return ResolutionOutcome.NotFound; + + var answer = await _upstream.GetPackumentAsync(upstream, name, abbreviated: true, cancellationToken).ConfigureAwait(false); + + return answer.Status switch + { + NpmUpstreamStatus.Found => FindVersion(answer.Document!, version, out _) == null ? ResolutionOutcome.NotFound : ResolutionOutcome.WouldFetch, + NpmUpstreamStatus.Unavailable => ResolutionOutcome.Unavailable, + NpmUpstreamStatus.Offline => ResolutionOutcome.Offline, + _ => ResolutionOutcome.NotFound, + }; + } + + // ---- writes: none --------------------------------------------------------------------------------------------------- + + private static Task Refuse(BaGetPrincipal? caller) + => Task.FromResult(caller == null ? NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required.") : NpmResult.Fail(NpmStatus.Forbidden, NoChanges)); + + /// + public Task PublishAsync(BaGetPrincipal? caller, NpmPublication publication, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task PublishTarballAsync(BaGetPrincipal? caller, Stream tarball, string tag, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task SetDistTagAsync(BaGetPrincipal? caller, string name, string tag, string version, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task RemoveDistTagAsync(BaGetPrincipal? caller, string name, string tag, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task DeprecateAsync(BaGetPrincipal? caller, string name, IReadOnlyDictionary messages, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task UnpublishVersionsAsync(BaGetPrincipal? caller, string name, IReadOnlyCollection versions, IReadOnlyDictionary? newTags, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task UnpublishPackageAsync(BaGetPrincipal? caller, string name, CancellationToken cancellationToken) => Refuse(caller); + + /// + public Task DeleteTarballAsync(BaGetPrincipal? caller, string name, string file, CancellationToken cancellationToken) => Refuse(caller); + + // ---- documents ------------------------------------------------------------------------------------------------------ + + // Points every tarball at this server. Versions that are not semantic versions are dropped (this server could not serve + // their tarball names, and npm cannot install them from a registry that does not either). + private JsonObject Rewrite(JsonObject document, string name) + { + var registry = _urls.GetNpmRegistryUrl(); + document["name"] = name; + + if (document["versions"] is JsonObject versions) + { + foreach (var pair in versions.ToList()) + { + if (pair.Value is not JsonObject manifest || !NpmNames.TryParseVersion(pair.Key, out _)) + { + versions.Remove(pair.Key); + (document["time"] as JsonObject)?.Remove(pair.Key); + + continue; + } + + var dist = manifest["dist"] as JsonObject ?? new JsonObject(); + dist["tarball"] = $"{registry}{name}/-/{NpmNames.TarballFileName(name, pair.Key)}"; + manifest["dist"] = dist; + } + + if (document["dist-tags"] is JsonObject tags) + { + foreach (var tag in tags.ToList()) + { + if (tag.Value is not JsonValue v || !v.TryGetValue(out var target) || !versions.ContainsKey(target)) tags.Remove(tag.Key); + } + } + } + + return document; + } + + private static NpmPackageInfo ToInfo(JsonObject document, string name) + { + var time = document["time"] as JsonObject; + var versions = new List(); + foreach (var pair in (document["versions"] as JsonObject) ?? new JsonObject()) + { + if (pair.Value is not JsonObject manifest || !NpmNames.TryParseVersion(pair.Key, out _)) continue; + + var copy = (JsonObject)manifest.DeepClone(); + var dist = copy["dist"] as JsonObject; + var integrity = Text(dist?["integrity"]) ?? string.Empty; + var shasum = Text(dist?["shasum"]) ?? string.Empty; + dist?.Remove("tarball"); + + versions.Add(new NpmVersionInfo( + pair.Key, + ParseTime(Text(time?[pair.Key])) ?? DateTime.UnixEpoch, + Text(copy["deprecated"]), + dist?["unpackedSize"] is JsonValue size && size.TryGetValue(out var bytes) ? bytes : 0, + integrity, + shasum, + copy)); + } + + var ordered = versions.OrderBy(v => v.Version, new NpmVersionOrder()).ToList(); + var created = ParseTime(Text(time?["created"])) ?? ordered.FirstOrDefault()?.Published ?? DateTime.UnixEpoch; + var modified = ParseTime(Text(time?["modified"])) ?? ordered.LastOrDefault()?.Published ?? created; + + return new NpmPackageInfo(name, created, modified, Tags(document), ordered); + } + + private static Dictionary Tags(JsonObject document) + { + var tags = new Dictionary(StringComparer.Ordinal); + foreach (var pair in (document["dist-tags"] as JsonObject) ?? new JsonObject()) + { + if (Text(pair.Value) is { } version) tags[pair.Key] = version; + } + + return tags; + } + + // The manifest of 'version' in a packument, matching by semantic version (build metadata ignored); the upstream's spelling is returned. + private static JsonObject? FindVersion(JsonObject document, string version, out string? upstreamVersion) + { + upstreamVersion = null; + if (document["versions"] is not JsonObject versions) return null; + + // The exact spelling first: an upstream may list versions that differ only in case. + if (versions[version] is JsonObject exact) + { + upstreamVersion = version; + + return exact; + } + + var wanted = NpmNames.Comparable(version); + foreach (var pair in versions) + { + if (pair.Value is JsonObject manifest && (pair.Key == version || NpmNames.Comparable(pair.Key) == wanted)) + { + upstreamVersion = pair.Key; + + return manifest; + } + } + + return null; + } + + private static string? Text(JsonNode? node) => node is JsonValue value && value.TryGetValue(out var text) ? text : null; + + private static DateTime? ParseTime(string? text) + => DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var parsed) ? parsed : null; + + private static async Task<(long Length, string Integrity, string Shasum)> CopyAndHashAsync(Stream source, Stream target, CancellationToken cancellationToken) + { + using var sha512 = IncrementalHash.CreateHash(HashAlgorithmName.SHA512); + using var sha1 = IncrementalHash.CreateHash(HashAlgorithmName.SHA1); + var buffer = new byte[81920]; + long length = 0; + int read; + while ((read = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + sha512.AppendData(buffer, 0, read); + sha1.AppendData(buffer, 0, read); + await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + length += read; + } + + await target.FlushAsync(cancellationToken).ConfigureAwait(false); + + return (length, "sha512-" + Convert.ToBase64String(sha512.GetHashAndReset()), Convert.ToHexString(sha1.GetHashAndReset()).ToLowerInvariant()); + } + + // Disposing the stream releases the download (its connection) too. + private sealed class OwningStream : Stream + { + private readonly NpmUpstreamDownload _download; + + public OwningStream(NpmUpstreamDownload download) + { + _download = download; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => _download.Content.Read(buffer, offset, count); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => _download.Content.ReadAsync(buffer, cancellationToken); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) _download.Dispose(); + + base.Dispose(disposing); + } + } +} + +/// Orders version strings by semantic version (an unparsable one by text). +internal sealed class NpmVersionOrder : IComparer +{ + public int Compare(string? x, string? y) + { + var okX = NuGet.Versioning.SemanticVersion.TryParse(x ?? string.Empty, out var a); + var okY = NuGet.Versioning.SemanticVersion.TryParse(y ?? string.Empty, out var b); + if (okX && okY) return a!.CompareTo(b!); + + return string.CompareOrdinal(x, y); + } +} diff --git a/src/BaGet.Core/Formats/Npm/VirtualNpmRegistry.cs b/src/BaGet.Core/Formats/Npm/VirtualNpmRegistry.cs new file mode 100644 index 000000000..c1e8cc380 --- /dev/null +++ b/src/BaGet.Core/Formats/Npm/VirtualNpmRegistry.cs @@ -0,0 +1,369 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Core; + +/// +/// of a npm repository: one registry made of its members, local or +/// remote, in resolution order (: only the members the caller may read, each asked in its own +/// scope, so its storage, upstream and rules apply; a member that fails is logged and skipped). +/// +/// +/// Packument. The members' packuments are merged: versions is the union, a version coming from the first +/// member that has it (its dist.tarball already points into the virtual repository: addresses come from the request); +/// dist-tags take, per tag, the first member that has the tag, so latest follows the member order, not the highest +/// version; time is the union with the earliest created and the latest modified; the other fields come from +/// the first member and are completed from the later ones. A package no member has is absent. +/// Tarball from the first member that has it. Search merges the members' listings by name (the first member's +/// entry wins), ordered by name; remote members contribute the packages they stored. +/// Writes go to the deploy repository, with that repository's rules and the caller's rights there: the HTTP routes and +/// pages are moved to it before they reach this class (RepositoryResolutionMiddleware, RepositoryPageGate); a caller of +/// the service gets the same through this class. Without a deploy repository they are refused (403). +/// +public sealed class VirtualNpmRegistry : INpmRegistry +{ + // The most search hits read from one member for a page: a merged page of skip+take needs at most that many from each. + internal const int MaxScanPerMember = 1000; + + private readonly IRepositoryContext _repository; + private readonly VirtualRepositoryReader _reader; + private readonly IVirtualRepositories _virtuals; + + public VirtualNpmRegistry(IRepositoryContext repository, VirtualRepositoryReader reader, IVirtualRepositories virtuals) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + } + + // ---- reads ---------------------------------------------------------------------------------------------------------- + + /// + public async Task GetPackumentAsync(string name, bool abbreviated, CancellationToken cancellationToken) + { + var members = await _reader.AllAsync( + name, + async sp => (await sp.GetRequiredService().GetPackumentAsync(name, abbreviated, cancellationToken).ConfigureAwait(false))!, + cancellationToken).ConfigureAwait(false); + + return members.Count == 0 ? null : MergePackuments(name, members.Select(m => m.Value).ToList(), abbreviated); + } + + /// Merges member packuments (in resolution order) as described on . + internal static JsonObject MergePackuments(string name, IReadOnlyList documents, bool abbreviated) + { + var result = new JsonObject(); + var versions = new Dictionary(StringComparer.Ordinal); + var comparable = new HashSet(StringComparer.Ordinal); + var times = new Dictionary(StringComparer.Ordinal); + var tags = new Dictionary(StringComparer.Ordinal); + DateTime? created = null, modified = null; + var revisions = new StringBuilder(); + + foreach (var document in documents) + { + var time = document["time"] as JsonObject; + if (document["versions"] is JsonObject own) + { + foreach (var pair in own) + { + if (pair.Value == null || !comparable.Add(NpmNames.Comparable(pair.Key))) continue; + + versions[pair.Key] = pair.Value.DeepClone(); + if (time?[pair.Key] is JsonNode at) times[pair.Key] = at.DeepClone(); + } + } + + foreach (var pair in (document["dist-tags"] as JsonObject) ?? new JsonObject()) + { + if (pair.Value is JsonValue v && v.TryGetValue(out var target) && !tags.ContainsKey(pair.Key)) tags[pair.Key] = target; + } + + created = Earlier(created, Time(time?["created"])); + modified = Later(modified, Time(time?["modified"] ?? document["modified"])); + revisions.Append(document["_rev"] is JsonValue rev && rev.TryGetValue(out var revision) ? revision : string.Empty).Append('|'); + + // The descriptive fields (description, readme, license...): the first member's, completed from the later ones. + foreach (var pair in document) + { + if (pair.Key is "versions" or "dist-tags" or "time" or "_rev" or "modified" or "name" or "_id" || pair.Value == null || result.ContainsKey(pair.Key)) continue; + + result[pair.Key] = pair.Value.DeepClone(); + } + } + + // A tag only points at a version the merged document has (a member's tag always does; an upstream may be inconsistent). + foreach (var tag in tags.Where(t => !versions.ContainsKey(t.Value)).ToList()) tags.Remove(tag.Key); + if (!tags.ContainsKey("latest")) + { + var highest = NpmNames.Highest(versions.Keys); + if (highest != null) tags["latest"] = highest; + } + + var versionsNode = new JsonObject(); + var timeNode = new JsonObject(); + foreach (var version in versions.Keys.OrderBy(v => v, new NpmVersionOrder())) + { + versionsNode[version] = versions[version]; + if (times.TryGetValue(version, out var at)) timeNode[version] = at; + } + + var tagsNode = new JsonObject(); + foreach (var tag in tags.OrderBy(t => t.Key, StringComparer.Ordinal)) tagsNode[tag.Key] = tag.Value; + + var stamp = modified ?? DateTime.UnixEpoch; + result["name"] = name; + result["dist-tags"] = tagsNode; + result["versions"] = versionsNode; + + if (abbreviated) + { + result["modified"] = Iso(stamp); + } + else + { + result["_id"] = name; + result["_rev"] = $"{versions.Count}-{Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(revisions.ToString())), 0, 8).ToLowerInvariant()}"; + timeNode["created"] = Iso(created ?? stamp); + timeNode["modified"] = Iso(stamp); + result["time"] = timeNode; + } + + return result; + } + + private static DateTime? Time(JsonNode? node) + => node is JsonValue v && v.TryGetValue(out var text) + && DateTime.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out var parsed) + ? parsed + : null; + + private static DateTime? Earlier(DateTime? a, DateTime? b) => a == null ? b : b == null ? a : (a < b ? a : b); + + private static DateTime? Later(DateTime? a, DateTime? b) => a == null ? b : b == null ? a : (a > b ? a : b); + + private static string Iso(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc).ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", System.Globalization.CultureInfo.InvariantCulture); + + /// + public async Task GetPackageAsync(string name, CancellationToken cancellationToken) + { + var members = await _reader.AllAsync( + name, + async sp => (await sp.GetRequiredService().GetPackageAsync(name, cancellationToken).ConfigureAwait(false))!, + cancellationToken).ConfigureAwait(false); + if (members.Count == 0) return null; + + var versions = new Dictionary(StringComparer.Ordinal); + var seen = new HashSet(StringComparer.Ordinal); + var tags = new Dictionary(StringComparer.Ordinal); + foreach (var info in members.Select(m => m.Value)) + { + foreach (var version in info.Versions) + { + if (seen.Add(NpmNames.Comparable(version.Version))) versions[version.Version] = version; + } + + foreach (var tag in info.DistTags) + { + if (!tags.ContainsKey(tag.Key)) tags[tag.Key] = tag.Value; + } + } + + foreach (var tag in tags.Where(t => !versions.ContainsKey(t.Value)).ToList()) tags.Remove(tag.Key); + if (!tags.ContainsKey("latest") && NpmNames.Highest(versions.Keys) is { } highest) tags["latest"] = highest; + + return new NpmPackageInfo( + name, + members.Min(m => m.Value.Created), + members.Max(m => m.Value.Modified), + tags, + versions.Values.OrderBy(v => v.Version, new NpmVersionOrder()).ToList()); + } + + /// + public async Task?> GetDistTagsAsync(string name, CancellationToken cancellationToken) + => (await GetPackageAsync(name, cancellationToken).ConfigureAwait(false))?.DistTags; + + /// + public Task OpenTarballAsync(string name, string file, CancellationToken cancellationToken) + => _reader.FirstAsync(name, sp => sp.GetRequiredService().OpenTarballAsync(name, file, cancellationToken), cancellationToken); + + /// + public async Task SearchAsync(string? text, int skip, int take, Func>? canRead = null, CancellationToken cancellationToken = default) + { + skip = Math.Max(skip, 0); + take = Math.Clamp(take, 0, 250); + var window = Math.Min(skip + take, MaxScanPerMember); + + var byName = new SortedDictionary(StringComparer.Ordinal); + var complete = true; + var upperBound = 0; + + foreach (var member in await _reader.ReadableMembersAsync(null, cancellationToken).ConfigureAwait(false)) + { + NpmSearchPage? page; + try + { + var asked = member; + page = await _reader.InMemberAsync(member, async sp => await sp.GetRequiredService().SearchAsync( + text, + 0, + window, + async (name, token) => await _reader.CanReadInMemberAsync(asked, name, token).ConfigureAwait(false) + && (canRead == null || await canRead(name, token).ConfigureAwait(false)), + cancellationToken).ConfigureAwait(false)).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + complete = false; + continue; + } + + if (page == null) continue; + + upperBound += page.Total; + if (page.Total > page.Hits.Count) complete = false; + foreach (var hit in page.Hits) byName.TryAdd(hit.Name, hit); + } + + // Exact while every member was read completely; else the most the members could hold together. + var total = complete ? byName.Count : Math.Max(byName.Count, upperBound); + + return new NpmSearchPage(total, byName.Values.Skip(skip).Take(take).ToList()); + } + + /// + public async Task ProbeAsync(string name, string version, CancellationToken cancellationToken) + { + var worst = ResolutionOutcome.NotFound; + foreach (var member in await _reader.ReadableMembersAsync(name, cancellationToken).ConfigureAwait(false)) + { + var outcome = await _reader.InMemberAsync(member, sp => sp.GetRequiredService().ProbeAsync(name, version, cancellationToken)).ConfigureAwait(false); + if (outcome is ResolutionOutcome.Stored or ResolutionOutcome.WouldFetch) return outcome; + if (outcome is ResolutionOutcome.Unavailable or ResolutionOutcome.Offline) worst = outcome; + } + + return worst; + } + + // ---- writes: the deploy repository ---------------------------------------------------------------------------------- + + private async Task OnDeployAsync(BaGetPrincipal? caller, Func> write, CancellationToken cancellationToken) + { + if (caller == null) return NpmResult.Fail(NpmStatus.Unauthorized, "Authentication is required."); + + var target = await _virtuals.DeployTargetAsync(_repository.Current, cancellationToken).ConfigureAwait(false); + if (target == null) return NpmResult.Fail(NpmStatus.Forbidden, "This virtual repository has no deploy repository, so it takes no changes."); + + return await _reader.InMemberAsync(target, sp => write(sp.GetRequiredService())).ConfigureAwait(false); + } + + /// + public Task PublishAsync(BaGetPrincipal? caller, NpmPublication publication, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.PublishAsync(caller, publication, cancellationToken), cancellationToken); + + /// + public Task PublishTarballAsync(BaGetPrincipal? caller, Stream tarball, string tag, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.PublishTarballAsync(caller, tarball, tag, cancellationToken), cancellationToken); + + /// + public Task SetDistTagAsync(BaGetPrincipal? caller, string name, string tag, string version, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.SetDistTagAsync(caller, name, tag, version, cancellationToken), cancellationToken); + + /// + public Task RemoveDistTagAsync(BaGetPrincipal? caller, string name, string tag, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.RemoveDistTagAsync(caller, name, tag, cancellationToken), cancellationToken); + + /// + public Task DeprecateAsync(BaGetPrincipal? caller, string name, IReadOnlyDictionary messages, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.DeprecateAsync(caller, name, messages, cancellationToken), cancellationToken); + + /// + public Task UnpublishVersionsAsync(BaGetPrincipal? caller, string name, IReadOnlyCollection versions, IReadOnlyDictionary? newTags, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.UnpublishVersionsAsync(caller, name, versions, newTags, cancellationToken), cancellationToken); + + /// + public Task UnpublishPackageAsync(BaGetPrincipal? caller, string name, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.UnpublishPackageAsync(caller, name, cancellationToken), cancellationToken); + + /// + public Task DeleteTarballAsync(BaGetPrincipal? caller, string name, string file, CancellationToken cancellationToken) + => OnDeployAsync(caller, r => r.DeleteTarballAsync(caller, name, file, cancellationToken), cancellationToken); +} + +/// +/// The everything resolves: it forwards to the registry that fits the kind of the request's +/// repository ( for a local one, , ), so +/// the routes and pages never ask which. +/// +public sealed class RepositoryNpmRegistry : INpmRegistry +{ + private readonly IRepositoryContext _repository; + private readonly IServiceProvider _services; + + public RepositoryNpmRegistry(IRepositoryContext repository, IServiceProvider services) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + // Resolved per call: the repository of the scope can move (a write to a virtual repository continues in its deploy repository). + private INpmRegistry Inner => _repository.Current.Kind switch + { + RepositoryKind.Remote => _services.GetRequiredService(), + RepositoryKind.Virtual => _services.GetRequiredService(), + _ => _services.GetRequiredService(), + }; + + /// + public Task GetPackageAsync(string name, CancellationToken cancellationToken) => Inner.GetPackageAsync(name, cancellationToken); + + /// + public Task GetPackumentAsync(string name, bool abbreviated, CancellationToken cancellationToken) => Inner.GetPackumentAsync(name, abbreviated, cancellationToken); + + /// + public Task OpenTarballAsync(string name, string file, CancellationToken cancellationToken) => Inner.OpenTarballAsync(name, file, cancellationToken); + + /// + public Task PublishAsync(BaGetPrincipal? caller, NpmPublication publication, CancellationToken cancellationToken) => Inner.PublishAsync(caller, publication, cancellationToken); + + /// + public Task PublishTarballAsync(BaGetPrincipal? caller, Stream tarball, string tag, CancellationToken cancellationToken) => Inner.PublishTarballAsync(caller, tarball, tag, cancellationToken); + + /// + public Task?> GetDistTagsAsync(string name, CancellationToken cancellationToken) => Inner.GetDistTagsAsync(name, cancellationToken); + + /// + public Task SetDistTagAsync(BaGetPrincipal? caller, string name, string tag, string version, CancellationToken cancellationToken) => Inner.SetDistTagAsync(caller, name, tag, version, cancellationToken); + + /// + public Task RemoveDistTagAsync(BaGetPrincipal? caller, string name, string tag, CancellationToken cancellationToken) => Inner.RemoveDistTagAsync(caller, name, tag, cancellationToken); + + /// + public Task DeprecateAsync(BaGetPrincipal? caller, string name, IReadOnlyDictionary messages, CancellationToken cancellationToken) => Inner.DeprecateAsync(caller, name, messages, cancellationToken); + + /// + public Task UnpublishVersionsAsync(BaGetPrincipal? caller, string name, IReadOnlyCollection versions, IReadOnlyDictionary? newTags, CancellationToken cancellationToken) + => Inner.UnpublishVersionsAsync(caller, name, versions, newTags, cancellationToken); + + /// + public Task UnpublishPackageAsync(BaGetPrincipal? caller, string name, CancellationToken cancellationToken) => Inner.UnpublishPackageAsync(caller, name, cancellationToken); + + /// + public Task DeleteTarballAsync(BaGetPrincipal? caller, string name, string file, CancellationToken cancellationToken) => Inner.DeleteTarballAsync(caller, name, file, cancellationToken); + + /// + public Task SearchAsync(string? text, int skip, int take, Func>? canRead = null, CancellationToken cancellationToken = default) + => Inner.SearchAsync(text, skip, take, canRead, cancellationToken); + + /// + public Task ProbeAsync(string name, string version, CancellationToken cancellationToken) => Inner.ProbeAsync(name, version, cancellationToken); +} diff --git a/src/BaGet.Core/Formats/NuGetFormatModule.cs b/src/BaGet.Core/Formats/NuGetFormatModule.cs new file mode 100644 index 000000000..30f2f8075 --- /dev/null +++ b/src/BaGet.Core/Formats/NuGetFormatModule.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// NuGet on the format layer: V3 (v3/…), V2 (api/v2) and symbol routes at the repository base, packages and symbols +/// in the folders that predate repositories. Its behaviour is exactly what the code did before the layer existed; this class only +/// names it, so the common code no longer assumes NuGet. +/// +public class NuGetFormatModule : IFormatModule +{ + /// + public RepositoryFormat Format => RepositoryFormat.NuGet; + + /// + public string DisplayName => "NuGet"; + + /// + public bool SupportsVirtual => true; + + /// + public string RoutePrefix => string.Empty; + + /// + public string FeedPath => "v3/index.json"; + + /// + public IReadOnlyCollection CreatableKinds { get; } = new[] { RepositoryKind.Local, RepositoryKind.Remote }; + + /// + public IReadOnlyList StorageFolders { get; } = new[] { "packages", "symbols", "catalog", "validation", "staging" }; + + /// + /// None: a NuGet repository is a name (a remote one has its own form with the upstream settings). + public IReadOnlyList CreateFields { get; } = Array.Empty(); + + /// + public string? CreateSettings(IReadOnlyDictionary fields) => null; + + /// + /// + /// Browse and upload, then the protocol resources a client or an operator can open besides the service index: the V2 feed, + /// the vulnerability index, and (a local repository only, the others have no log or signer of their own) the catalog and the + /// repository signatures. + /// + public IReadOnlyList RepositoryLinks(RepositoryInfo repository) + { + var links = new List + { + FormatLink.ToScreen("browse", "Browse", "Home", "Index"), + FormatLink.ToScreen("upload", "Upload", "Upload", "Index", needsUploads: true), + FormatLink.ToPath("v2", "V2 feed", "api/v2"), + FormatLink.ToPath("vulnerabilities", "Vulnerabilities", "v3/vulnerabilities/index.json"), + }; + + if (repository.Kind == RepositoryKind.Local) + { + links.Add(FormatLink.ToPath("catalog", "Catalog", "v3/catalog/index.json")); + links.Add(FormatLink.ToPath("signatures", "Signatures", "v3/repository-signatures/index.json")); + } + + return links; + } + + /// + public async Task> CountArtifactsAsync(IContext context, CancellationToken cancellationToken) + => await context.Packages! + .IgnoreQueryFilters() + .GroupBy(p => p.RepositoryKey) + .Select(g => new { Key = g.Key, Count = g.Count() }) + .ToDictionaryAsync(g => g.Key, g => g.Count, cancellationToken) + .ConfigureAwait(false); + + /// + public async Task GetUsageAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + var packages = await context.Packages!.IgnoreQueryFilters().CountAsync(e => e.RepositoryKey == repositoryKey, cancellationToken).ConfigureAwait(false); + + // A pushed package the client already got an accepted response for, staged but not indexed yet: deleting loses it. + var pending = await context.PackageValidations!.IgnoreQueryFilters() + .AnyAsync(e => e.RepositoryKey == repositoryKey && e.State == PackageValidationState.Pending, cancellationToken).ConfigureAwait(false); + + return new FormatUsage(packages, pending); + } + + /// + /// + /// The catalog is an append-only log (deleting a package adds an entry) and owner rows outlive their package, so those, the + /// finished validations, the abuse reports and the symbol records are history of a repository that no longer exists. + /// + public async Task StagePurgeAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + context.CatalogLeafs!.RemoveRange(await context.CatalogLeafs!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + context.PackageOwners!.RemoveRange(await context.PackageOwners!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + context.PackageValidations!.RemoveRange(await context.PackageValidations!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + context.AbuseReports!.RemoveRange(await context.AbuseReports!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + context.PackageSymbols!.RemoveRange(await context.PackageSymbols!.IgnoreQueryFilters().Where(e => e.RepositoryKey == repositoryKey).ToListAsync(cancellationToken).ConfigureAwait(false)); + } +} + +/// NuGet's : the push pipeline (). +public class NuGetFormatIndexer : IFormatIndexer +{ + private readonly IPackageIndexingService _indexing; + + /// The service that validates, stores and records a package. + public NuGetFormatIndexer(IPackageIndexingService indexing) + { + _indexing = indexing ?? throw new ArgumentNullException(nameof(indexing)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.NuGet; + + /// + public async Task IndexAsync(Stream? artifact, CancellationToken cancellationToken) + => await _indexing.IndexAsync(artifact, cancellationToken).ConfigureAwait(false) switch + { + PackageIndexingResult.Success => FormatIndexResult.Indexed, + PackageIndexingResult.Accepted => FormatIndexResult.Accepted, + PackageIndexingResult.PackageAlreadyExists => FormatIndexResult.AlreadyExists, + _ => FormatIndexResult.Invalid, + }; +} + +/// NuGet's : the registered (so a virtual repository merges its members). +public class NuGetFormatSearchProvider : IFormatSearchProvider +{ + private readonly ISearchService _search; + + /// The search service of the host. + public NuGetFormatSearchProvider(ISearchService search) + { + _search = search ?? throw new ArgumentNullException(nameof(search)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.NuGet; + + /// + public async Task SearchAsync(FormatSearchQuery query, CancellationToken cancellationToken) + { + if (query == null) throw new ArgumentNullException(nameof(query)); + + var response = await _search.SearchAsync( + new SearchRequest + { + Query = query.Query, + Skip = query.Skip, + Take = query.Take, + IncludePrerelease = query.IncludePrerelease, + IncludeSemVer2 = true, + }, + cancellationToken).ConfigureAwait(false); + + var hits = (response.Data ?? Array.Empty()) + .Select(r => new FormatSearchHit(r.PackageId ?? string.Empty, r.Version, r.Description, r.TotalDownloads)) + .ToList(); + + return new FormatSearchPage(response.TotalHits, hits); + } +} diff --git a/src/BaGet.Core/Formats/NuGetFormatScanner.cs b/src/BaGet.Core/Formats/NuGetFormatScanner.cs new file mode 100644 index 000000000..d353814ec --- /dev/null +++ b/src/BaGet.Core/Formats/NuGetFormatScanner.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using NuGet.Packaging; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// What a NuGet package is made of for scanning: itself and its dependencies at the lowest version their range allows (the version +/// NuGet restores). Dependencies without a lower bound are skipped. +/// +public static class NuGetScanComponents +{ + /// The OSV ecosystem name. + public const string Ecosystem = "NuGet"; + + /// The package and its dependencies. + /// The package id. + /// The package version. + /// The declared dependencies as (id, version range) pairs, all target frameworks together. + public static IReadOnlyList Of(string id, string version, IEnumerable<(string? Id, string? Range)> dependencies) + { + var result = new List { new(Ecosystem, id, NormalizeVersion(version)) }; + foreach (var (dependencyId, range) in dependencies) + { + if (string.IsNullOrWhiteSpace(dependencyId) || string.IsNullOrWhiteSpace(range)) continue; + if (!VersionRange.TryParse(range, out var parsed) || parsed.MinVersion == null) continue; + + var component = new ScanComponent(Ecosystem, dependencyId, parsed.MinVersion.ToNormalizedString()); + if (!result.Contains(component)) result.Add(component); + } + + return result; + } + + /// + /// The components of a .nupkg being pushed, or null when the stream is not a readable package (the indexer then refuses + /// it with its own message). The stream is rewound. + /// + public static IReadOnlyList? TryRead(Stream package) + { + if (package == null) throw new ArgumentNullException(nameof(package)); + + try + { + package.Position = 0; + using var reader = new PackageArchiveReader(package, leaveStreamOpen: true); + var identity = reader.GetIdentity(); + var dependencies = reader.GetPackageDependencies() + .SelectMany(g => g.Packages) + .Select(d => ((string?)d.Id, (string?)d.VersionRange.ToNormalizedString())); + return Of(identity.Id, identity.Version.ToNormalizedString(), dependencies); + } + catch (Exception e) when (e is not OperationCanceledException) + { + return null; + } + finally + { + try { package.Position = 0; } catch (NotSupportedException) { } + } + } + + private static string NormalizeVersion(string version) + => NuGetVersion.TryParse(version, out var parsed) ? parsed.ToNormalizedString() : version; +} + +/// NuGet's : the repository's packages and their declared dependencies against OSV. +public sealed class NuGetFormatScanner : IFormatScanner +{ + private readonly IContext _context; + + public NuGetFormatScanner(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.NuGet; + + /// + public async Task> ListComponentsAsync(string name, string version, CancellationToken cancellationToken) + { + if (_context is NullContext) return Array.Empty(); + var normalized = NuGetVersion.TryParse(version, out var parsed) ? parsed.ToNormalizedString() : version; + + var package = await _context.Packages! + .AsNoTracking() + .Include(p => p.Dependencies) + .AsSplitQuery() + .FirstOrDefaultAsync(p => p.Id == name && p.NormalizedVersionString == normalized, cancellationToken) + .ConfigureAwait(false); + if (package == null) return Array.Empty(); + + return NuGetScanComponents.Of( + package.Id!, + package.NormalizedVersionString!, + (package.Dependencies ?? new List()).Select(d => (d.Id, d.VersionRange))); + } + + /// + public async Task> ListArtifactsAsync(CancellationToken cancellationToken) + { + if (_context is NullContext) return Array.Empty(); + + var rows = await _context.Packages! + .AsNoTracking() + .Select(p => new { p.Id, p.NormalizedVersionString }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + return rows.Select(r => new ScanArtifact(r.Id!, r.NormalizedVersionString!)).ToList(); + } +} diff --git a/src/BaGet.Core/Formats/NuGetRetentionHooks.cs b/src/BaGet.Core/Formats/NuGetRetentionHooks.cs new file mode 100644 index 000000000..047f9d129 --- /dev/null +++ b/src/BaGet.Core/Formats/NuGetRetentionHooks.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// NuGet's : versions are the repository's package rows, deleted for good through +/// whatever PackageDeletionBehavior says (a retention policy +/// is cleanup, not the protocol's DELETE). Download times come from . +/// +public sealed class NuGetRetentionHooks : IFormatRetentionHooks +{ + private readonly IContext _context; + private readonly IPackageDeletionService _deletion; + private readonly IPackageStorageService _storage; + + public NuGetRetentionHooks(IContext context, IPackageDeletionService deletion, IPackageStorageService storage) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _deletion = deletion ?? throw new ArgumentNullException(nameof(deletion)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.NuGet; + + /// + public async Task> ListVersionsAsync(CancellationToken cancellationToken) + { + var usage = await ArtifactUsageMap.LoadAsync(_context, cancellationToken).ConfigureAwait(false); + var rows = await _context.Packages!.AsNoTracking() + .Select(p => new { p.Id, p.NormalizedVersionString, p.Published, p.IsPrerelease }) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + // The size of a package is in the store, not the row: GetSizeAsync reads it when a cache limit needs it. + return rows + .Select(r => new FormatVersion(r.Id!, r.NormalizedVersionString!, DateTime.SpecifyKind(r.Published, DateTimeKind.Utc), usage.Get(r.Id!, r.NormalizedVersionString!), null, r.IsPrerelease)) + .ToList(); + } + + /// + public async Task DeleteVersionAsync(string name, string version, CancellationToken cancellationToken) + => await _deletion.TryHardDeletePackageAsync(name, NuGetVersion.Parse(version), cancellationToken).ConfigureAwait(false); + + /// + public async Task GetSizeAsync(string name, string version, CancellationToken cancellationToken) + { + using var stream = await _storage.GetPackageStreamAsync(name, NuGetVersion.Parse(version), cancellationToken).ConfigureAwait(false); + if (stream == null) return null; + if (stream.CanSeek) return stream.Length; + + // A store that cannot say (object storage behind a forward-only stream): count the bytes. + long total = 0; + var buffer = new byte[81920]; + int read; + while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) total += read; + + return total; + } + + /// + public (string Name, string Version)? Canonical(string name, string? version) + { + if (string.IsNullOrWhiteSpace(name)) return null; + if (string.IsNullOrWhiteSpace(version)) return (name.Trim(), string.Empty); + + return NuGetVersion.TryParse(version.Trim(), out var parsed) ? (name.Trim(), parsed.ToNormalizedString().ToLowerInvariant()) : null; + } +} diff --git a/src/BaGet.Core/Ha/ClusterJobLease.cs b/src/BaGet.Core/Ha/ClusterJobLease.cs new file mode 100644 index 000000000..2124e5422 --- /dev/null +++ b/src/BaGet.Core/Ha/ClusterJobLease.cs @@ -0,0 +1,154 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// The cluster-wide : a key in the shared store that only one node can create, holding the holder's name. The +/// holder renews it every third of , so a node that dies frees its jobs within that +/// time, and a lease that could not be renewed is reported (the job itself is not interrupted). When the store cannot be reached the +/// lease is refused, so a job is skipped rather than run twice. +/// +public sealed class ClusterJobLease : IJobLease, IJobLeaseAvailability +{ + private readonly ClusterRuntime _cluster; + private readonly ILogger _logger; + + /// Creates the lease over the cluster's store. + public ClusterJobLease(ClusterRuntime cluster, ILogger logger) + { + _cluster = cluster ?? throw new ArgumentNullException(nameof(cluster)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + if (_cluster.Store == null) throw new InvalidOperationException("ClusterJobLease needs Ha:Enabled and a cluster store."); + } + + /// + public async ValueTask TryAcquireAsync(string job, CancellationToken cancellationToken) + { + if (job == null) throw new ArgumentNullException(nameof(job)); + + var store = _cluster.Store!; + var key = ClusterRuntime.Keys.Lease(job); + var value = LeaseInfo.Format(_cluster.NodeId, Guid.NewGuid().ToString("N"), DateTime.UtcNow); + try + { + if (!await store.SetIfAbsentAsync(key, value, _cluster.LeaseDuration, cancellationToken).ConfigureAwait(false)) return null; + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "Could not take the lease {Job}; the job is skipped.", job); + + return null; + } + + return new Held(store, key, value, job, _cluster.LeaseDuration, _logger); + } + + /// + public async Task IsAvailableAsync(CancellationToken cancellationToken) + { + try + { + return await _cluster.Store!.PingAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + return false; + } + } + + private sealed class Held : IAsyncDisposable + { + private readonly IClusterStore _store; + private readonly string _key; + private readonly string _value; + private readonly string _job; + private readonly TimeSpan _duration; + private readonly ILogger _logger; + private readonly CancellationTokenSource _stop = new(); + private readonly Task _renewing; + private int _disposed; + + public Held(IClusterStore store, string key, string value, string job, TimeSpan duration, ILogger logger) + { + _store = store; + _key = key; + _value = value; + _job = job; + _duration = duration; + _logger = logger; + _renewing = Task.Run(RenewAsync); + } + + private async Task RenewAsync() + { + var every = TimeSpan.FromTicks(_duration.Ticks / 3); + try + { + while (!_stop.IsCancellationRequested) + { + await Task.Delay(every, _stop.Token).ConfigureAwait(false); + try + { + if (!await _store.ExtendIfValueAsync(_key, _value, _duration, _stop.Token).ConfigureAwait(false)) + { + _logger.LogWarning("The lease {Job} was lost (it expired or was taken); the job may now run on two nodes.", _job); + + return; + } + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "The lease {Job} could not be renewed; it is retried.", _job); + } + } + } + catch (OperationCanceledException) + { + } + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + + _stop.Cancel(); + try + { + await _renewing.ConfigureAwait(false); + await _store.DeleteIfValueAsync(_key, _value, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) + { + // The key expires by itself. + _logger.LogWarning(e, "Could not release the lease {Job}; it expires by itself.", _job); + } + finally + { + _stop.Dispose(); + } + } + } +} + +/// A lease as stored: the holder's node, a token that tells two holders of one node apart, and when it was taken. +/// The job's name. +/// The holder. +/// When it was acquired (UTC). +public sealed record LeaseInfo(string Job, string Node, DateTime Since) +{ + internal static string Format(string node, string token, DateTime since) + => node + "|" + token + "|" + since.ToString("O", System.Globalization.CultureInfo.InvariantCulture); + + internal static LeaseInfo? Parse(string job, string value) + { + var parts = value.Split('|'); + if (parts.Length < 3) return null; + + return DateTime.TryParse(parts[2], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var since) + ? new LeaseInfo(job, parts[0], since) + : new LeaseInfo(job, parts[0], DateTime.MinValue); + } +} diff --git a/src/BaGet.Core/Ha/ClusterRuntime.cs b/src/BaGet.Core/Ha/ClusterRuntime.cs new file mode 100644 index 000000000..bc4945466 --- /dev/null +++ b/src/BaGet.Core/Ha/ClusterRuntime.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// What a node knows about the cluster it is in: whether it is in one, its name, and the shared store. Always registered; without +/// Ha:Enabled is false and is null, and every component keeps its in-process behaviour. +/// +public sealed class ClusterRuntime +{ + private readonly HaOptions _options; + + /// Creates the runtime. + /// The HA options (read once; they need a restart). + /// The shared store, registered only in HA mode. + public ClusterRuntime(IOptions options, IClusterStore? store = null) + { + _options = (options ?? throw new ArgumentNullException(nameof(options))).Value ?? new HaOptions(); + Store = _options.Enabled ? store : null; + Started = DateTime.UtcNow; + NodeId = string.IsNullOrWhiteSpace(_options.NodeName) + ? Environment.MachineName.ToLowerInvariant() + "-" + Guid.NewGuid().ToString("N").Substring(0, 6) + : _options.NodeName!.Trim(); + } + + /// Whether this node is part of a cluster (HA enabled and a store present). + public bool IsEnabled => Store != null; + + /// The shared store, or null on a single node. + public IClusterStore? Store { get; } + + /// This node's name on the cluster page and in lease holders. + public string NodeId { get; } + + /// When this node started (UTC). + public DateTime Started { get; } + + /// How long a lease lasts without being renewed. + public TimeSpan LeaseDuration => _options.LeaseDuration; + + /// How often the node publishes and polls. + public TimeSpan SyncInterval => _options.SyncInterval; + + /// How long a node's heartbeat stays listed after its last one. + public TimeSpan HeartbeatTtl => TimeSpan.FromTicks(Math.Max(SyncInterval.Ticks * 4, TimeSpan.FromSeconds(10).Ticks)); + + /// Key names (relative to Ha:KeyPrefix, which the store adds). + public static class Keys + { + public const string NodePrefix = "node:"; + public const string LeasePrefix = "lease:"; + public const string Gate = "gate"; + public const string AccessVersion = "access-version"; + public const string CopyStatus = "copy-status"; + + public static string Node(string id) => NodePrefix + id; + + public static string Lease(string job) => LeasePrefix + job; + } +} + +/// +/// The storage and database a cluster may use: both must be reachable from every node. Checked at startup (the node refuses to start) +/// and by ValidateStartupOptions. +/// +public sealed class HaBackendRules +{ + /// Tests and a single-host trial may accept a local database and the file system; production never should. + public bool AllowLocalBackends { get; init; } + + /// What stops from running on this database and storage (empty when nothing). + public IReadOnlyList Check(HaOptions ha, DatabaseOptions? database, StorageOptions? storage) + { + if (ha == null) throw new ArgumentNullException(nameof(ha)); + if (!ha.Enabled) return Array.Empty(); + + var problems = ha.Validate().ToList(); + if (string.IsNullOrWhiteSpace(ha.ConnectionString)) + { + problems.Add("Ha:ConnectionString is required (the Redis connection string)."); + } + + if (AllowLocalBackends) return problems; + + var databaseType = database?.Type; + if (string.IsNullOrWhiteSpace(databaseType) || string.Equals(databaseType, "Sqlite", StringComparison.OrdinalIgnoreCase)) + { + problems.Add("Ha:Enabled needs a database every node can reach: SQLite is a file on one machine (use SqlServer, PostgreSql or MySql)."); + } + else if (string.Equals(databaseType, "AzureTable", StringComparison.OrdinalIgnoreCase)) + { + problems.Add("Ha:Enabled keeps the data protection keys in a relational database: Azure Table is not supported (use SqlServer, PostgreSql or MySql)."); + } + + var storageType = storage?.Type; + if (string.IsNullOrWhiteSpace(storageType) || string.Equals(storageType, "Filesystem", StringComparison.OrdinalIgnoreCase)) + { + problems.Add("Ha:Enabled needs storage every node can reach: the file system is local to one machine (use AwsS3, AzureBlobStorage, GoogleCloud or AliyunOss)."); + } + + return problems; + } +} diff --git a/src/BaGet.Core/Ha/ClusterSyncService.cs b/src/BaGet.Core/Ha/ClusterSyncService.cs new file mode 100644 index 000000000..0ac41f9e8 --- /dev/null +++ b/src/BaGet.Core/Ha/ClusterSyncService.cs @@ -0,0 +1,362 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// A node as it publishes itself. +/// The node's name. +/// When it started (UTC). +/// Its latest heartbeat (UTC). +/// The BaGet version it runs. +/// Whether its last readiness check passed. +/// What failed, when it did not. +/// Whether its read-only gate is closed. +public sealed record NodeInfo(string Id, DateTime Started, DateTime Seen, string Version, bool Ready, string? Problem, bool GateClosed); + +/// +/// The node's side of a cluster: publishes a heartbeat and brings the state the nodes share into this process every +/// : +/// +/// the read-only (a closure published by one node closes all; it lives while its node renews it); +/// the access model's version (a change committed on one node makes the others reload their snapshot); +/// the database copy's progress (a copy runs on the node that accepted it; every node shows it). +/// +/// Idle without Ha:Enabled. A store that cannot be reached is logged and retried; the node keeps serving with what it has. +/// +public sealed class ClusterSyncService : BackgroundService +{ + internal static readonly JsonSerializerOptions Json = CreateJson(); + + private readonly ClusterRuntime _cluster; + private readonly MaintenanceGate _gate; + private readonly AccessModelVersion _access; + private readonly ReadinessService _readiness; + private readonly ILogger _logger; + private readonly DatabaseCopyService? _copy; + private long _accessSeen = -1; + + /// Creates the service. + public ClusterSyncService( + ClusterRuntime cluster, + MaintenanceGate gate, + AccessModelVersion access, + ReadinessService readiness, + ILogger logger, + DatabaseCopyService? copy = null) + { + _cluster = cluster ?? throw new ArgumentNullException(nameof(cluster)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _readiness = readiness ?? throw new ArgumentNullException(nameof(readiness)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _copy = copy; + } + + /// Starts publishing this node's own gate and access changes at once (not only at the next tick). + public override Task StartAsync(CancellationToken cancellationToken) + { + if (_cluster.IsEnabled) + { + var store = _cluster.Store!; + _gate.Publisher = reason => + { + try + { + if (reason != null) store.Set(ClusterRuntime.Keys.Gate, GateValue(reason), _cluster.LeaseDuration); + else store.Delete(ClusterRuntime.Keys.Gate); + } + catch (Exception e) + { + // The next tick publishes it again. + _logger.LogWarning(e, "Could not publish the read-only gate to the cluster; retried at the next sync."); + } + }; + _access.Publisher = () => + { + try + { + var n = store.Increment(ClusterRuntime.Keys.AccessVersion, TimeSpan.FromDays(30)); + Interlocked.CompareExchange(ref _accessSeen, n, n - 1); + } + catch (Exception e) + { + _logger.LogWarning(e, "Could not tell the cluster the access model changed; the other nodes reload within 30 seconds."); + } + }; + } + + return base.StartAsync(cancellationToken); + } + + /// + public override async Task StopAsync(CancellationToken cancellationToken) + { + await base.StopAsync(cancellationToken).ConfigureAwait(false); + if (!_cluster.IsEnabled) return; + + _gate.Publisher = null; + _access.Publisher = null; + try + { + var store = _cluster.Store!; + await store.DeleteAsync(ClusterRuntime.Keys.Node(_cluster.NodeId), CancellationToken.None).ConfigureAwait(false); + if (_gate.LocalReason != null) await store.DeleteAsync(ClusterRuntime.Keys.Gate, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.LogDebug(e, "Could not remove this node from the cluster listing; it expires by itself."); + } + } + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (!_cluster.IsEnabled) return; + + await Task.Yield(); + while (!stoppingToken.IsCancellationRequested) + { + try + { + await SyncAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception e) + { + _logger.LogWarning(e, "Cluster sync failed; retried in {Interval}.", _cluster.SyncInterval); + } + + try + { + await Task.Delay(_cluster.SyncInterval, stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + } + } + + /// One round: heartbeat, then gate, access model and copy status. Public so a test can force it. + public async Task SyncAsync(CancellationToken cancellationToken) + { + var store = _cluster.Store ?? throw new InvalidOperationException("Not in a cluster."); + + // Each part is independent: a failure in one must not stop the others. + var errors = new List(); + await TryAsync(() => HeartbeatAsync(store, cancellationToken), errors).ConfigureAwait(false); + await TryAsync(() => SyncGateAsync(store, cancellationToken), errors).ConfigureAwait(false); + await TryAsync(() => SyncAccessAsync(store, cancellationToken), errors).ConfigureAwait(false); + await TryAsync(() => SyncCopyAsync(store, cancellationToken), errors).ConfigureAwait(false); + + if (errors.Count > 0) throw errors.Count == 1 ? errors[0] : new AggregateException(errors); + } + + private static async Task TryAsync(Func step, List errors) + { + try + { + await step().ConfigureAwait(false); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception e) + { + errors.Add(e); + } + } + + private async Task HeartbeatAsync(IClusterStore store, CancellationToken cancellationToken) + { + var readiness = _readiness.Last; + if (readiness == null || DateTime.UtcNow - readiness.CheckedAt > ReadinessService.CacheFor) + { + readiness = await _readiness.CheckAsync(force: false, cancellationToken).ConfigureAwait(false); + } + + var info = new NodeInfo( + _cluster.NodeId, + _cluster.Started, + DateTime.UtcNow, + typeof(ClusterSyncService).Assembly.GetName().Version?.ToString() ?? "?", + readiness.IsReady, + readiness.Problem, + _gate.IsClosed); + await store.SetAsync(ClusterRuntime.Keys.Node(_cluster.NodeId), JsonSerializer.Serialize(info, Json), _cluster.HeartbeatTtl, cancellationToken).ConfigureAwait(false); + } + + private async Task SyncGateAsync(IClusterStore store, CancellationToken cancellationToken) + { + var mine = _gate.LocalReason; + if (mine != null) + { + // Keep our closure alive; if its key vanished (expired during a pause) this recreates it. + await store.SetAsync(ClusterRuntime.Keys.Gate, GateValue(mine), _cluster.LeaseDuration, cancellationToken).ConfigureAwait(false); + + return; + } + + var value = await store.GetAsync(ClusterRuntime.Keys.Gate, cancellationToken).ConfigureAwait(false); + if (value == null) + { + _gate.ApplyRemote(null); + + return; + } + + var separator = value.IndexOf('|'); + var owner = separator < 0 ? string.Empty : value.Substring(0, separator); + var reason = separator < 0 ? value : value.Substring(separator + 1); + if (owner == _cluster.NodeId) + { + // A closure this node reopened but could not remove. + await store.DeleteAsync(ClusterRuntime.Keys.Gate, cancellationToken).ConfigureAwait(false); + _gate.ApplyRemote(null); + + return; + } + + _gate.ApplyRemote(reason); + } + + private async Task SyncAccessAsync(IClusterStore store, CancellationToken cancellationToken) + { + // No counter yet (no node has changed the access model) reads as 0. + var value = await store.GetAsync(ClusterRuntime.Keys.AccessVersion, cancellationToken).ConfigureAwait(false); + var seen = 0L; + if (value != null && !long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out seen)) return; + + var previous = Interlocked.Exchange(ref _accessSeen, seen); + // The first read only learns where the counter is. + if (previous != -1 && previous != seen) _access.BumpFromCluster(); + } + + private async Task SyncCopyAsync(IClusterStore store, CancellationToken cancellationToken) + { + if (_copy == null) return; + + var local = _copy.LocalStatus; + if (local != DatabaseCopyStatus.Idle) + { + await store.SetAsync(ClusterRuntime.Keys.CopyStatus, JsonSerializer.Serialize(local, Json), TimeSpan.FromHours(1), cancellationToken).ConfigureAwait(false); + _copy.RemoteStatus = null; + + return; + } + + var value = await store.GetAsync(ClusterRuntime.Keys.CopyStatus, cancellationToken).ConfigureAwait(false); + _copy.RemoteStatus = value == null ? null : JsonSerializer.Deserialize(value, Json); + } + + private string GateValue(string reason) => _cluster.NodeId + "|" + reason; + + private static JsonSerializerOptions CreateJson() + { + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); + options.Converters.Add(new JsonStringEnumConverter()); + + return options; + } +} + +/// What the cluster page shows. +/// Whether this node is in a cluster. +/// This node's name. +/// The store, without credentials. +/// Whether the store answered. +/// The nodes with a recent heartbeat, this one included. +/// The job leases held now. +/// Why the cluster is read-only, or null. +/// This node's readiness check. +public sealed record ClusterStatus( + bool Enabled, + string ThisNode, + string? Backend, + bool BackendReachable, + IReadOnlyList Nodes, + IReadOnlyList Leases, + string? GateReason, + ReadinessReport Readiness); + +/// Reads the cluster's shared state for the administrator's page. +public interface IClusterStatusService +{ + /// The current status (cheap on a single node, which lists only itself). + Task GetAsync(CancellationToken cancellationToken); +} + +/// The default . +public sealed class ClusterStatusService : IClusterStatusService +{ + private readonly ClusterRuntime _cluster; + private readonly ReadinessService _readiness; + private readonly MaintenanceGate _gate; + + /// Creates the service. + public ClusterStatusService(ClusterRuntime cluster, ReadinessService readiness, MaintenanceGate gate) + { + _cluster = cluster ?? throw new ArgumentNullException(nameof(cluster)); + _readiness = readiness ?? throw new ArgumentNullException(nameof(readiness)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + } + + /// + public async Task GetAsync(CancellationToken cancellationToken) + { + var readiness = await _readiness.CheckAsync(force: false, cancellationToken).ConfigureAwait(false); + var store = _cluster.Store; + if (store == null) + { + var self = new NodeInfo(_cluster.NodeId, _cluster.Started, DateTime.UtcNow, typeof(ClusterStatusService).Assembly.GetName().Version?.ToString() ?? "?", readiness.IsReady, readiness.Problem, _gate.IsClosed); + + return new ClusterStatus(false, _cluster.NodeId, null, false, new[] { self }, Array.Empty(), _gate.Reason, readiness); + } + + var reachable = false; + var nodes = new List(); + var leases = new List(); + string? gate = _gate.Reason; + try + { + reachable = await store.PingAsync(cancellationToken).ConfigureAwait(false); + foreach (var (_, value) in await store.ListAsync(ClusterRuntime.Keys.NodePrefix, cancellationToken).ConfigureAwait(false)) + { + var node = JsonSerializer.Deserialize(value, ClusterSyncService.Json); + if (node != null) nodes.Add(node); + } + + foreach (var (key, value) in await store.ListAsync(ClusterRuntime.Keys.LeasePrefix, cancellationToken).ConfigureAwait(false)) + { + var lease = LeaseInfo.Parse(key.Substring(ClusterRuntime.Keys.LeasePrefix.Length), value); + if (lease != null) leases.Add(lease); + } + } + catch (Exception e) when (e is not OperationCanceledException) + { + reachable = false; + } + + return new ClusterStatus( + true, + _cluster.NodeId, + store.Description, + reachable, + nodes.OrderBy(n => n.Id, StringComparer.Ordinal).ToList(), + leases.OrderBy(l => l.Job, StringComparer.Ordinal).ToList(), + gate, + readiness); + } +} diff --git a/src/BaGet.Core/Ha/DataProtectionKeyEntry.cs b/src/BaGet.Core/Ha/DataProtectionKeyEntry.cs new file mode 100644 index 000000000..e0ffdcd60 --- /dev/null +++ b/src/BaGet.Core/Ha/DataProtectionKeyEntry.cs @@ -0,0 +1,22 @@ +namespace BaGet.Core; + +/// +/// One key of the ASP.NET Core data protection key ring, kept in the database in cluster mode (Ha:Enabled) so every node +/// signs and reads the same cookies, antiforgery tokens, API-key-free tokens and protected remote credentials. The XML is what the +/// key manager wrote (the key material is encrypted by its own key-encryption setting, or stored as is when none is configured: protect the database). +/// Without HA the host's own key ring (a folder) is used and this table stays empty. +/// +public class DataProtectionKeyEntry +{ + /// The longest friendly name stored. + public const int MaxNameLength = 200; + + /// The row's id. + public int Key { get; set; } + + /// The key manager's name for the element (key-{guid}). + public string? FriendlyName { get; set; } + + /// The key's XML element. + public string? Xml { get; set; } +} diff --git a/src/BaGet.Core/Ha/HaOptions.cs b/src/BaGet.Core/Ha/HaOptions.cs new file mode 100644 index 000000000..d7d1b5c53 --- /dev/null +++ b/src/BaGet.Core/Ha/HaOptions.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// High availability (Ha:*): several BaGet nodes behind a load balancer sharing one database, one object store and one +/// Redis. Off by default; a single node then behaves as always and needs no Redis. Everything here is read when the host starts +/// (registration decides from Ha:Enabled), so every setting needs a restart. See docs/high-availability.md. +/// +[RestartRequired] +public class HaOptions +{ + /// + /// Turns cluster mode on. The node then refuses to start unless the database is shared (not SQLite or Azure Table), the storage is + /// shared (not the file system) and is set. + /// + public bool Enabled { get; set; } + + /// The shared backend: only Redis today. + [AllowedSettingValues("Redis")] + public string Backend { get; set; } = "Redis"; + + /// The Redis connection string (host:6379,password=...,ssl=true). Never shown or logged. + [SensitiveSetting] + [SettingExample(nameof(Backend), "Redis", "redis.example.com:6379,password=,ssl=true")] + public string? ConnectionString { get; set; } + + /// The name this node shows on the cluster page. Default: the machine name plus a random suffix, new at every start. + public string? NodeName { get; set; } + + /// A prefix for every key BaGet writes, so several clusters can share one Redis. Default baget. + public string KeyPrefix { get; set; } = "baget"; + + /// + /// Path of a PFX certificate (with private key) that encrypts the data protection key ring stored in the database. Every node needs + /// the same certificate. Without it the keys that protect remote-repository passwords and replication peer keys are plain XML in the + /// same database as those secrets, so set it (the node logs a warning at start otherwise). + /// + public string? KeyCertificatePath { get; set; } + + /// The password of the PFX at , if it has one. + [SensitiveSetting] + public string? KeyCertificatePassword { get; set; } + + /// + /// How long a job lease or the read-only gate of a node that stopped answering stays held. The holder renews it every third of + /// this, so a crashed node frees its jobs within this time. Default 30 seconds, at least 3. + /// + public TimeSpan LeaseDuration { get; set; } = TimeSpan.FromSeconds(30); + + /// + /// How often a node publishes its heartbeat and picks up what the others changed (read-only gate, access model, database copy + /// status). Default 2 seconds, at least 100 ms. + /// + public TimeSpan SyncInterval { get; set; } = TimeSpan.FromSeconds(2); + + /// What is wrong with these options, one message per problem (empty when valid or when HA is off). + public IReadOnlyList Validate() + { + var failures = new List(); + if (!Enabled) return failures; + + if (!string.Equals(Backend, "Redis", StringComparison.OrdinalIgnoreCase)) + { + failures.Add("The 'Ha:Backend' config is invalid. Allowed values: Redis"); + } + + if (LeaseDuration < TimeSpan.FromSeconds(3)) + { + failures.Add("The 'Ha:LeaseDuration' config must be at least 3 seconds."); + } + + if (SyncInterval < TimeSpan.FromMilliseconds(100)) + { + failures.Add("The 'Ha:SyncInterval' config must be at least 100 milliseconds."); + } + + if (string.IsNullOrWhiteSpace(KeyPrefix)) + { + failures.Add("The 'Ha:KeyPrefix' config must not be empty."); + } + + return failures; + } +} diff --git a/src/BaGet.Core/Ha/HaStartupGuard.cs b/src/BaGet.Core/Ha/HaStartupGuard.cs new file mode 100644 index 000000000..39c397b89 --- /dev/null +++ b/src/BaGet.Core/Ha/HaStartupGuard.cs @@ -0,0 +1,59 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// Refuses to start a node whose Ha:Enabled setting cannot work: a database or storage that is local to one machine, or no +/// Redis connection string (). A cluster of nodes that each write their own SQLite file would silently +/// diverge, so the start fails with the reasons instead. +/// +public sealed class HaStartupGuard : IHostedService +{ + private readonly IOptions _ha; + private readonly IOptions _database; + private readonly IOptions _storage; + private readonly HaBackendRules _rules; + private readonly ILogger _logger; + + /// Creates the guard. + public HaStartupGuard( + IOptions ha, + IOptions database, + IOptions storage, + HaBackendRules rules, + ILogger logger) + { + _ha = ha ?? throw new ArgumentNullException(nameof(ha)); + _database = database ?? throw new ArgumentNullException(nameof(database)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _rules = rules ?? throw new ArgumentNullException(nameof(rules)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + public Task StartAsync(CancellationToken cancellationToken) + { + var problems = _rules.Check(_ha.Value, _database.Value, _storage.Value); + if (problems.Count == 0) + { + if (_ha.Value.Enabled && string.IsNullOrWhiteSpace(_ha.Value.KeyCertificatePath)) + { + _logger.LogWarning("High availability: the data protection keys are stored unencrypted in the database, next to the passwords and peer keys they protect. Set Ha:KeyCertificatePath (a PFX every node holds)."); + } + + return Task.CompletedTask; + } + + foreach (var problem in problems) _logger.LogCritical("High availability: {Problem}", problem); + + throw new InvalidOperationException("Ha:Enabled cannot start: " + string.Join(" ", problems)); + } + + /// + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/src/BaGet.Core/Ha/IClusterStore.cs b/src/BaGet.Core/Ha/IClusterStore.cs new file mode 100644 index 000000000..668ac0c2b --- /dev/null +++ b/src/BaGet.Core/Ha/IClusterStore.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// The small shared key/value store a cluster of nodes coordinates through (Redis in production, +/// in tests). Values are short strings with an optional time to live. Registered only when Ha:Enabled is set. +/// +public interface IClusterStore +{ + /// Where it is, without credentials (shown on the cluster page). + string Description { get; } + + /// Whether the store answers. + Task PingAsync(CancellationToken cancellationToken); + + /// The value, or null when absent or expired. + Task GetAsync(string key, CancellationToken cancellationToken); + + /// Sets the value, replacing any; null keeps it until deleted. + Task SetAsync(string key, string value, TimeSpan? ttl, CancellationToken cancellationToken); + + /// Sets the value only when the key is absent (atomic). False when it exists. + Task SetIfAbsentAsync(string key, string value, TimeSpan ttl, CancellationToken cancellationToken); + + /// Deletes the key. False when it did not exist. + Task DeleteAsync(string key, CancellationToken cancellationToken); + + /// Restarts the time to live of the key when it still holds (atomic). False otherwise. + Task ExtendIfValueAsync(string key, string value, TimeSpan ttl, CancellationToken cancellationToken); + + /// Deletes the key when it still holds (atomic). False otherwise. + Task DeleteIfValueAsync(string key, string value, CancellationToken cancellationToken); + + /// Adds one to the counter (created as 1 with , which later increments do not change) and returns it. + Task IncrementAsync(string key, TimeSpan ttlOnCreate, CancellationToken cancellationToken); + + /// The live keys that start with and their values. + Task> ListAsync(string prefix, CancellationToken cancellationToken); +} + +/// Blocking forms for the few synchronous callers (the rate limiters, the read-only gate); the calls are single round trips. +internal static class ClusterStoreExtensions +{ + public static bool SetIfAbsent(this IClusterStore store, string key, string value, TimeSpan ttl) + => store.SetIfAbsentAsync(key, value, ttl, CancellationToken.None).GetAwaiter().GetResult(); + + public static void Set(this IClusterStore store, string key, string value, TimeSpan? ttl) + => store.SetAsync(key, value, ttl, CancellationToken.None).GetAwaiter().GetResult(); + + public static void Delete(this IClusterStore store, string key) + => store.DeleteAsync(key, CancellationToken.None).GetAwaiter().GetResult(); + + public static long Increment(this IClusterStore store, string key, TimeSpan ttlOnCreate) + => store.IncrementAsync(key, ttlOnCreate, CancellationToken.None).GetAwaiter().GetResult(); +} diff --git a/src/BaGet.Core/Ha/IJobLeaseAvailability.cs b/src/BaGet.Core/Ha/IJobLeaseAvailability.cs new file mode 100644 index 000000000..4f1332940 --- /dev/null +++ b/src/BaGet.Core/Ha/IJobLeaseAvailability.cs @@ -0,0 +1,14 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Optional capability of an : tells "another holder has it" from "the lease backend cannot be reached", +/// both of which make answer null. +/// +public interface IJobLeaseAvailability +{ + /// True when the backend answers, so a refused lease means another holder. + Task IsAvailableAsync(CancellationToken cancellationToken); +} diff --git a/src/BaGet.Core/Ha/InMemoryClusterStore.cs b/src/BaGet.Core/Ha/InMemoryClusterStore.cs new file mode 100644 index 000000000..d85d5c6f7 --- /dev/null +++ b/src/BaGet.Core/Ha/InMemoryClusterStore.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// An in this process's memory. Several hosts in one process can share one instance, which is how the +/// tests run a cluster without Redis; it is not a production backend (nothing outside the process sees it). +/// +public sealed class InMemoryClusterStore : IClusterStore +{ + private readonly object _lock = new(); + private readonly Dictionary _items = new(StringComparer.Ordinal); + private readonly Func _clock; + + /// Creates a store. + /// UTC now; real time by default (tests pass a fake to expire entries). + public InMemoryClusterStore(Func? clock = null) => _clock = clock ?? (() => DateTime.UtcNow); + + /// Set to make every call fail, to test a node that loses the backend. + public bool Unavailable { get; set; } + + /// + public string Description => "in-memory (single process)"; + + /// + public Task PingAsync(CancellationToken cancellationToken) => Task.FromResult(!Unavailable); + + /// + public Task GetAsync(string key, CancellationToken cancellationToken) + { + lock (_lock) return Task.FromResult(Live(key)); + } + + /// + public Task SetAsync(string key, string value, TimeSpan? ttl, CancellationToken cancellationToken) + { + lock (_lock) + { + Check(); + _items[key] = (value, ttl == null ? null : _clock() + ttl.Value); + } + + return Task.CompletedTask; + } + + /// + public Task SetIfAbsentAsync(string key, string value, TimeSpan ttl, CancellationToken cancellationToken) + { + lock (_lock) + { + if (Live(key) != null) return Task.FromResult(false); + _items[key] = (value, _clock() + ttl); + + return Task.FromResult(true); + } + } + + /// + public Task DeleteAsync(string key, CancellationToken cancellationToken) + { + lock (_lock) + { + var existed = Live(key) != null; + _items.Remove(key); + + return Task.FromResult(existed); + } + } + + /// + public Task ExtendIfValueAsync(string key, string value, TimeSpan ttl, CancellationToken cancellationToken) + { + lock (_lock) + { + if (Live(key) != value) return Task.FromResult(false); + _items[key] = (value, _clock() + ttl); + + return Task.FromResult(true); + } + } + + /// + public Task DeleteIfValueAsync(string key, string value, CancellationToken cancellationToken) + { + lock (_lock) + { + if (Live(key) != value) return Task.FromResult(false); + _items.Remove(key); + + return Task.FromResult(true); + } + } + + /// + public Task IncrementAsync(string key, TimeSpan ttlOnCreate, CancellationToken cancellationToken) + { + lock (_lock) + { + var current = Live(key); + if (current == null) + { + _items[key] = ("1", _clock() + ttlOnCreate); + + return Task.FromResult(1L); + } + + var next = long.Parse(current, CultureInfo.InvariantCulture) + 1; + _items[key] = (next.ToString(CultureInfo.InvariantCulture), _items[key].Expires); + + return Task.FromResult(next); + } + } + + /// + public Task> ListAsync(string prefix, CancellationToken cancellationToken) + { + lock (_lock) + { + Check(); + var now = _clock(); + var live = _items + .Where(p => p.Key.StartsWith(prefix, StringComparison.Ordinal) && (p.Value.Expires == null || p.Value.Expires > now)) + .ToDictionary(p => p.Key, p => p.Value.Value, StringComparer.Ordinal); + + return Task.FromResult>(live); + } + } + + private string? Live(string key) + { + Check(); + if (!_items.TryGetValue(key, out var item)) return null; + if (item.Expires != null && item.Expires <= _clock()) + { + _items.Remove(key); + + return null; + } + + return item.Value; + } + + private void Check() + { + if (Unavailable) throw new InvalidOperationException("The cluster store is unavailable."); + } +} diff --git a/src/BaGet.Core/Ha/JobLeaseExtensions.cs b/src/BaGet.Core/Ha/JobLeaseExtensions.cs new file mode 100644 index 000000000..834d7f809 --- /dev/null +++ b/src/BaGet.Core/Ha/JobLeaseExtensions.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// How the background workers use . A worker built without a lease (a test, an embedded host) runs +/// everything, as a single node does; with one it runs only what it holds the lease for, so a job runs once cluster-wide. +/// +public static class JobLeaseExtensions +{ + private static readonly IAsyncDisposable Nothing = new NoLease(); + + /// + /// Takes the lease for , or returns a no-op handle when there is no lease service. + /// + /// A handle to dispose when the job ends, or null when another holder has the lease (skip the job). + public static async ValueTask AcquireAsync(this IJobLease? lease, string job, CancellationToken cancellationToken) + => lease == null ? Nothing : await lease.TryAcquireAsync(job, cancellationToken).ConfigureAwait(false); + + /// Blocking form for the synchronous TryStart methods (one store round trip). + public static IAsyncDisposable? Acquire(this IJobLease? lease, string job) + => lease == null ? Nothing : lease.TryAcquireAsync(job, CancellationToken.None).AsTask().GetAwaiter().GetResult(); + + /// Releases a handle from synchronously. + public static void Release(this IAsyncDisposable handle) => handle.DisposeAsync().AsTask().GetAwaiter().GetResult(); + + private sealed class NoLease : IAsyncDisposable + { + public ValueTask DisposeAsync() => default; + } +} diff --git a/src/BaGet.Core/Ha/ReadinessService.cs b/src/BaGet.Core/Ha/ReadinessService.cs new file mode 100644 index 000000000..17ef795ac --- /dev/null +++ b/src/BaGet.Core/Ha/ReadinessService.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// One probe of the readiness check. +/// database, storage or cluster. +/// Whether it answered. +/// A short, credential-free note (the exception type when it failed). +/// The probe is reported but a failure does not make the node unready (the shared store: a node keeps serving without it). +public sealed record HealthProbe(string Name, bool Healthy, string? Detail, bool Informational = false); + +/// The result of the readiness check. +/// When it ran (UTC). +/// Each probe. +public sealed record ReadinessReport(DateTime CheckedAt, IReadOnlyList Probes) +{ + /// Every probe that decides readiness answered (an informational probe, the shared store, never takes the node out of rotation). + public bool IsReady => Probes.All(p => p.Healthy || p.Informational); + + /// The failing probes (informational ones too) as one line, or null. + public string? Problem + { + get + { + var failing = Probes.Where(p => !p.Healthy).Select(p => p.Name + (p.Detail == null ? "" : " (" + p.Detail + ")")).ToList(); + + return failing.Count == 0 ? null : string.Join(", ", failing); + } + } +} + +/// +/// What /health/ready and the cluster page report: whether this node can serve. It reaches the database (a connection), the +/// storage (writes and deletes a one-byte probe object) and, in a cluster, the shared store, which is only reported +/// (): a node keeps serving without Redis, so a Redis outage must not take every node out of rotation at once. The answer is kept for +/// , so a load balancer polling every second costs one check per interval. Readiness never depends on the +/// read-only gate (a node refusing writes still serves reads). +/// +public sealed class ReadinessService +{ + /// How long an answer is reused. + public static readonly TimeSpan CacheFor = TimeSpan.FromSeconds(5); + + private readonly IServiceScopeFactory _scopes; + private readonly ClusterRuntime _cluster; + private readonly ILogger _logger; + private readonly SemaphoreSlim _lock = new(1, 1); + private ReadinessReport? _last; + + /// Creates the service. + public ReadinessService(IServiceScopeFactory scopes, ClusterRuntime cluster, ILogger logger) + { + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _cluster = cluster ?? throw new ArgumentNullException(nameof(cluster)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// The last answer, without running a check (null before the first). + public ReadinessReport? Last => _last; + + /// Runs the probes unless a recent answer exists. + /// Run them even if the last answer is recent. + /// Cancels the check. + public async Task CheckAsync(bool force, CancellationToken cancellationToken) + { + var last = _last; + if (!force && last != null && DateTime.UtcNow - last.CheckedAt < CacheFor) return last; + + await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + last = _last; + if (!force && last != null && DateTime.UtcNow - last.CheckedAt < CacheFor) return last; + + var probes = new List + { + await ProbeAsync("database", DatabaseAsync, cancellationToken).ConfigureAwait(false), + await ProbeAsync("storage", StorageAsync, cancellationToken).ConfigureAwait(false), + }; + if (_cluster.IsEnabled) probes.Add(await ProbeAsync("cluster", ClusterAsync, cancellationToken, informational: true).ConfigureAwait(false)); + + return _last = new ReadinessReport(DateTime.UtcNow, probes); + } + finally + { + _lock.Release(); + } + } + + private async Task ProbeAsync(string name, Func> probe, CancellationToken cancellationToken, bool informational = false) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + try + { + return new HealthProbe(name, true, await probe(timeout.Token).ConfigureAwait(false), informational); + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // The type only: a message can carry a connection string. + _logger.LogWarning("Readiness probe {Probe} failed: {Error}", name, e.GetType().Name); + + return new HealthProbe(name, false, e is OperationCanceledException ? "timeout" : e.GetType().Name, informational); + } + } + + private async Task DatabaseAsync(CancellationToken cancellationToken) + { + using var scope = _scopes.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); + if (context is NullContext) return "not checked (Azure Table)"; + if (!await context.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false)) throw new InvalidOperationException("cannot connect"); + + return null; + } + + private async Task StorageAsync(CancellationToken cancellationToken) + { + using var scope = _scopes.CreateScope(); + var storage = scope.ServiceProvider.GetRequiredService(); + var path = "health/" + _cluster.NodeId.Replace('|', '_') + ".probe"; + using (var content = new MemoryStream(Encoding.ASCII.GetBytes("ok"))) + { + await storage.PutAsync(path, content, "text/plain", cancellationToken).ConfigureAwait(false); + } + + await storage.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + + return null; + } + + private async Task ClusterAsync(CancellationToken cancellationToken) + { + if (!await _cluster.Store!.PingAsync(cancellationToken).ConfigureAwait(false)) throw new InvalidOperationException("no answer"); + + return _cluster.Store.Description; + } +} diff --git a/src/BaGet.Core/IPackageDatabase.cs b/src/BaGet.Core/IPackageDatabase.cs index 38ec29663..60b392bdf 100644 --- a/src/BaGet.Core/IPackageDatabase.cs +++ b/src/BaGet.Core/IPackageDatabase.cs @@ -1,115 +1,167 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The "source of truth" for packages' state. Packages' content +/// are stored by the . +/// +public interface IPackageDatabase { /// - /// The "source of truth" for packages' state. Packages' content - /// are stored by the . + /// Attempt to add a new package to the database. /// - public interface IPackageDatabase - { - /// - /// Attempt to add a new package to the database. - /// - /// The package to add to the database. - /// A token to cancel the task. - /// The result of attempting to add the package to the database. - Task AddAsync(Package package, CancellationToken cancellationToken); - - /// - /// Attempt to find a package with the given id and version. - /// - /// The package's id. - /// The package's version. - /// Whether unlisted results should be included. - /// A token to cancel the task. - /// The package found, or null. - Task FindOrNullAsync( - string id, - NuGetVersion version, - bool includeUnlisted, - CancellationToken cancellationToken); - - /// - /// Attempt to find all packages with a given id. - /// - /// The packages' id. - /// Whether unlisted results should be included. - /// A token to cancel the task. - /// The packages found. Always non-null. - Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken); - - /// - /// Determine whether a package exists in the database (even if the package is unlisted). - /// - /// The package id to search. - /// A token to cancel the task. - /// Whether the package exists in the database. - Task ExistsAsync(string id, CancellationToken cancellationToken); - - /// - /// Determine whether a package exists in the database (even if the package is unlisted). - /// - /// The package id to search. - /// The package version to search. - /// A token to cancel the task. - /// Whether the package exists in the database. - Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Unlist a package, making it undiscoverable. - /// - /// The id of the package to unlist. - /// The version of the package to unlist. - /// A token to cancel the task. - /// False if the package does not exist. - Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Relist a package, making it discoverable. - /// - /// The id of the package to relist. - /// The version of the package to relist. - /// A token to cancel the task. - /// False if the package does not exist. - Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Increment a package's download count. - /// - /// The id of the package to update. - /// The id of the package to update. - /// A token to cancel the task. - /// Task that completes when the package's download has been incremented. - Task AddDownloadAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Completely remove the package from the database. - /// - /// The id of the package to remove. - /// The version of the pacakge to remove. - /// A token to cancel the task. - /// False if the package doesn't exist. - Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } + /// The package to add to the database. + /// A token to cancel the task. + /// The result of attempting to add the package to the database. + Task AddAsync(Package package, CancellationToken cancellationToken); + + /// + /// Attempt to find a package with the given id and version. + /// + /// The package's id. + /// The package's version. + /// Whether unlisted results should be included. + /// A token to cancel the task. + /// The package found, or null. + Task FindOrNullAsync( + string? id, + NuGetVersion version, + bool includeUnlisted, + CancellationToken cancellationToken); /// - /// The result of attempting to add the package to the database. - /// See + /// Attempt to find all packages with a given id. /// - public enum PackageAddResult + /// The packages' id. + /// Whether unlisted results should be included. + /// A token to cancel the task. + /// The packages found. Always non-null. + Task> FindAsync(string? id, bool includeUnlisted, CancellationToken cancellationToken); + + /// + /// Attempt to find all packages with any of the given ids, in one round trip where the implementation can. + /// + /// The packages' ids. + /// Whether unlisted results should be included. + /// A token to cancel the task. + /// The packages found, of all the ids. Always non-null. + /// The default asks per id. + async Task> FindManyAsync( + IReadOnlyCollection ids, + bool includeUnlisted, + CancellationToken cancellationToken) { - /// - /// Failed to add the package as it already exists. - /// - PackageAlreadyExists, - - /// - /// The package was added successfully. - /// - Success + var result = new List(); + foreach (var id in ids) + { + result.AddRange(await FindAsync(id, includeUnlisted, cancellationToken)); + } + + return result; } + + /// + /// Determine whether a package exists in the database (even if the package is unlisted). + /// + /// The package id to search. + /// A token to cancel the task. + /// Whether the package exists in the database. + Task ExistsAsync(string? id, CancellationToken cancellationToken); + + /// + /// Determine whether a package exists in the database (even if the package is unlisted). + /// + /// The package id to search. + /// The package version to search. + /// A token to cancel the task. + /// Whether the package exists in the database. + Task ExistsAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Unlist a package, making it undiscoverable. + /// + /// The id of the package to unlist. + /// The version of the package to unlist. + /// A token to cancel the task. + /// False if the package does not exist. + Task UnlistPackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Relist a package, making it discoverable. + /// + /// The id of the package to relist. + /// The version of the package to relist. + /// A token to cancel the task. + /// False if the package does not exist. + Task RelistPackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Increment a package's download count. + /// + /// The id of the package to update. + /// The id of the package to update. + /// A token to cancel the task. + /// Task that completes when the package's download has been incremented. + Task AddDownloadAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Completely remove the package from the database. + /// + /// The id of the package to remove. + /// The version of the pacakge to remove. + /// A token to cancel the task. + /// False if the package doesn't exist. + Task HardDeletePackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Mark a package version as deprecated, replacing any earlier deprecation. + /// + /// False if the package version does not exist. + Task SetDeprecationAsync( + string? id, + NuGetVersion version, + PackageDeprecation deprecation, + CancellationToken cancellationToken); + + /// + /// Remove a package version's deprecation, if it has one. + /// + /// False if the package version does not exist. + Task RemoveDeprecationAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Replace the known vulnerabilities of a package version. An empty list clears them. + /// + /// False if the package version does not exist. + Task SetVulnerabilitiesAsync( + string id, + NuGetVersion version, + IReadOnlyList vulnerabilities, + CancellationToken cancellationToken); + + /// + /// Every known vulnerability, with the package version it affects. + /// + Task> GetAllVulnerabilitiesAsync(CancellationToken cancellationToken); } + +/// +/// The result of attempting to add the package to the database. +/// See +/// +public enum PackageAddResult +{ + /// + /// Failed to add the package as it already exists. + /// + PackageAlreadyExists, + + /// + /// The package was added successfully. + /// + Success +} \ No newline at end of file diff --git a/src/BaGet.Core/IPackageService.cs b/src/BaGet.Core/IPackageService.cs index 768813d23..677b8b832 100644 --- a/src/BaGet.Core/IPackageService.cs +++ b/src/BaGet.Core/IPackageService.cs @@ -1,70 +1,85 @@ using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The service that combines the state of indexed packages and +/// upstream packages. +/// For upstream packages, see . +/// For indexed packages, see . +/// +public interface IPackageService { /// - /// The service that combines the state of indexed packages and - /// upstream packages. - /// For upstream packages, see . - /// For indexed packages, see . + /// Attempt to find a package's versions using mirroring. This will merge + /// results from the configured upstream source with the locally indexed packages. + /// + /// The package's id to lookup + /// The token to cancel the lookup + /// + /// The package's versions, or an empty list if the package cannot be found. + /// This includes unlisted versions. + /// + Task> FindPackageVersionsAsync(string id, CancellationToken cancellationToken); + + /// + /// Attempt to find a package's metadata using mirroring. This will merge + /// results from the configured upstream source with the locally indexed packages. /// - public interface IPackageService - { - /// - /// Attempt to find a package's versions using mirroring. This will merge - /// results from the configured upstream source with the locally indexed packages. - /// - /// The package's id to lookup - /// The token to cancel the lookup - /// - /// The package's versions, or an empty list if the package cannot be found. - /// This includes unlisted versions. - /// - Task> FindPackageVersionsAsync(string id, CancellationToken cancellationToken); + /// The package's id to lookup + /// The token to cancel the lookup + /// + /// The metadata for all versions of a package, including unlisted versions. + /// Returns an empty list if the package cannot be found. + /// + Task> FindPackagesAsync(string id, CancellationToken cancellationToken); - /// - /// Attempt to find a package's metadata using mirroring. This will merge - /// results from the configured upstream source with the locally indexed packages. - /// - /// The package's id to lookup - /// The token to cancel the lookup - /// - /// The metadata for all versions of a package, including unlisted versions. - /// Returns an empty list if the package cannot be found. - /// - Task> FindPackagesAsync(string id, CancellationToken cancellationToken); + /// + /// Attempt to find a package's metadata using mirroring. This will merge + /// results from the configured upstream source with the locally indexed packages. + /// + /// The package's id to lookup + /// The package's version to lookup + /// The token to cancel the lookup + /// + /// The metadata for single version of a package. + /// Returns null if the package does not exist. + /// + Task FindPackageOrNullAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Attempt to find a package's metadata using mirroring. This will merge - /// results from the configured upstream source with the locally indexed packages. - /// - /// The package's id to lookup - /// The package's version to lookup - /// The token to cancel the lookup - /// - /// The metadata for single version of a package. - /// Returns null if the package does not exist. - /// - Task FindPackageOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Determine whether a package exists locally or on the upstream source. + /// + /// The package id to search. + /// The package version to search. + /// A token to cancel the task. + /// Whether the package exists in the database. + Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Determine whether a package exists locally or on the upstream source. - /// - /// The package id to search. - /// The package version to search. - /// A token to cancel the task. - /// Whether the package exists in the database. - Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Increment a package's download count. + /// + /// The id of the package to update. + /// The id of the package to update. + /// A token to cancel the task. + Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Increment a package's download count. - /// - /// The id of the package to update. - /// The id of the package to update. - /// A token to cancel the task. - Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken); - } -} + /// + /// For a remote repository that does not store what it fetches + /// ( off): downloads the package from the upstream and returns + /// it, without indexing or storing it. + /// + /// The package id. + /// The package version. + /// A token to cancel the task. + /// + /// A seekable stream, or null when the repository stores locally (use the stored package), the package is stored + /// already, or the upstream does not have it. + /// + Task OpenUncachedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + => Task.FromResult(null); +} \ No newline at end of file diff --git a/src/BaGet.Core/IUrlGenerator.cs b/src/BaGet.Core/IUrlGenerator.cs index 443dba796..bbbb66582 100644 --- a/src/BaGet.Core/IUrlGenerator.cs +++ b/src/BaGet.Core/IUrlGenerator.cs @@ -1,105 +1,196 @@ -using NuGet.Versioning; +using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Used to create URLs to resources in the NuGet protocol. +/// +public interface IUrlGenerator { /// - /// Used to create URLs to resources in the NuGet protocol. - /// - public interface IUrlGenerator - { - /// - /// Get the URL for the package source (also known as the "service index"). - /// See: https://docs.microsoft.com/en-us/nuget/api/service-index - /// - string GetServiceIndexUrl(); - - /// - /// Get the URL for the root of the package content resource. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource - /// - string GetPackageContentResourceUrl(); - - /// - /// Get the URL for the root of the package metadata resource. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource - /// - string GetPackageMetadataResourceUrl(); - - /// - /// Get the URL to publish packages. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource - /// - string GetPackagePublishResourceUrl(); - - /// - /// Get the URL to publish symbol packages. - /// See: https://docs.microsoft.com/en-us/nuget/api/symbol-package-publish-resource - /// - string GetSymbolPublishResourceUrl(); - - /// - /// Get the URL to search for packages. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource - /// - string GetSearchResourceUrl(); - - /// - /// Get the URL to autocomplete package IDs. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource - /// - string GetAutocompleteResourceUrl(); - - /// - /// Get the URL for the entry point of a package's metadata. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index - /// - /// The package's ID. - string GetRegistrationIndexUrl(string id); - - /// - /// Get the URL for the metadata of several versions of a single package. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The package's ID - /// The lowest SemVer 2.0.0 version in the page (inclusive) - /// The highest SemVer 2.0.0 version in the page (inclusive) - string GetRegistrationPageUrl(string id, NuGetVersion lower, NuGetVersion upper); - - /// - /// Get the URL for the metadata of a specific package ID and version. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf - /// - /// The package's ID - /// The package's version - string GetRegistrationLeafUrl(string id, NuGetVersion version); - - /// - /// Get the URL that lists a package's versions. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions - /// - /// The package's ID - string GetPackageVersionsUrl(string id); - - /// - /// Get the URL to download a package (.nupkg). - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg - /// - /// The package's ID - /// The package's version - string GetPackageDownloadUrl(string id, NuGetVersion version); - - /// - /// Get the URL to download a package's manifest (.nuspec). - /// - /// The package's ID - /// The package's version - string GetPackageManifestDownloadUrl(string id, NuGetVersion version); - - /// - /// Get the URL to download a package icon. - /// - /// The package's ID - /// The package's version - string GetPackageIconDownloadUrl(string id, NuGetVersion version); - } -} + /// Get the URL for the package source (also known as the "service index"). + /// See: https://docs.microsoft.com/en-us/nuget/api/service-index + /// + string? GetServiceIndexUrl(); + + /// + /// Get the URL for the root of the package content resource. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// + string GetPackageContentResourceUrl(); + + /// + /// Get the URL for the root of the package metadata resource. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// + string GetPackageMetadataResourceUrl(); + + /// + /// Get the URL to publish packages. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource + /// + string? GetPackagePublishResourceUrl(); + + /// + /// Get the URL to publish symbol packages. + /// See: https://docs.microsoft.com/en-us/nuget/api/symbol-package-publish-resource + /// + string? GetSymbolPublishResourceUrl(); + + /// + /// Get the URL to search for packages. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// + string? GetSearchResourceUrl(); + + /// + /// Get the URL to autocomplete package IDs. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// + string? GetAutocompleteResourceUrl(); + + /// + /// Get the URL of the V2 (OData) feed, for clients that cannot use V3. + /// + string? GetV2FeedUrl(); + + /// + /// Get the URI template a client expands to reach a package's details page. + /// The literal "{id}" and "{version}" placeholders are part of the value. + /// See: https://learn.microsoft.com/en-us/nuget/api/service-index#resources + /// + /// + /// The template, in the current repository (/r/{name}/packages/… for a non-default one, as the pages exist + /// under every repository). Null is reserved for a generator whose host has no package pages, in which case the + /// service index leaves the resource out. + /// + string? GetPackageDetailsUriTemplate(); + + /// + /// Get the URI template a client expands to report a package as abusive. + /// The literal "{id}" and "{version}" placeholders are part of the value. + /// See: https://learn.microsoft.com/en-us/nuget/api/service-index#resources + /// + /// The template, or null when the host has no such page; see . + string? GetReportAbuseUriTemplate(); + + /// + /// Get the URL of the vulnerability index, which lists the vulnerability pages. + /// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info + /// + string GetVulnerabilityIndexUrl(); + + /// + /// Get the URL of one page of vulnerability data. + /// + /// The page's name, such as "base". + string GetVulnerabilityPageUrl(string pageName); + + /// + /// Get the URL of the catalog index. + /// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource + /// + string GetCatalogIndexUrl(); + + /// + /// Get the URL of one catalog page. + /// + /// The page's zero based index. + string GetCatalogPageUrl(int pageIndex); + + /// + /// Get the URL of one catalog leaf. + /// + /// The ID of the commit that wrote the leaf. + string GetCatalogLeafUrl(string? commitId); + + /// + /// Get the URL of the repository signatures resource. + /// See: https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource + /// + string GetRepositorySignaturesUrl(); + + /// + /// Get the URL to download a repository signing certificate. + /// + /// The certificate's SHA-256 fingerprint, as lowercase hex. + string GetRepositorySigningCertificateUrl(string fingerprint); + + /// + /// Get the URL for the entry point of a package's metadata. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index + /// + /// The package's ID. + string? GetRegistrationIndexUrl(string? id); + + /// + /// Get the URL for the metadata of several versions of a single package. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page + /// + /// The package's ID + /// The lowest SemVer 2.0.0 version in the page (inclusive) + /// The highest SemVer 2.0.0 version in the page (inclusive) + string GetRegistrationPageUrl(string id, NuGetVersion lower, NuGetVersion upper); + + /// + /// Get the URL for the metadata of a specific package ID and version. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf + /// + /// The package's ID + /// The package's version + string? GetRegistrationLeafUrl(string? id, NuGetVersion version); + + /// + /// Get the URL that lists a package's versions. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions + /// + /// The package's ID + string? GetPackageVersionsUrl(string id); + + /// + /// Get the URL to download a package (.nupkg). + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg + /// + /// The package's ID + /// The package's version + string? GetPackageDownloadUrl(string? id, NuGetVersion version); + + /// + /// Get the URL to download a package's manifest (.nuspec). + /// + /// The package's ID + /// The package's version + string? GetPackageManifestDownloadUrl(string id, NuGetVersion version); + + /// + /// Get the URL to download a package icon. + /// + /// The package's ID + /// The package's version + string? GetPackageIconDownloadUrl(string? id, NuGetVersion version); + + /// + /// Get the address an npm client is configured with for the current repository: npm/ below the repository base, + /// with a trailing slash (https://host/r/web/npm/). Tarball URLs are this plus {name}/-/{file}. + /// + string GetNpmRegistryUrl(); + + /// + /// Get the address a Maven client is configured with for the current repository: maven/ below the repository base, + /// with a trailing slash (https://host/r/libs/maven/). A file is this plus its layout path. + /// + string GetMavenRepositoryUrl(); + + /// + /// Get the root of the OCI registry: v2/ at the server root (after the path base), with a trailing slash + /// (https://host/v2/). A registry is not under a repository's r/{repo}/ prefix: the BaGet repository is the + /// first segment after v2/, so the address of an image is this plus {repo}/{image}/…. + /// + string GetOciRegistryUrl(); + + /// + /// Get the registry host as a Docker client writes it in an image reference (host:port, no scheme), and whether the + /// request came over plain http (a daemon must then list it as an insecure registry). + /// + (string Host, bool IsHttp) GetOciRegistryHost(); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs b/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs index 4cf4820b2..bf7636f62 100644 --- a/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs +++ b/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs @@ -4,87 +4,92 @@ using System.Linq; using NuGet.Frameworks; -namespace BaGet.Core +namespace BaGet.Core; + +using static NuGet.Frameworks.FrameworkConstants; + +public class FrameworkCompatibilityService : IFrameworkCompatibilityService { - using static NuGet.Frameworks.FrameworkConstants; + private const string AnyFramework = "any"; - public class FrameworkCompatibilityService : IFrameworkCompatibilityService + private static readonly Dictionary KnownFrameworks; + private static readonly IReadOnlyList CompatibilityMapping; + private static readonly ConcurrentDictionary> CompatibleFrameworks; + + static FrameworkCompatibilityService() { - private const string AnyFramework = "any"; + var supportedFrameworks = new HashSet(); + supportedFrameworks.Add(FrameworkIdentifiers.NetStandard); + supportedFrameworks.Add(FrameworkIdentifiers.NetCoreApp); + supportedFrameworks.Add(FrameworkIdentifiers.Net); - private static readonly Dictionary KnownFrameworks; - private static readonly IReadOnlyList CompatibilityMapping; - private static readonly ConcurrentDictionary> CompatibleFrameworks; + CompatibilityMapping = DefaultFrameworkMappings.Instance.CompatibilityMappings.ToList(); + CompatibleFrameworks = new ConcurrentDictionary>(); - static FrameworkCompatibilityService() - { - var supportedFrameworks = new HashSet(); - supportedFrameworks.Add(FrameworkIdentifiers.NetStandard); - supportedFrameworks.Add(FrameworkIdentifiers.NetCoreApp); - supportedFrameworks.Add(FrameworkIdentifiers.Net); + #pragma warning disable CS8619, CS8621, CS8714 + KnownFrameworks = typeof(CommonFrameworks) + .GetFields() + .Where(f => f.IsStatic) + .Where(f => f.FieldType == typeof(NuGetFramework)) + .Select(f => (NuGetFramework?)f.GetValue(null)) + .Where(f => supportedFrameworks.Contains(f?.Framework)) + .ToDictionary(f => f?.GetShortFolderName()); + #pragma warning restore CS8619, CS8621, CS8714 - CompatibilityMapping = DefaultFrameworkMappings.Instance.CompatibilityMappings.ToList(); - CompatibleFrameworks = new ConcurrentDictionary>(); - - KnownFrameworks = typeof(CommonFrameworks) - .GetFields() - .Where(f => f.IsStatic) - .Where(f => f.FieldType == typeof(NuGetFramework)) - .Select(f => (NuGetFramework)f.GetValue(null)) - .Where(f => supportedFrameworks.Contains(f.Framework)) - .ToDictionary(f => f.GetShortFolderName()); + // Add more frameworks missing from "CommonFrameworks" + KnownFrameworks["net472"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 2, 0)); + KnownFrameworks["net471"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 1, 0)); + } - // Add more frameworks missing from "CommonFrameworks" - KnownFrameworks["net472"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 2, 0)); - KnownFrameworks["net471"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 1, 0)); + public IReadOnlyList FindAllCompatibleFrameworks(string name) + { + if (!KnownFrameworks.TryGetValue(name, out var framework)) + { + return new List { name, AnyFramework }; } - public IReadOnlyList FindAllCompatibleFrameworks(string name) - { - if (!KnownFrameworks.TryGetValue(name, out var framework)) - { - return new List { name, AnyFramework }; - } + #pragma warning disable CS8604, CS8621 + return CompatibleFrameworks.GetOrAdd(framework, FindAllCompatibleFrameworks); + #pragma warning restore CS8604, CS8621 + } - return CompatibleFrameworks.GetOrAdd(framework, FindAllCompatibleFrameworks); - } + private IReadOnlyList FindAllCompatibleFrameworks(NuGetFramework targetFramework) + { + var results = new HashSet { AnyFramework }; - private IReadOnlyList FindAllCompatibleFrameworks(NuGetFramework targetFramework) + // Find all framework mappings that apply to the target framework + foreach (var mapping in CompatibilityMapping) { - var results = new HashSet { AnyFramework }; - - // Find all framework mappings that apply to the target framework - foreach (var mapping in CompatibilityMapping) + // Skip this mapping if it isn't for our target framework. + if (!mapping.TargetFrameworkRange.Satisfies(targetFramework)) { - // Skip this mapping if it isn't for our target framework. - if (!mapping.TargetFrameworkRange.Satisfies(targetFramework)) - { - continue; - } - - // Any framework that satisfies this mapping is compatible with the target framework. - foreach (var possibleFramework in KnownFrameworks.Values) - { - if (mapping.SupportedFrameworkRange.Satisfies(possibleFramework)) - { - results.Add(possibleFramework.GetShortFolderName()); - } - } + continue; } - // Find all frameworks that have the same "framework identifier" and a version - // less than equal to our target framework. For example, "net45" is compatible - // with "net20" and "net45". + // Any framework that satisfies this mapping is compatible with the target framework. foreach (var possibleFramework in KnownFrameworks.Values) { - if (possibleFramework.Framework == targetFramework.Framework && - possibleFramework.Version <= targetFramework.Version) + #pragma warning disable CS8604 + if (mapping.SupportedFrameworkRange.Satisfies(possibleFramework)) + #pragma warning restore CS8604 { results.Add(possibleFramework.GetShortFolderName()); } } + } - return results.ToList(); + // Find all frameworks that have the same "framework identifier" and a version + // less than equal to our target framework. For example, "net45" is compatible + // with "net20" and "net45". + foreach (var possibleFramework in KnownFrameworks.Values) + { + if (possibleFramework?.Framework == targetFramework.Framework && + possibleFramework?.Version <= targetFramework.Version) + { + results.Add(possibleFramework?.GetShortFolderName()); + } } + + return results.ToList(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs b/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs index 50f07256e..fec73792d 100644 --- a/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs +++ b/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs @@ -1,17 +1,16 @@ using System.Collections.Generic; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Used to determine the compatibility matrix between frameworks. +/// +public interface IFrameworkCompatibilityService { /// - /// Used to determine the compatibility matrix between frameworks. + /// Given a framework, find all other compatible frameworks. /// - public interface IFrameworkCompatibilityService - { - /// - /// Given a framework, find all other compatible frameworks. - /// - /// The input framework. - /// The list of compatible frameworks. - IReadOnlyList FindAllCompatibleFrameworks(string framework); - } -} + /// The input framework. + /// The list of compatible frameworks. + IReadOnlyList FindAllCompatibleFrameworks(string framework); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageChangeHandler.cs b/src/BaGet.Core/Indexing/IPackageChangeHandler.cs new file mode 100644 index 000000000..5bfc608d4 --- /dev/null +++ b/src/BaGet.Core/Indexing/IPackageChangeHandler.cs @@ -0,0 +1,22 @@ +using System.Threading; +using System.Threading.Tasks; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// Told about every change to a package version after it has been committed. Register +/// any number of these; calls each in turn. +/// +public interface IPackageChangeHandler +{ + /// + /// The package version was added, relisted or unlisted, or its metadata changed. + /// + Task OnPackageChangedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// The package version was permanently deleted. + /// + Task OnPackageDeletedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageDeletionService.cs b/src/BaGet.Core/Indexing/IPackageDeletionService.cs index 691b99e8b..acade0a3c 100644 --- a/src/BaGet.Core/Indexing/IPackageDeletionService.cs +++ b/src/BaGet.Core/Indexing/IPackageDeletionService.cs @@ -2,17 +2,23 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IPackageDeletionService { - public interface IPackageDeletionService - { - /// - /// Attempt to delete a package. - /// - /// The id of the package to delete. - /// The version of the package to delete. - /// - /// False if the package does not exist. - Task TryDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } -} + /// + /// Attempt to delete a package. + /// + /// The id of the package to delete. + /// The version of the package to delete. + /// + /// False if the package does not exist. + Task TryDeletePackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Remove the version's rows and files whatever says. + /// For administrators; the protocol's DELETE keeps following the setting. + /// + /// False if the database held no such version (its files are removed either way). + Task TryHardDeletePackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageIndexingService.cs b/src/BaGet.Core/Indexing/IPackageIndexingService.cs index ddbf06d27..5afe37ea4 100644 --- a/src/BaGet.Core/Indexing/IPackageIndexingService.cs +++ b/src/BaGet.Core/Indexing/IPackageIndexingService.cs @@ -2,41 +2,45 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The result of attempting to index a package. +/// See . +/// +public enum PackageIndexingResult { /// - /// The result of attempting to index a package. - /// See . + /// The package is malformed. This may also happen if BaGet is in a corrupted state. /// - public enum PackageIndexingResult - { - /// - /// The package is malformed. This may also happen if BaGet is in a corrupted state. - /// - InvalidPackage, + InvalidPackage, - /// - /// The package has already been indexed. - /// - PackageAlreadyExists, + /// + /// The package has already been indexed. + /// + PackageAlreadyExists, - /// - /// The package has been indexed successfully. - /// - Success, - } + /// + /// The package has been indexed successfully. + /// + Success, /// - /// The service used to accept new packages. + /// The package was queued for validation and is not available yet. /// - public interface IPackageIndexingService - { - /// - /// Attempt to index a new package. - /// - /// The stream containing the package's content. - /// - /// The result of the attempted indexing operation. - Task IndexAsync(Stream stream, CancellationToken cancellationToken); - } + Accepted, } + +/// +/// The service used to accept new packages. +/// +public interface IPackageIndexingService +{ + /// + /// Attempt to index a new package. + /// + /// The stream containing the package's content. + /// + /// The result of the attempted indexing operation. + Task IndexAsync(Stream? stream, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageSubmissionService.cs b/src/BaGet.Core/Indexing/IPackageSubmissionService.cs new file mode 100644 index 000000000..b102b88f0 --- /dev/null +++ b/src/BaGet.Core/Indexing/IPackageSubmissionService.cs @@ -0,0 +1,34 @@ +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Accepts a package a user pushed. Unlike , which +/// always indexes at once and which mirroring uses, a submission may be validated first. +/// +public interface IPackageSubmissionService +{ + /// + /// if the package is queued for + /// validation, otherwise the result of indexing it. + /// + Task SubmitAsync(Stream package, CancellationToken cancellationToken); +} + +/// +/// Indexes every submission at once: the behaviour without validation. +/// +public class DirectPackageSubmissionService : IPackageSubmissionService +{ + private readonly IPackageIndexingService _indexer; + + public DirectPackageSubmissionService(IPackageIndexingService indexer) + { + _indexer = indexer ?? throw new System.ArgumentNullException(nameof(indexer)); + } + + public Task SubmitAsync(Stream? package, CancellationToken cancellationToken) + => _indexer.IndexAsync(package, cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/ISymbolIndexingService.cs b/src/BaGet.Core/Indexing/ISymbolIndexingService.cs index 85a671a96..d413b55cb 100644 --- a/src/BaGet.Core/Indexing/ISymbolIndexingService.cs +++ b/src/BaGet.Core/Indexing/ISymbolIndexingService.cs @@ -2,41 +2,40 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The result of attempting to index a symbol package. +/// See . +/// +public enum SymbolIndexingResult { /// - /// The result of attempting to index a symbol package. - /// See . + /// The symbol package is malformed. /// - public enum SymbolIndexingResult - { - /// - /// The symbol package is malformed. - /// - InvalidSymbolPackage, - - /// - /// A corresponding package with the provided ID and version does not exist. - /// - PackageNotFound, + InvalidSymbolPackage, - /// - /// The symbol package has been indexed successfully. - /// - Success, - } + /// + /// A corresponding package with the provided ID and version does not exist. + /// + PackageNotFound, /// - /// The service used to accept new symbol packages. + /// The symbol package has been indexed successfully. /// - public interface ISymbolIndexingService - { - /// - /// Attempt to index a new symbol package. - /// - /// The stream containing the symbol package's content. - /// - /// The result of the attempted indexing operation. - Task IndexAsync(Stream stream, CancellationToken cancellationToken); - } + Success, } + +/// +/// The service used to accept new symbol packages. +/// +public interface ISymbolIndexingService +{ + /// + /// Attempt to index a new symbol package. + /// + /// The stream containing the symbol package's content. + /// + /// The result of the attempted indexing operation. + Task IndexAsync(Stream? stream, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/PackageChangeNotifier.cs b/src/BaGet.Core/Indexing/PackageChangeNotifier.cs new file mode 100644 index 000000000..97a76de45 --- /dev/null +++ b/src/BaGet.Core/Indexing/PackageChangeNotifier.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// Calls every registered . The change has already +/// been committed when this runs, so a handler's failure is logged and never fails the +/// operation that made the change. +/// +public class PackageChangeNotifier +{ + /// + /// A notifier with no handlers, for callers constructed without one. + /// + public static readonly PackageChangeNotifier None = new(Array.Empty(), logger: null); + + private readonly IReadOnlyList _handlers; + private readonly ILogger? _logger; + + public PackageChangeNotifier( + IEnumerable? handlers, + ILogger? logger) + { + _handlers = handlers?.ToList() ?? throw new ArgumentNullException(nameof(handlers)); + _logger = logger; + } + + public Task PackageChangedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + => NotifyAsync(id, version, (h, ct) => h.OnPackageChangedAsync(id, version, ct), cancellationToken); + + public Task PackageDeletedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + => NotifyAsync(id, version, (h, ct) => h.OnPackageDeletedAsync(id, version, ct), cancellationToken); + + private async Task NotifyAsync( + string? id, + NuGetVersion version, + Func notify, + CancellationToken cancellationToken) + { + foreach (var handler in _handlers) + { + try + { + await notify(handler, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException && cancellationToken.IsCancellationRequested)) + { + _logger?.LogError( + e, + "{Handler} failed for package {PackageId} {PackageVersion}", + handler.GetType().Name, + id, + version); + } + } + } +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/PackageDeletionService.cs b/src/BaGet.Core/Indexing/PackageDeletionService.cs index 41cf60a98..9d8c5453f 100644 --- a/src/BaGet.Core/Indexing/PackageDeletionService.cs +++ b/src/BaGet.Core/Indexing/PackageDeletionService.cs @@ -5,88 +5,106 @@ using Microsoft.Extensions.Options; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageDeletionService : IPackageDeletionService { - public class PackageDeletionService : IPackageDeletionService + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _storage; + private readonly BaGetOptions _options; + private readonly ILogger _logger; + private readonly PackageChangeNotifier _notifier; + + public PackageDeletionService( + IPackageDatabase packages, + IPackageStorageService storage, + IOptionsSnapshot options, + ILogger logger) + : this(packages, storage, options, logger, PackageChangeNotifier.None) { - private readonly IPackageDatabase _packages; - private readonly IPackageStorageService _storage; - private readonly BaGetOptions _options; - private readonly ILogger _logger; - - public PackageDeletionService( - IPackageDatabase packages, - IPackageStorageService storage, - IOptionsSnapshot options, - ILogger logger) - { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + } + + public PackageDeletionService( + IPackageDatabase packages, + IPackageStorageService storage, + IOptionsSnapshot? options, + ILogger logger, + PackageChangeNotifier notifier) + { + _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task TryDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + public async Task TryDeletePackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + switch (_options.PackageDeletionBehavior) { - switch (_options.PackageDeletionBehavior) - { - case PackageDeletionBehavior.Unlist: - return await TryUnlistPackageAsync(id, version, cancellationToken); + case PackageDeletionBehavior.Unlist: + return await TryUnlistPackageAsync(id, version, cancellationToken); - case PackageDeletionBehavior.HardDelete: - return await TryHardDeletePackageAsync(id, version, cancellationToken); + case PackageDeletionBehavior.HardDelete: + return await TryHardDeletePackageAsync(id, version, cancellationToken); - default: - throw new InvalidOperationException($"Unknown deletion behavior '{_options.PackageDeletionBehavior}'"); - } + default: + throw new InvalidOperationException($"Unknown deletion behavior '{_options.PackageDeletionBehavior}'"); } + } - private async Task TryUnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + private async Task TryUnlistPackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + _logger.LogInformation("Unlisting package {PackageId} {PackageVersion}...", id, version); + + if (!await _packages.UnlistPackageAsync(id, version, cancellationToken)) { - _logger.LogInformation("Unlisting package {PackageId} {PackageVersion}...", id, version); + _logger.LogWarning("Could not find package {PackageId} {PackageVersion}", id, version); - if (!await _packages.UnlistPackageAsync(id, version, cancellationToken)) - { - _logger.LogWarning("Could not find package {PackageId} {PackageVersion}", id, version); + return false; + } - return false; - } + _logger.LogInformation("Unlisted package {PackageId} {PackageVersion}", id, version); - _logger.LogInformation("Unlisted package {PackageId} {PackageVersion}", id, version); + await _notifier.PackageChangedAsync(id, version, cancellationToken); - return true; - } + return true; + } + + public async Task TryHardDeletePackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + _logger.LogInformation( + "Hard deleting package {PackageId} {PackageVersion} from the database...", + id, + version); - private async Task TryHardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + var found = await _packages.HardDeletePackageAsync(id, version, cancellationToken); + if (!found) { - _logger.LogInformation( - "Hard deleting package {PackageId} {PackageVersion} from the database...", + _logger.LogWarning( + "Could not find package {PackageId} {PackageVersion} in the database", id, version); + } - var found = await _packages.HardDeletePackageAsync(id, version, cancellationToken); - if (!found) - { - _logger.LogWarning( - "Could not find package {PackageId} {PackageVersion} in the database", - id, - version); - } - - // Delete the package from storage. This is necessary even if the package isn't - // in the database to ensure that the storage is consistent with the database. - _logger.LogInformation("Hard deleting package {PackageId} {PackageVersion} from storage...", - id, - version); + // Delete the package from storage. This is necessary even if the package isn't + // in the database to ensure that the storage is consistent with the database. + _logger.LogInformation("Hard deleting package {PackageId} {PackageVersion} from storage...", + id, + version); - await _storage.DeleteAsync(id, version, cancellationToken); + await _storage.DeleteAsync(id, version, cancellationToken); - _logger.LogInformation( - "Hard deleted package {PackageId} {PackageVersion} from storage", - id, - version); + _logger.LogInformation( + "Hard deleted package {PackageId} {PackageVersion} from storage", + id, + version); - return found; + if (found) + { + await _notifier.PackageDeletedAsync(id, version, cancellationToken); } + + return found; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/PackageIndexingService.cs b/src/BaGet.Core/Indexing/PackageIndexingService.cs index 8a3006fac..8e602a5ad 100644 --- a/src/BaGet.Core/Indexing/PackageIndexingService.cs +++ b/src/BaGet.Core/Indexing/PackageIndexingService.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -6,160 +8,307 @@ using Microsoft.Extensions.Options; using NuGet.Packaging; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageIndexingService : IPackageIndexingService { - public class PackageIndexingService : IPackageIndexingService + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _storage; + private readonly ISearchIndexer _search; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly ILogger _logger; + private readonly PackageChangeNotifier _notifier; + private readonly MaintenanceGate? _gate; + private readonly IScanGate? _scanGate; + + public PackageIndexingService( + IPackageDatabase packages, + IPackageStorageService storage, + ISearchIndexer search, + SystemTime time, + IOptionsSnapshot options, + ILogger logger) + : this(packages, storage, search, time, options, logger, PackageChangeNotifier.None) + { + } + + public PackageIndexingService( + IPackageDatabase packages, + IPackageStorageService storage, + ISearchIndexer search, + SystemTime time, + IOptionsSnapshot options, + ILogger logger, + PackageChangeNotifier notifier) + : this(packages, storage, search, time, options, logger, notifier, gate: null) + { + } + + /// The package database. + /// Where package content is stored. + /// Indexes the package for search. + /// The current time. + /// The server's options. + /// The logger. + /// Told when a package changes, once it is indexed. + /// + /// When closed, indexing is refused up front with , before any + /// content reaches storage, so a refused push leaves no orphan files behind. + /// + public PackageIndexingService( + IPackageDatabase packages, + IPackageStorageService storage, + ISearchIndexer search, + SystemTime time, + IOptionsSnapshot options, + ILogger logger, + PackageChangeNotifier notifier, + MaintenanceGate? gate) + : this(packages, storage, search, time, options, logger, notifier, gate, scanGate: null) + { + } + + /// The package database. + /// Where package content is stored. + /// Indexes the package for search. + /// The current time. + /// The server's options. + /// The logger. + /// Told when a package changes, once it is indexed. + /// When closed, indexing is refused up front with . + /// Told to scan the package for vulnerabilities once it is indexed (no-op when scanning is off). + public PackageIndexingService( + IPackageDatabase packages, + IPackageStorageService storage, + ISearchIndexer search, + SystemTime time, + IOptionsSnapshot options, + ILogger logger, + PackageChangeNotifier notifier, + MaintenanceGate? gate, + IScanGate? scanGate) { - private readonly IPackageDatabase _packages; - private readonly IPackageStorageService _storage; - private readonly ISearchIndexer _search; - private readonly SystemTime _time; - private readonly IOptionsSnapshot _options; - private readonly ILogger _logger; - - public PackageIndexingService( - IPackageDatabase packages, - IPackageStorageService storage, - ISearchIndexer search, - SystemTime time, - IOptionsSnapshot options, - ILogger logger) + _scanGate = scanGate; + _gate = gate; + _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _search = search ?? throw new ArgumentNullException(nameof(search)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task IndexAsync(Stream? packageStream, CancellationToken cancellationToken) + { + // Costs nothing without a listener: StartActivity returns null. + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.PackageIndex); + + try { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _search = search ?? throw new ArgumentNullException(nameof(search)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + var result = await IndexCoreAsync(packageStream, activity, cancellationToken); - public async Task IndexAsync(Stream packageStream, CancellationToken cancellationToken) + activity?.SetTag(BaGetDiagnostics.Tags.Result, result.ToString()); + BaGetDiagnostics.PackagesPushed.Add(1, new KeyValuePair(BaGetDiagnostics.Tags.Result, result.ToString())); + + return result; + } + catch (Exception e) { - // Try to extract all the necessary information from the package. - Package package; - Stream nuspecStream; - Stream readmeStream; - Stream iconStream; + BaGetDiagnostics.Fail(activity, e); + BaGetDiagnostics.PackagesPushed.Add(1, new KeyValuePair(BaGetDiagnostics.Tags.Result, "error")); + + throw; + } + } - try + private async Task IndexCoreAsync( + Stream? packageStream, + Activity? activity, + CancellationToken cancellationToken) + { + _gate?.ThrowIfClosed(); + + // Try to extract all the necessary information from the package. + Package package; + Stream? nuspecStream = null; + Stream? readmeStream = null; + Stream? iconStream = null; + + try + { + using (var packageReader = new PackageArchiveReader(packageStream, leaveStreamOpen: true)) { - using (var packageReader = new PackageArchiveReader(packageStream, leaveStreamOpen: true)) + // Reject packages whose entries cannot be extracted safely, such as an + // entry whose path escapes the extraction directory. + await packageReader.ValidatePackageEntriesAsync(cancellationToken); + + package = packageReader.GetPackageMetadata(); + package.Published = _time.UtcNow; + + using (var rawNuspec = await packageReader.GetNuspecAsync(cancellationToken)) { - package = packageReader.GetPackageMetadata(); - package.Published = _time.UtcNow; - - nuspecStream = await packageReader.GetNuspecAsync(cancellationToken); - nuspecStream = await nuspecStream.AsTemporaryFileStreamAsync(cancellationToken); - - if (package.HasReadme) - { - readmeStream = await packageReader.GetReadmeAsync(cancellationToken); - readmeStream = await readmeStream.AsTemporaryFileStreamAsync(cancellationToken); - } - else - { - readmeStream = null; - } - - if (package.HasEmbeddedIcon) - { - iconStream = await packageReader.GetIconAsync(cancellationToken); - iconStream = await iconStream.AsTemporaryFileStreamAsync(cancellationToken); - } - else - { - iconStream = null; - } + nuspecStream = await rawNuspec.AsTemporaryFileStreamAsync(cancellationToken); } - } - catch (Exception e) - { - _logger.LogError(e, "Uploaded package is invalid"); - return PackageIndexingResult.InvalidPackage; - } + if (package.HasReadme) + { + using var rawReadme = await packageReader.GetReadmeAsync(cancellationToken); + readmeStream = await rawReadme.AsTemporaryFileStreamAsync(cancellationToken); + } - // The package is well-formed. Ensure this is a new package. - if (await _packages.ExistsAsync(package.Id, package.Version, cancellationToken)) - { - if (!_options.Value.AllowPackageOverwrites) + if (package.HasEmbeddedIcon) { - return PackageIndexingResult.PackageAlreadyExists; + using var rawIcon = await packageReader.GetIconAsync(cancellationToken); + iconStream = await rawIcon.AsTemporaryFileStreamAsync(cancellationToken); } + } + } + catch (Exception e) + { + // The temporary copies are DeleteOnClose files: release them on every path. + nuspecStream?.Dispose(); + readmeStream?.Dispose(); + iconStream?.Dispose(); + + _logger.LogError(e, "Uploaded package is invalid"); - await _packages.HardDeletePackageAsync(package.Id, package.Version, cancellationToken); - await _storage.DeleteAsync(package.Id, package.Version, cancellationToken); + return PackageIndexingResult.InvalidPackage; + } + + try + { + return await IndexExtractedAsync( + package, + packageStream, + nuspecStream!, + readmeStream, + iconStream, + activity, + cancellationToken); + } + finally + { + nuspecStream?.Dispose(); + readmeStream?.Dispose(); + iconStream?.Dispose(); + } + } + + private async Task IndexExtractedAsync( + Package package, + Stream? packageStream, + Stream nuspecStream, + Stream? readmeStream, + Stream? iconStream, + Activity? activity, + CancellationToken cancellationToken) + { + activity?.SetTag(BaGetDiagnostics.Tags.PackageId, package.Id); + activity?.SetTag(BaGetDiagnostics.Tags.PackageVersion, package.NormalizedVersionString); + + // The package is well-formed. Ensure this is a new package. + if (await _packages.ExistsAsync(package.Id, package.Version, cancellationToken)) + { + if (!_options.Value.AllowPackageOverwrites) + { + return PackageIndexingResult.PackageAlreadyExists; } - // TODO: Add more package validations - // TODO: Call PackageArchiveReader.ValidatePackageEntriesAsync - _logger.LogInformation( - "Validated package {PackageId} {PackageVersion}, persisting content to storage...", + await _packages.HardDeletePackageAsync(package.Id, package.Version, cancellationToken); + await _storage.DeleteAsync(package.Id, package.Version, cancellationToken); + } + + // TODO: Add more package validations + _logger.LogInformation( + "Validated package {PackageId} {PackageVersion}, persisting content to storage...", + package.Id, + package.NormalizedVersionString); + + PackageSaveResult storageResult; + + try + { + packageStream?.Position = 0; + + storageResult = await _storage.SavePackageContentAsync( + package, + packageStream, + nuspecStream, + readmeStream, + iconStream, + cancellationToken); + } + catch (Exception e) + { + _logger.LogError( + e, + "Failed to persist package {PackageId} {PackageVersion} content to storage", package.Id, package.NormalizedVersionString); - try - { - packageStream.Position = 0; - - await _storage.SavePackageContentAsync( - package, - packageStream, - nuspecStream, - readmeStream, - iconStream, - cancellationToken); - } - catch (Exception e) - { - // This may happen due to concurrent pushes. - // TODO: Make IPackageStorageService.SavePackageContentAsync return a result enum so this - // can be properly handled. - _logger.LogError( - e, - "Failed to persist package {PackageId} {PackageVersion} content to storage", - package.Id, - package.NormalizedVersionString); - - throw; - } + throw; + } - _logger.LogInformation( - "Persisted package {Id} {Version} content to storage, saving metadata to database...", + if (storageResult == PackageSaveResult.Conflict) + { + // Content for this id/version is already stored and differs from what was pushed. + // This may happen due to concurrent pushes. + _logger.LogWarning( + "Package {PackageId} {PackageVersion} content conflicts with the content already in storage", package.Id, package.NormalizedVersionString); - var result = await _packages.AddAsync(package, cancellationToken); - if (result == PackageAddResult.PackageAlreadyExists) - { - _logger.LogWarning( - "Package {Id} {Version} metadata already exists in database", - package.Id, - package.NormalizedVersionString); + return PackageIndexingResult.PackageAlreadyExists; + } - return PackageIndexingResult.PackageAlreadyExists; - } + if (storageResult != PackageSaveResult.Success) + { + _logger.LogError($"Unknown {nameof(PackageSaveResult)} value: {{PackageSaveResult}}", storageResult); - if (result != PackageAddResult.Success) - { - _logger.LogError($"Unknown {nameof(PackageAddResult)} value: {{PackageAddResult}}", result); + throw new InvalidOperationException($"Unknown {nameof(PackageSaveResult)} value: {storageResult}"); + } - throw new InvalidOperationException($"Unknown {nameof(PackageAddResult)} value: {result}"); - } + _logger.LogInformation( + "Persisted package {Id} {Version} content to storage, saving metadata to database...", + package.Id, + package.NormalizedVersionString); - _logger.LogInformation( - "Successfully persisted package {Id} {Version} metadata to database. Indexing in search...", + var result = await _packages.AddAsync(package, cancellationToken); + if (result == PackageAddResult.PackageAlreadyExists) + { + _logger.LogWarning( + "Package {Id} {Version} metadata already exists in database", package.Id, package.NormalizedVersionString); - await _search.IndexAsync(package, cancellationToken); + return PackageIndexingResult.PackageAlreadyExists; + } - _logger.LogInformation( - "Successfully indexed package {Id} {Version} in search", - package.Id, - package.NormalizedVersionString); + if (result != PackageAddResult.Success) + { + _logger.LogError($"Unknown {nameof(PackageAddResult)} value: {{PackageAddResult}}", result); - return PackageIndexingResult.Success; + throw new InvalidOperationException($"Unknown {nameof(PackageAddResult)} value: {result}"); } + + _logger.LogInformation( + "Successfully persisted package {Id} {Version} metadata to database. Indexing in search...", + package.Id, + package.NormalizedVersionString); + + await _search.IndexAsync(package, cancellationToken); + + _logger.LogInformation( + "Successfully indexed package {Id} {Version} in search", + package.Id, + package.NormalizedVersionString); + + await _notifier.PackageChangedAsync(package.Id, package.Version, cancellationToken); + + if (_scanGate != null) await _scanGate.RegisterStoredAsync(package.Id!, package.NormalizedVersionString!, cancellationToken).ConfigureAwait(false); + + return PackageIndexingResult.Success; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/SearchIndexChangeHandler.cs b/src/BaGet.Core/Indexing/SearchIndexChangeHandler.cs new file mode 100644 index 000000000..e36562454 --- /dev/null +++ b/src/BaGet.Core/Indexing/SearchIndexChangeHandler.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// Re-indexes a package ID in the search index () whenever one of its versions is unlisted, relisted, +/// has its metadata changed or is deleted: indexes on push only, so an external index (Azure +/// Search) would otherwise keep a deleted or unlisted version, and miss a relisted one, until the next push of the same ID. +/// A no-op with the default (the database searches itself). +/// +public sealed class SearchIndexChangeHandler : IPackageChangeHandler +{ + private readonly ISearchIndexer _indexer; + + public SearchIndexChangeHandler(ISearchIndexer indexer) + { + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + } + + /// + public Task OnPackageChangedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) => ReindexAsync(id, cancellationToken); + + /// + public Task OnPackageDeletedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) => ReindexAsync(id, cancellationToken); + + private Task ReindexAsync(string? id, CancellationToken cancellationToken) + => string.IsNullOrEmpty(id) || _indexer is NullSearchIndexer + ? Task.CompletedTask + : _indexer.IndexAsync(new Package { Id = id }, cancellationToken); +} diff --git a/src/BaGet.Core/Indexing/SymbolIndexingService.cs b/src/BaGet.Core/Indexing/SymbolIndexingService.cs index a8a3e52e5..6acb4a62b 100644 --- a/src/BaGet.Core/Indexing/SymbolIndexingService.cs +++ b/src/BaGet.Core/Indexing/SymbolIndexingService.cs @@ -1,206 +1,479 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NuGet.Packaging; +using NuGet.Packaging.Core; +using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +// Based off: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery/Services/SymbolPackageUploadService.cs +// Based off: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L44 +public class SymbolIndexingService : ISymbolIndexingService { - // Based off: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery/Services/SymbolPackageUploadService.cs - // Based off: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L44 - public class SymbolIndexingService : ISymbolIndexingService + // Entry paths inside a package are matched case-insensitively, so an extension + // must be too: a symbol package carrying "Library.PDB" is valid. + private static readonly HashSet ValidSymbolPackageContentExtensions = new(StringComparer.OrdinalIgnoreCase) { - private static readonly HashSet ValidSymbolPackageContentExtensions = new HashSet - { - ".pdb", - ".nuspec", - ".xml", - ".psmdcp", - ".rels", - ".p7s" - }; + ".pdb", + ".nuspec", + ".xml", + ".psmdcp", + ".rels", + ".p7s" + }; - private readonly IPackageDatabase _packages; - private readonly ISymbolStorageService _storage; - private readonly ILogger _logger; + // The extensions of the files a PDB can describe, most likely first. + private static readonly string[] AssemblyExtensions = { ".dll", ".exe" }; - public SymbolIndexingService( - IPackageDatabase packages, - ISymbolStorageService storage, - ILogger logger) - { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + // "BSJB": the signature at the start of the ECMA-335 metadata root, which is what a + // portable PDB is. A Windows PDB starts with "Microsoft C/C++ MSF 7.00" instead, and + // a file that is not a PDB at all starts with something else again. + private static readonly byte[] PortablePdbSignature = { 0x42, 0x53, 0x4A, 0x42 }; + + // The length of a portable PDB's debug metadata id: a 16 byte GUID and a 4 byte stamp. + private const int DebugMetadataIdLength = 20; - public async Task IndexAsync(Stream stream, CancellationToken cancellationToken) + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _packageStorage; + private readonly ISymbolStorageService _storage; + private readonly ILogger _logger; + private readonly ISymbolRegistry? _registry; + private readonly MaintenanceGate? _gate; + + // registry: records which package version each PDB came from, so they can be listed and deleted per + // version (null records nothing). gate: checked before any PDB is stored, so a refused write leaves no file. + public SymbolIndexingService( + IPackageDatabase packages, + IPackageStorageService packageStorage, + ISymbolStorageService storage, + ILogger logger, + ISymbolRegistry? registry = null, + MaintenanceGate? gate = null) + { + _registry = registry; + _gate = gate; + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _packageStorage = packageStorage ?? throw new ArgumentNullException(nameof(packageStorage)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task IndexAsync(Stream? stream, CancellationToken cancellationToken) + { + try { - try + using (var symbolPackage = new PackageArchiveReader(stream, leaveStreamOpen: true)) { - using (var symbolPackage = new PackageArchiveReader(stream, leaveStreamOpen: true)) + var pdbPaths = await GetSymbolPackagePdbPathsOrNullAsync(symbolPackage, cancellationToken); + if (pdbPaths == null) { - var pdbPaths = await GetSymbolPackagePdbPathsOrNullAsync(symbolPackage, cancellationToken); - if (pdbPaths == null) - { - return SymbolIndexingResult.InvalidSymbolPackage; - } + return SymbolIndexingResult.InvalidSymbolPackage; + } - // Ensure a corresponding NuGet package exists. - var packageId = symbolPackage.NuspecReader.GetId(); - var packageVersion = symbolPackage.NuspecReader.GetVersion(); + // Ensure a corresponding NuGet package exists. + var packageId = symbolPackage.NuspecReader.GetId(); + var packageVersion = symbolPackage.NuspecReader.GetVersion(); - var package = await _packages.FindOrNullAsync(packageId, packageVersion, includeUnlisted: true, cancellationToken); - if (package == null) + var package = await _packages.FindOrNullAsync(packageId, packageVersion, includeUnlisted: true, cancellationToken); + if (package == null) + { + _logger.LogWarning( + "Rejecting symbol package {PackageId} {PackageVersion}: the package it belongs to does not exist", + packageId, + packageVersion.ToNormalizedString()); + return SymbolIndexingResult.PackageNotFound; + } + + using (var pdbs = new PdbList()) + { + // Extract the portable PDBs from the snupkg. Nothing is persisted until after all + // PDBs have been extracted and validated sucessfully. + foreach (var pdbPath in pdbPaths) { - return SymbolIndexingResult.PackageNotFound; + var portablePdb = await ExtractPortablePdbOrNullAsync(symbolPackage, pdbPath, cancellationToken); + if (portablePdb == null) + { + return SymbolIndexingResult.InvalidSymbolPackage; + } + + pdbs.Add(portablePdb); } - using (var pdbs = new PdbList()) + // Every PDB must describe a file the package itself ships, otherwise the + // symbol server would serve symbols for code that is not in the package. + if (!await PdbsDescribePackageAsync(packageId, packageVersion, pdbs, cancellationToken)) { - // Extract the portable PDBs from the snupkg. Nothing is persisted until after all - // PDBs have been extracted and validated sucessfully. - foreach (var pdbPath in pdbPaths) - { - var portablePdb = await ExtractPortablePdbAsync(symbolPackage, pdbPath, cancellationToken); - if (portablePdb == null) - { - return SymbolIndexingResult.InvalidSymbolPackage; - } + return SymbolIndexingResult.InvalidSymbolPackage; + } - pdbs.Add(portablePdb); - } + _gate?.ThrowIfClosed(); - // Persist the portable PDBs to storage. - foreach (var pdb in pdbs) - { - await _storage.SavePortablePdbContentAsync(pdb.Filename, pdb.Key, pdb.Content, cancellationToken); - } + // Persist the portable PDBs to storage. + foreach (var pdb in pdbs) + { + pdb.Content.Position = 0; + await _storage.SavePortablePdbContentAsync(pdb.Filename, pdb.Key, pdb.Content, cancellationToken); + } - return SymbolIndexingResult.Success; + // PDBs are stored by file and key, not by package: remember where these came from. + if (_registry != null && pdbs.Count > 0) + { + await _registry.RecordAsync( + packageId, + packageVersion, + pdbs.Select(p => new SymbolReference(p.Filename, p.Key)), + cancellationToken); } + + return SymbolIndexingResult.Success; } } - catch (Exception e) - { - _logger.LogError(e, "Unable to index symbol package due to exception"); - return SymbolIndexingResult.InvalidSymbolPackage; - } } + catch (MaintenanceException) + { + // A refused write is not a malformed package. + throw; + } + catch (Exception e) + { + _logger.LogError(e, "Unable to index symbol package due to exception"); + return SymbolIndexingResult.InvalidSymbolPackage; + } + } - private async Task> GetSymbolPackagePdbPathsOrNullAsync( - PackageArchiveReader symbolPackage, - CancellationToken cancellationToken) + private async Task?> GetSymbolPackagePdbPathsOrNullAsync( + PackageArchiveReader symbolPackage, + CancellationToken cancellationToken) + { + try { - try + await symbolPackage.ValidatePackageEntriesAsync(cancellationToken); + } + catch (PackagingException e) + { + // An entry whose path escapes the extraction directory, such as "../../evil.pdb", + // or that is otherwise unusable. Say so: otherwise the only trace a rejected + // upload leaves is an "invalid symbol package" with no reason attached. + _logger.LogError(e, "Rejecting symbol package: its entries are not safe to extract"); + return null; + } + + var files = (await symbolPackage.GetFilesAsync(cancellationToken)).ToList(); + + // Ensure there are no unexpected file extensions within the symbol package. + var invalidFiles = files.Where(file => !IsValidSymbolFile(file)).ToList(); + if (invalidFiles.Count > 0) + { + _logger.LogError( + "Rejecting symbol package: the entries {InvalidEntries} do not have an extension a symbol package may contain", + string.Join(", ", invalidFiles)); + return null; + } + + return files.Where(IsPdbPath).ToList(); + } + + internal static bool IsPdbPath(string path) + { + return string.Equals(Path.GetExtension(path), ".pdb", StringComparison.OrdinalIgnoreCase); + } + + internal static bool IsValidSymbolFile(string entry) + { + if (string.IsNullOrEmpty(Path.GetFileName(entry))) return false; + + var extension = Path.GetExtension(entry); + if (string.IsNullOrEmpty(extension)) return false; + + return ValidSymbolPackageContentExtensions.Contains(extension); + } + + internal static bool AreSymbolFilesValid(IReadOnlyList entries) + { + return entries.All(IsValidSymbolFile); + } + + private async Task ExtractPortablePdbOrNullAsync( + PackageArchiveReader symbolPackage, + string pdbPath, + CancellationToken cancellationToken) + { + Stream? pdbStream = null; + PortablePdb? result = null; + + try + { + using (var rawPdbStream = await symbolPackage.GetStreamAsync(pdbPath, cancellationToken)) { - await symbolPackage.ValidatePackageEntriesAsync(cancellationToken); + pdbStream = await rawPdbStream.AsTemporaryFileStreamAsync(cancellationToken); - var files = (await symbolPackage.GetFilesAsync(cancellationToken)).ToList(); + // A symbol package may only carry portable PDBs. A Windows PDB cannot be read + // as metadata and cannot be keyed for the symbol server, so reject it here + // with a reason rather than letting the metadata reader throw. + if (!HasPortablePdbSignature(pdbStream)) + { + _logger.LogError( + "Rejecting symbol package: the entry {PdbPath} is not a portable PDB", + pdbPath); + return null; + } - // Ensure there are no unexpected file extensions within the symbol package. - if (!AreSymbolFilesValid(files)) + var signature = ReadPortablePdbSignatureOrNull(pdbStream, pdbPath); + if (signature == null) { return null; } - return files.Where(p => Path.GetExtension(p) == ".pdb").ToList(); + var fileName = Path.GetFileName(pdbPath).ToLowerInvariant(); + var key = $"{signature.Value.ToString("N").ToUpperInvariant()}ffffffff"; + + pdbStream.Position = 0; + result = new PortablePdb(pdbPath, fileName, key, signature.Value, pdbStream); } - catch (Exception) + } + finally + { + if (result == null) { - // TODO: ValidatePackageEntries throws PackagingException. - // Add better logging. - return null; + pdbStream?.Dispose(); } } - private bool AreSymbolFilesValid(IReadOnlyList entries) + return result; + } + + /// + /// Whether the stream starts with the signature every portable PDB starts with. + /// + internal static bool HasPortablePdbSignature(Stream pdbStream) + { + if (pdbStream == null) throw new ArgumentNullException(nameof(pdbStream)); + if (!pdbStream.CanSeek) throw new ArgumentException("The stream must be seekable", nameof(pdbStream)); + + var position = pdbStream.Position; + + try + { + pdbStream.Position = 0; + + var signature = new byte[PortablePdbSignature.Length]; + var read = pdbStream.ReadAtLeast(signature, signature.Length, throwOnEndOfStream: false); + + // A file shorter than the signature - including an empty one - is not a PDB. + return read == signature.Length && signature.SequenceEqual(PortablePdbSignature); + } + finally + { + pdbStream.Position = position; + } + } + + private Guid? ReadPortablePdbSignatureOrNull(Stream pdbStream, string pdbPath) + { + pdbStream.Position = 0; + + try { - // TODO: Validate that all PDBs are portable. See: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery/Services/SymbolPackageService.cs#L174 - bool IsValidSymbolFileInfo(FileInfo file) + using (var pdbReaderProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream, MetadataStreamOptions.LeaveOpen)) { - if (string.IsNullOrEmpty(file.Name)) return false; - if (string.IsNullOrEmpty(file.Extension)) return false; - if (!ValidSymbolPackageContentExtensions.Contains(file.Extension)) return false; + var reader = pdbReaderProvider.GetMetadataReader(); - return true; + // Metadata that starts with the right signature but carries no debug metadata + // header is not a PDB, it is an assembly's metadata. + var header = reader.DebugMetadataHeader; + if (header == null || header.Id.Length != DebugMetadataIdLength) + { + _logger.LogError( + "Rejecting symbol package: the entry {PdbPath} does not contain portable PDB debug metadata", + pdbPath); + return null; + } + + return new BlobContentId(header.Id).Guid; } + } + catch (BadImageFormatException e) + { + _logger.LogError(e, "Rejecting symbol package: the entry {PdbPath} is a malformed portable PDB", pdbPath); + return null; + } + } - return entries.Select(e => new FileInfo(e)).All(IsValidSymbolFileInfo); + /// + /// Whether every PDB describes a file shipped by the package it claims to belong to. + /// See: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L170 + /// + private async Task PdbsDescribePackageAsync( + string packageId, + NuGetVersion packageVersion, + IReadOnlyList pdbs, + CancellationToken cancellationToken) + { + if (pdbs.Count == 0) + { + return true; } - private async Task ExtractPortablePdbAsync( - PackageArchiveReader symbolPackage, - string pdbPath, - CancellationToken cancellationToken) + using (var packageStream = await _packageStorage.GetPackageStreamAsync(packageId, packageVersion, cancellationToken)) + using (var package = new PackageArchiveReader(packageStream, leaveStreamOpen: true)) { - // TODO: Validate that the PDB has a corresponding DLL - // See: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L170 - Stream pdbStream = null; - PortablePdb result = null; + var packageFiles = (await package.GetFilesAsync(cancellationToken)).ToList(); - try + foreach (var pdb in pdbs) { - using (var rawPdbStream = await symbolPackage.GetStreamAsync(pdbPath, cancellationToken)) + var assemblyPath = FindAssemblyPathOrNull(packageFiles, pdb.Path); + if (assemblyPath == null) { - pdbStream = await rawPdbStream.AsTemporaryFileStreamAsync(); + _logger.LogError( + "Rejecting symbol package {PackageId} {PackageVersion}: its PDB {PdbPath} has no corresponding assembly in the package", + packageId, + packageVersion.ToNormalizedString(), + pdb.Path); + return false; + } - string signature; - using (var pdbReaderProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream, MetadataStreamOptions.LeaveOpen)) - { - var reader = pdbReaderProvider.GetMetadataReader(); - var id = new BlobContentId(reader.DebugMetadataHeader.Id); + if (!await AssemblyMatchesPdbAsync(package, assemblyPath, pdb, cancellationToken)) + { + return false; + } + } + } - signature = id.Guid.ToString("N").ToUpperInvariant(); - } + return true; + } - var fileName = Path.GetFileName(pdbPath).ToLowerInvariant(); - var key = $"{signature}ffffffff"; + /// + /// A symbol package mirrors the layout of the package it belongs to, so the assembly a + /// PDB describes sits at the same path with an assembly extension. + /// + private static string? FindAssemblyPathOrNull(IReadOnlyList packageFiles, string pdbPath) + { + foreach (var extension in AssemblyExtensions) + { + var candidate = NormalizePath(Path.ChangeExtension(pdbPath, extension)); - pdbStream.Position = 0; - result = new PortablePdb(fileName, key, pdbStream); - } - } - finally + foreach (var packageFile in packageFiles) { - if (result == null) + if (string.Equals(NormalizePath(packageFile), candidate, StringComparison.OrdinalIgnoreCase)) { - pdbStream?.Dispose(); + return packageFile; } } - - return result; } - private class PortablePdb : IDisposable + return null; + } + + private static string NormalizePath(string path) + { + return path.Replace('\\', '/').TrimStart('/'); + } + + private async Task AssemblyMatchesPdbAsync( + PackageArchiveReader package, + string assemblyPath, + PortablePdb pdb, + CancellationToken cancellationToken) + { + using (var rawAssemblyStream = await package.GetStreamAsync(assemblyPath, cancellationToken)) + using (var assemblyStream = await rawAssemblyStream.AsTemporaryFileStreamAsync(cancellationToken)) { - public PortablePdb(string filename, string key, Stream content) + IReadOnlyList signatures; + + try + { + signatures = ReadCodeViewSignatures(assemblyStream); + } + catch (BadImageFormatException e) + { + _logger.LogError( + e, + "Rejecting symbol package: the package's {AssemblyPath} is not a readable assembly, so its PDB {PdbPath} cannot be matched to it", + assemblyPath, + pdb.Path); + return false; + } + + if (signatures.Count == 0) + { + // The assembly ships without a debug directory, so there is nothing to match + // the PDB against. Index it rather than reject what cannot be checked. + _logger.LogWarning( + "The package's {AssemblyPath} has no debug directory, so its PDB {PdbPath} cannot be matched to it", + assemblyPath, + pdb.Path); + return true; + } + + if (!signatures.Contains(pdb.Signature)) { - Filename = filename; - Key = key; - Content = content; + _logger.LogError( + "Rejecting symbol package: its PDB {PdbPath} does not describe the package's {AssemblyPath}", + pdb.Path, + assemblyPath); + return false; } - public string Filename { get; } - public string Key { get; } - public Stream Content { get; } + return true; + } + } + + /// + /// The debug signatures an assembly's CodeView debug directory entries point at. A + /// portable PDB describes the assembly when it carries one of them. + /// + private static IReadOnlyList ReadCodeViewSignatures(Stream assemblyStream) + { + assemblyStream.Position = 0; + + using (var peReader = new PEReader(assemblyStream, PEStreamOptions.LeaveOpen)) + { + return peReader + .ReadDebugDirectory() + .Where(entry => entry.Type == DebugDirectoryEntryType.CodeView) + .Select(entry => peReader.ReadCodeViewDebugDirectoryData(entry).Guid) + .ToList(); + } + } - public void Dispose() => Content.Dispose(); + private class PortablePdb : IDisposable + { + public PortablePdb(string path, string filename, string key, Guid signature, Stream content) + { + Path = path; + Filename = filename; + Key = key; + Signature = signature; + Content = content; } - private class PdbList : List, IDisposable + /// The PDB's path within the symbol package. + public string Path { get; } + public string Filename { get; } + public string Key { get; } + + /// The PDB's debug signature GUID. + public Guid Signature { get; } + public Stream Content { get; } + + public void Dispose() => Content.Dispose(); + } + + private class PdbList : List, IDisposable + { + public void Dispose() { - public void Dispose() + foreach (var pdb in this) { - foreach (var pdb in this) - { - pdb.Dispose(); - } + pdb.Dispose(); } } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs b/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs index f84747d41..e6a4032b7 100644 --- a/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs +++ b/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs @@ -2,33 +2,32 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to the package metadata model. These additions +/// are not part of the official protocol. +/// +public class BaGetPackageMetadata : PackageMetadata { - /// - /// BaGet's extensions to the package metadata model. These additions - /// are not part of the official protocol. - /// - public class BaGetPackageMetadata : PackageMetadata - { - [JsonPropertyName("downloads")] - public long Downloads { get; set; } + [JsonPropertyName("downloads")] + public long Downloads { get; set; } - [JsonPropertyName("hasReadme")] - public bool HasReadme { get; set; } + [JsonPropertyName("hasReadme")] + public bool HasReadme { get; set; } - [JsonPropertyName("packageTypes")] - public IReadOnlyList PackageTypes { get; set; } + [JsonPropertyName("packageTypes")] + public IReadOnlyList? PackageTypes { get; set; } - /// - /// The package's release notes. - /// - [JsonPropertyName("releaseNotes")] - public string ReleaseNotes { get; set; } + /// + /// The package's release notes. + /// + [JsonPropertyName("releaseNotes")] + public string? ReleaseNotes { get; set; } - [JsonPropertyName("repositoryUrl")] - public string RepositoryUrl { get; set; } + [JsonPropertyName("repositoryUrl")] + public string? RepositoryUrl { get; set; } - [JsonPropertyName("repositoryType")] - public string RepositoryType { get; set; } - } -} + [JsonPropertyName("repositoryType")] + public string? RepositoryType { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs index 6ade52d0f..30460ded3 100644 --- a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs +++ b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs @@ -1,39 +1,21 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to a registration index page. Extends +/// , shadowing the single property whose type +/// differs. +/// +public class BaGetRegistrationIndexPage : RegistrationIndexPage { /// - /// BaGet's extensions to a registration index page. - /// Extends . + /// This was modified to use BaGet's extended registration index page item model. /// - /// - /// TODO: After this project is updated to .NET 5, make - /// extend and remove identical properties. - /// Properties that are modified should be marked with the "new" modified. - /// See: https://github.com/dotnet/runtime/pull/32107 - /// - public class BaGetRegistrationIndexPage - { -#region Original properties from RegistrationIndexPage. - [JsonPropertyName("@id")] - public string RegistrationPageUrl { get; set; } - - [JsonPropertyName("count")] - public int Count { get; set; } - - [JsonPropertyName("lower")] - public string Lower { get; set; } - - [JsonPropertyName("upper")] - public string Upper { get; set; } -#endregion - - /// - /// This was modified to use BaGet's extended registration index page item model. - /// - [JsonPropertyName("items")] - public IReadOnlyList ItemsOrNull { get; set; } - } -} + // Ordered so the serialized property order is unchanged by inheriting the base type. + [JsonPropertyName("items")] + [JsonPropertyOrder(1)] + public new IReadOnlyList? ItemsOrNull { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs index 3177522e3..7f0a88813 100644 --- a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs +++ b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs @@ -1,33 +1,20 @@ -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to a registration index page item. Extends +/// , shadowing the single property whose type +/// differs. +/// +public class BaGetRegistrationIndexPageItem : RegistrationIndexPageItem { /// - /// BaGet's extensions to a registration index page. - /// Extends . + /// This was modified to use BaGet's extended package metadata model. /// - /// - /// TODO: After this project is updated to .NET 5, make - /// extend and remove identical properties. - /// Properties that are modified should be marked with the "new" modified. - /// See: https://github.com/dotnet/runtime/pull/32107 - /// - public class BaGetRegistrationIndexPageItem - { -#region Original properties from RegistrationIndexPageItem. - [JsonPropertyName("@id")] - public string RegistrationLeafUrl { get; set; } - - [JsonPropertyName("packageContent")] - public string PackageContentUrl { get; set; } -#endregion - - /// - /// The catalog entry containing the package metadata. - /// This was modified to use BaGet's extended package metadata model. - /// - [JsonPropertyName("catalogEntry")] - public BaGetPackageMetadata PackageMetadata { get; set; } - } -} + // Ordered so the serialized property order is unchanged by inheriting the base type. + [JsonPropertyName("catalogEntry")] + [JsonPropertyOrder(1)] + public new BaGetPackageMetadata? PackageMetadata { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs b/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs index 9ff6ce66c..33f0a7490 100644 --- a/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs +++ b/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs @@ -1,45 +1,31 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to a registration index response. Extends +/// , shadowing the property whose type differs +/// and adding BaGet's own total download count. +/// +public class BaGetRegistrationIndexResponse : RegistrationIndexResponse { /// - /// BaGet's extensions to a registration index response. - /// Extends . + /// The pages that contain all of the versions of the package, ordered + /// by the package's version. This was modified to use BaGet's extended + /// registration index page model. /// - /// - /// TODO: After this project is updated to .NET 5, make - /// extend and remove identical properties. - /// Properties that are modified should be marked with the "new" modified. - /// See: https://github.com/dotnet/runtime/pull/32107 - /// - public class BaGetRegistrationIndexResponse - { -#region Original properties from RegistrationIndexResponse. - [JsonPropertyName("@id")] - public string RegistrationIndexUrl { get; set; } - - [JsonPropertyName("@type")] - public IReadOnlyList Type { get; set; } - - [JsonPropertyName("count")] - public int Count { get; set; } -#endregion + // Ordered so the serialized property order is unchanged by inheriting the base type. + [JsonPropertyName("items")] + [JsonPropertyOrder(1)] + public new IReadOnlyList? Pages { get; set; } - /// - /// The pages that contain all of the versions of the package, ordered - /// by the package's version. This was modified to use BaGet's extended - /// registration index page model. - /// - [JsonPropertyName("items")] - public IReadOnlyList Pages { get; set; } - - /// - /// The package's total downloads across all versions. - /// This is not part of the official NuGet protocol. - /// - [JsonPropertyName("totalDownloads")] - public long TotalDownloads { get; set; } - } -} + /// + /// The package's total downloads across all versions. + /// This is not part of the official NuGet protocol. + /// + [JsonPropertyName("totalDownloads")] + [JsonPropertyOrder(2)] + public long TotalDownloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs b/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs index 130e1e59b..072bfdae5 100644 --- a/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs +++ b/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs @@ -5,50 +5,49 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +public class DefaultPackageMetadataService : IPackageMetadataService { - /// - public class DefaultPackageMetadataService : IPackageMetadataService + private readonly IPackageService _packages; + private readonly RegistrationBuilder _builder; + + public DefaultPackageMetadataService( + IPackageService packages, + RegistrationBuilder builder) { - private readonly IPackageService _packages; - private readonly RegistrationBuilder _builder; + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + } - public DefaultPackageMetadataService( - IPackageService packages, - RegistrationBuilder builder) + public async Task GetRegistrationIndexOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var packages = await _packages.FindPackagesAsync(packageId, cancellationToken); + if (!packages.Any()) { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + return null; } - public async Task GetRegistrationIndexOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var packages = await _packages.FindPackagesAsync(packageId, cancellationToken); - if (!packages.Any()) - { - return null; - } - - return _builder.BuildIndex( - new PackageRegistration( - packageId, - packages)); - } + return _builder.BuildIndex( + new PackageRegistration( + packageId, + packages)); + } - public async Task GetRegistrationLeafOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken = default) + public async Task GetRegistrationLeafOrNullAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken = default) + { + var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); + if (package == null) { - var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); - if (package == null) - { - return null; - } - - return _builder.BuildLeaf(package); + return null; } + + return _builder.BuildLeaf(package); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/IPackageMetadataService.cs b/src/BaGet.Core/Metadata/IPackageMetadataService.cs index 83bf3fab0..082182484 100644 --- a/src/BaGet.Core/Metadata/IPackageMetadataService.cs +++ b/src/BaGet.Core/Metadata/IPackageMetadataService.cs @@ -3,34 +3,33 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The Package Metadata client, used to fetch packages' metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource +/// +public interface IPackageMetadataService { /// - /// The Package Metadata client, used to fetch packages' metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// Attempt to get a package's registration index, if it exists. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page /// - public interface IPackageMetadataService - { - /// - /// Attempt to get a package's registration index, if it exists. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The package's ID. - /// A token to cancel the task. - /// The package's registration index, or null if the package does not exist - Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); + /// The package's ID. + /// A token to cancel the task. + /// The package's registration index, or null if the package does not exist + Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); - /// - /// Get the metadata for a single package version, if the package exists. - /// - /// The package's id. - /// The package's version. - /// A token to cancel the task. - /// The registration leaf, or null if the package does not exist. - Task GetRegistrationLeafOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default); - } -} + /// + /// Get the metadata for a single package version, if the package exists. + /// + /// The package's id. + /// The package's version. + /// A token to cancel the task. + /// The registration leaf, or null if the package does not exist. + Task GetRegistrationLeafOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/PackageRegistration.cs b/src/BaGet.Core/Metadata/PackageRegistration.cs index 6e583574a..8891b3195 100644 --- a/src/BaGet.Core/Metadata/PackageRegistration.cs +++ b/src/BaGet.Core/Metadata/PackageRegistration.cs @@ -1,34 +1,33 @@ using System; using System.Collections.Generic; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The information on all versions of a package. +/// +public class PackageRegistration { /// - /// The information on all versions of a package. + /// Create a new registration object. /// - public class PackageRegistration + /// + /// All versions of the package. + public PackageRegistration( + string? packageId, + IReadOnlyList packages) { - /// - /// Create a new registration object. - /// - /// - /// All versions of the package. - public PackageRegistration( - string packageId, - IReadOnlyList packages) - { - PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); - Packages = packages ?? throw new ArgumentNullException(nameof(packages)); - } + PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); + Packages = packages ?? throw new ArgumentNullException(nameof(packages)); + } - /// - /// The package's ID. - /// - public string PackageId { get; } + /// + /// The package's ID. + /// + public string PackageId { get; } - /// - /// The information for each version of the package. - /// - public IReadOnlyList Packages { get; } - } -} + /// + /// The information for each version of the package. + /// + public IReadOnlyList Packages { get; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/PackageVulnerabilityRules.cs b/src/BaGet.Core/Metadata/PackageVulnerabilityRules.cs new file mode 100644 index 000000000..69591bcd3 --- /dev/null +++ b/src/BaGet.Core/Metadata/PackageVulnerabilityRules.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// The rules a package version's vulnerability list must satisfy, shared by the metadata API +/// (PackageMetadataAdminController) and the Manage page so both accept and refuse the same input. +/// +public static class PackageVulnerabilityRules +{ + /// The protocol numbers severity 0 low, 1 moderate, 2 high, 3 critical. + public const int MaxSeverity = 3; + + /// Display names of the severities, indexed by their protocol number. + public static readonly IReadOnlyList SeverityNames = new[] { "Low", "Moderate", "High", "Critical" }; + + /// The first problem with the list, or null when every entry is acceptable. + /// The list to check; null is refused (an empty list clears). + public static string? Validate(IReadOnlyList? vulnerabilities) + { + if (vulnerabilities == null) + { + return "A list of vulnerabilities is required; send an empty list to clear them."; + } + + foreach (var vulnerability in vulnerabilities) + { + if (vulnerability == null) + { + return "A vulnerability cannot be null."; + } + + var error = Validate(vulnerability.AdvisoryUrl, vulnerability.Severity, vulnerability.VersionRange); + if (error != null) + { + return error; + } + } + + return null; + } + + /// The first problem with one vulnerability's fields, or null when they are acceptable. + public static string? Validate(string? advisoryUrl, int severity, string? versionRange) + { + if (!Uri.TryCreate(advisoryUrl, UriKind.Absolute, out var url) + || (url.Scheme != Uri.UriSchemeHttps && url.Scheme != Uri.UriSchemeHttp)) + { + return $"'{advisoryUrl}' is not an absolute http or https URL."; + } + + if (severity < 0 || severity > MaxSeverity) + { + return $"Severity {severity} is outside the range 0 to {MaxSeverity}."; + } + + if (versionRange != null && !VersionRange.TryParse(versionRange, out _)) + { + return $"'{versionRange}' is not a version range."; + } + + return null; + } +} diff --git a/src/BaGet.Core/Metadata/RegistrationBuilder.cs b/src/BaGet.Core/Metadata/RegistrationBuilder.cs index 4090e9323..84e6a3d08 100644 --- a/src/BaGet.Core/Metadata/RegistrationBuilder.cs +++ b/src/BaGet.Core/Metadata/RegistrationBuilder.cs @@ -1,118 +1,170 @@ -using System; +using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public class RegistrationBuilder { - public class RegistrationBuilder + private readonly IUrlGenerator _url; + + public RegistrationBuilder(IUrlGenerator url) { - private readonly IUrlGenerator _url; + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public RegistrationBuilder(IUrlGenerator url) - { - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public virtual BaGetRegistrationIndexResponse BuildIndex(PackageRegistration registration) + { + var sortedPackages = registration.Packages.OrderBy(p => p.Version).ToList(); - public virtual BaGetRegistrationIndexResponse BuildIndex(PackageRegistration registration) + // TODO: Paging of registration items. + // "Un-paged" example: https://api.nuget.org/v3/registration3/newtonsoft.json/index.json + // Paged example: https://api.nuget.org/v3/registration3/fake/index.json + return new BaGetRegistrationIndexResponse { - var sortedPackages = registration.Packages.OrderBy(p => p.Version).ToList(); - - // TODO: Paging of registration items. - // "Un-paged" example: https://api.nuget.org/v3/registration3/newtonsoft.json/index.json - // Paged example: https://api.nuget.org/v3/registration3/fake/index.json - return new BaGetRegistrationIndexResponse + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(registration.PackageId), + Type = RegistrationIndexResponse.DefaultType, + Count = 1, + TotalDownloads = registration.Packages.Sum(p => p.Downloads), + Pages = new[] { - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(registration.PackageId), - Type = RegistrationIndexResponse.DefaultType, - Count = 1, - TotalDownloads = registration.Packages.Sum(p => p.Downloads), - Pages = new[] + new BaGetRegistrationIndexPage { - new BaGetRegistrationIndexPage - { - RegistrationPageUrl = _url.GetRegistrationIndexUrl(registration.PackageId), - Count = registration.Packages.Count(), - Lower = sortedPackages.First().Version.ToNormalizedString().ToLowerInvariant(), - Upper = sortedPackages.Last().Version.ToNormalizedString().ToLowerInvariant(), - ItemsOrNull = sortedPackages.Select(ToRegistrationIndexPageItem).ToList(), - } + RegistrationPageUrl = _url.GetRegistrationIndexUrl(registration.PackageId), + Count = registration.Packages.Count(), + Lower = sortedPackages.First().Version.ToNormalizedString().ToLowerInvariant(), + Upper = sortedPackages.Last().Version.ToNormalizedString().ToLowerInvariant(), + ItemsOrNull = sortedPackages.Select(ToRegistrationIndexPageItem).ToList(), } - }; - } + } + }; + } + + public virtual RegistrationLeafResponse BuildLeaf(Package package) + { + var id = package.Id; + var version = package.Version; - public virtual RegistrationLeafResponse BuildLeaf(Package package) + return new RegistrationLeafResponse { - var id = package.Id; - var version = package.Version; + Type = RegistrationLeafResponse.DefaultType, + Listed = package.Listed, + Published = package.Published, + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(id, version), + PackageContentUrl = _url.GetPackageDownloadUrl(id, version), + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(id) + }; + } - return new RegistrationLeafResponse + #pragma warning disable CS8604 + private BaGetRegistrationIndexPageItem ToRegistrationIndexPageItem(Package package) => + new() + { + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(package.Id, package.Version), + PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), + PackageMetadata = new BaGetPackageMetadata { - Type = RegistrationLeafResponse.DefaultType, + PackageId = package.Id, + Version = package.Version.ToFullString(), + Authors = string.Join(", ", package.Authors), + Description = package.Description, + Downloads = package.Downloads, + HasReadme = package.HasReadme, + IconUrl = package.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(package.Id, package.Version) + : package.IconUrlString, + Language = package.Language, + LicenseUrl = package.LicenseUrlString, Listed = package.Listed, - Published = package.Published, - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(id, version), - PackageContentUrl = _url.GetPackageDownloadUrl(id, version), - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(id) - }; + MinClientVersion = package.MinClientVersion, + ReleaseNotes = package.ReleaseNotes, + PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), + PackageTypes = package.PackageTypes?.Select(t => t.Name).ToList(), + ProjectUrl = package.ProjectUrlString, + RepositoryUrl = package.RepositoryUrlString, + RepositoryType = package.RepositoryType, + Published = package.Published==DateTime.MinValue?DateTimeOffset.Now : package.Published, + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + Summary = package.Summary, + Tags = package.Tags, + Title = package.Title, + DependencyGroups = ToDependencyGroups(package), + Deprecation = ToDeprecation(package.Deprecation), + Vulnerabilities = ToVulnerabilities(package.Vulnerabilities), + }, + }; + #pragma warning restore CS8604 + + // Inside BaGet.Core the entity BaGet.Core.PackageDeprecation is found before the + // protocol model of the same name, so the protocol model is named in full. + internal static Protocol.Models.PackageDeprecation? ToDeprecation(PackageDeprecation? deprecation) + { + if (deprecation == null) + { + return null; } - private BaGetRegistrationIndexPageItem ToRegistrationIndexPageItem(Package package) => - new BaGetRegistrationIndexPageItem - { - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(package.Id, package.Version), - PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), - PackageMetadata = new BaGetPackageMetadata + return new Protocol.Models.PackageDeprecation + { + Reasons = deprecation.Reasons ?? Array.Empty(), + Message = deprecation.Message, + AlternatePackage = string.IsNullOrEmpty(deprecation.AlternatePackageId) + ? null + : new AlternatePackage { - PackageId = package.Id, - Version = package.Version.ToFullString(), - Authors = string.Join(", ", package.Authors), - Description = package.Description, - Downloads = package.Downloads, - HasReadme = package.HasReadme, - IconUrl = package.HasEmbeddedIcon - ? _url.GetPackageIconDownloadUrl(package.Id, package.Version) - : package.IconUrlString, - Language = package.Language, - LicenseUrl = package.LicenseUrlString, - Listed = package.Listed, - MinClientVersion = package.MinClientVersion, - ReleaseNotes = package.ReleaseNotes, - PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), - PackageTypes = package.PackageTypes.Select(t => t.Name).ToList(), - ProjectUrl = package.ProjectUrlString, - RepositoryUrl = package.RepositoryUrlString, - RepositoryType = package.RepositoryType, - Published = package.Published, - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - Summary = package.Summary, - Tags = package.Tags, - Title = package.Title, - DependencyGroups = ToDependencyGroups(package) + Id = deprecation.AlternatePackageId, + + // The protocol writes "*" for "any version". + Range = string.IsNullOrEmpty(deprecation.AlternateVersionRange) + ? "*" + : deprecation.AlternateVersionRange, }, - }; + }; + } - private IReadOnlyList ToDependencyGroups(Package package) + internal static IReadOnlyList? ToVulnerabilities( + IReadOnlyCollection? vulnerabilities) + { + // Null rather than empty, so a version with no known vulnerabilities serialises + // exactly as it did before vulnerabilities existed. + if (vulnerabilities == null || vulnerabilities.Count == 0) { - return package.Dependencies - .GroupBy(d => d.TargetFramework) - .Select(group => new DependencyGroupItem - { - TargetFramework = group.Key, - - // A package that supports a target framework but does not have dependencies while on - // that target framework is represented by a fake dependency with a null "Id" and "VersionRange". - // This fake dependency should not be included in the output. - Dependencies = group - .Where(d => d.Id != null && d.VersionRange != null) - .Select(d => new DependencyItem - { - Id = d.Id, - Range = d.VersionRange - }) - .ToList() - }) - .ToList(); + return null; } + + return vulnerabilities + .Select(v => new PackageVulnerabilityMetadata + { + AdvisoryUrl = v.AdvisoryUrl, + Severity = v.Severity.ToString(CultureInfo.InvariantCulture), + }) + .ToList(); + } + + internal static IReadOnlyList ToDependencyGroups(Package package) + { + #pragma warning disable CS8604 + return package.Dependencies + .GroupBy(d => d.TargetFramework) + .Select(group => new DependencyGroupItem + { + TargetFramework = group.Key, + + // A package that supports a target framework but does not have dependencies while on + // that target framework is represented by a fake dependency with a null "Id" and "VersionRange". + // This fake dependency should not be included in the output. + Dependencies = group + .Where(d => d.Id != null && d.VersionRange != null) + .Select(d => new DependencyItem + { + Id = d.Id, + Range = d.VersionRange + }) + .ToList() + }) + .ToList(); + #pragma warning restore CS8604 } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Operations/AbuseReportAdministration.cs b/src/BaGet.Core/Operations/AbuseReportAdministration.cs new file mode 100644 index 000000000..7a64d83b0 --- /dev/null +++ b/src/BaGet.Core/Operations/AbuseReportAdministration.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// An abuse report with the name of its repository. +public sealed record AbuseReportSummary( + int Key, + string Repository, + string? PackageId, + string? PackageVersion, + string? Reason, + string? Details, + string? ReporterEmail, + DateTime Created, + DateTime? Resolved) +{ + public bool IsResolved => Resolved != null; +} + +/// +/// The administrator's view of abuse reports across every repository. Needs a relational database: with Azure Table +/// () nothing is stored, so is false and the list is empty. +/// +public interface IAbuseReportAdministration +{ + bool IsSupported { get; } + + /// Newest first. + Task> ListAsync(bool unresolvedOnly, CancellationToken cancellationToken); + + /// Marks a report resolved (or open again). + /// False when there is no such report. + /// The gate is closed. + Task SetResolvedAsync(int key, bool resolved, CancellationToken cancellationToken); +} + +/// +public sealed class AbuseReportAdministration : IAbuseReportAdministration +{ + private readonly IContext _context; + private readonly IRepositoryService _repositories; + private readonly SystemTime _time; + private readonly MaintenanceGate? _gate; + + public AbuseReportAdministration(IContext context, IRepositoryService repositories, SystemTime time, MaintenanceGate? gate = null) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate; + } + + /// + public bool IsSupported => _context is not NullContext && _context.AbuseReports != null; + + /// + public async Task> ListAsync(bool unresolvedOnly, CancellationToken cancellationToken) + { + if (!IsSupported) return Array.Empty(); + + // Every repository's reports: the page is not tied to one. + var query = _context.AbuseReports!.IgnoreQueryFilters().AsNoTracking(); + if (unresolvedOnly) query = query.Where(r => r.Resolved == null); + + var reports = await query.OrderByDescending(r => r.Created).ThenByDescending(r => r.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var names = (await _repositories.ListAsync(cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, r => r.Name); + + return reports + .Select(r => new AbuseReportSummary( + r.Key, + names.TryGetValue(r.RepositoryKey, out var name) ? name : Repository.DefaultName, + r.PackageId, r.PackageVersion, r.Reason, r.Details, r.ReporterEmail, r.Created, r.Resolved)) + .ToList(); + } + + /// + public async Task SetResolvedAsync(int key, bool resolved, CancellationToken cancellationToken) + { + _gate?.ThrowIfClosed(); + if (!IsSupported) return false; + + var report = await _context.AbuseReports!.IgnoreQueryFilters().FirstOrDefaultAsync(r => r.Key == key, cancellationToken).ConfigureAwait(false); + if (report == null) return false; + + report.Resolved = resolved ? report.Resolved ?? _time.UtcNow : null; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return true; + } +} diff --git a/src/BaGet.Core/Operations/AdminJobs.cs b/src/BaGet.Core/Operations/AdminJobs.cs new file mode 100644 index 000000000..a6c2092bb --- /dev/null +++ b/src/BaGet.Core/Operations/AdminJobs.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// A long-running maintenance operation an administrator can start from the web UI for one repository +/// (what the catalog rebuild and import downloads commands do). Registered as a singleton. +/// +public interface IAdminOperation +{ + /// The stable id used in forms and status (catalog-rebuild). + string Name { get; } + + string Title { get; } + + string Description { get; } + + /// Whether the configured services can run it; is a request scope. + bool IsAvailable(IServiceProvider services); + + /// + /// Whether the operation makes sense for (a Docker garbage collection does not for a NuGet repository). + /// The Operations page lists it only for those, and refuses the others. Default: every repository. + /// + bool AppliesTo(RepositoryInfo repository) => true; + + /// + /// Whether the operation deletes data, so the Operations page asks the administrator's password again before it starts it (as the + /// other destructive pages do). Default: no. + /// + bool RequiresConfirmation => false; + + /// Runs it inside a scope already pinned to the repository. + /// A short human-readable result, such as the counts. + Task RunAsync(IServiceProvider services, CancellationToken cancellationToken); +} + +public enum AdminJobState +{ + Running, + Succeeded, + Failed, +} + +/// The last run of an operation on a repository. In memory: a restart forgets it. +public sealed class AdminJobStatus +{ + public string Operation { get; init; } = string.Empty; + + public string Repository { get; init; } = string.Empty; + + public AdminJobState State { get; internal set; } + + public string? Actor { get; init; } + + public DateTime Started { get; init; } + + public DateTime? Finished { get; internal set; } + + /// The result on success, the exception type and message on failure. + public string? Message { get; internal set; } +} + +/// +/// Runs s in the background, one at a time per operation and repository, and keeps +/// the last status of each. Starting is refused while the is closed (throws +/// ), and every start and outcome is recorded with . +/// +public sealed class AdminJobService +{ + private readonly IServiceScopeFactory _scopes; + private readonly IEnumerable _operations; + private readonly MaintenanceGate? _gate; + private readonly IAdminAudit _audit; + private readonly SystemTime _time; + private readonly ILogger _logger; + private readonly IHostApplicationLifetime? _lifetime; + private readonly IJobLease? _lease; + private readonly ConcurrentDictionary<(string, string), AdminJobStatus> _status = new(); + private readonly ConcurrentDictionary<(string, string), Task> _running = new(); + private readonly object _lock = new(); + + public AdminJobService( + IServiceScopeFactory scopes, + IEnumerable operations, + IAdminAudit audit, + SystemTime time, + ILogger logger, + MaintenanceGate? gate = null, + IHostApplicationLifetime? lifetime = null, + IJobLease? lease = null) + { + _lease = lease; + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _operations = operations ?? throw new ArgumentNullException(nameof(operations)); + _audit = audit ?? throw new ArgumentNullException(nameof(audit)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _gate = gate; + _lifetime = lifetime; + } + + /// Every registered operation. + public IReadOnlyList Operations => _operations.ToList(); + + /// The last status of on , or null if never run. + public AdminJobStatus? Get(string operation, string repository) + => _status.TryGetValue(Key(operation, repository), out var status) ? status : null; + + /// + /// Starts on in the background. + /// + /// The . + /// The repository to run on. + /// The administrator starting it, for the audit record. + /// Why it was not started. + /// The gate is closed. + public bool TryStart(string operation, RepositoryInfo repository, string? actor, out string? refusal) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + _gate?.ThrowIfClosed(); + + var definition = _operations.FirstOrDefault(o => string.Equals(o.Name, operation, StringComparison.Ordinal)); + if (definition == null) + { + refusal = "Unknown operation."; + return false; + } + + if (!definition.AppliesTo(repository)) + { + refusal = $"{definition.Title} does not apply to {repository.Name}."; + return false; + } + + var key = Key(operation, repository.Name); + + // One run per operation and repository in the whole cluster, not only in this process. + var held = _lease.Acquire($"operation:{operation}:{key.Item2}"); + if (held == null) + { + refusal = $"{definition.Title} is already running on {repository.Name} (on another node)."; + return false; + } + + var status = new AdminJobStatus + { + Operation = definition.Name, + Repository = repository.Name, + State = AdminJobState.Running, + Actor = actor, + Started = _time.UtcNow, + }; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + lock (_lock) + { + if (_running.ContainsKey(key)) + { + held.Release(); + refusal = $"{definition.Title} is already running on {repository.Name}."; + return false; + } + + _status[key] = status; + _running[key] = completion.Task; + } + + _audit.Record(actor, $"operation.{definition.Name}.start", $"repository {repository.Name}"); + var stopping = _lifetime?.ApplicationStopping ?? CancellationToken.None; + _ = Task.Run(async () => + { + try + { + using var scope = _scopes.CreateRepositoryScope(repository); + var message = await definition.RunAsync(scope.ServiceProvider, stopping); + Finish(status, AdminJobState.Succeeded, message); + } + catch (Exception e) + { + _logger.LogError(e, "{Operation} on repository {Repository} failed", definition.Name, repository.Name); + Finish(status, AdminJobState.Failed, $"{e.GetType().Name}: {e.Message}"); + } + finally + { + _running.TryRemove(key, out _); + try { await held.DisposeAsync(); } catch (Exception) { /* the lease expires by itself */ } + completion.SetResult(true); + } + + _audit.Record(actor, $"operation.{definition.Name}.{status.State.ToString().ToLowerInvariant()}", $"repository {repository.Name}", status.Message); + }); + + refusal = null; + return true; + } + + /// Completes when the current run of on ends (immediately when none). + public Task WaitAsync(string operation, string repository) + => _running.TryGetValue(Key(operation, repository), out var task) ? task : Task.CompletedTask; + + private void Finish(AdminJobStatus status, AdminJobState state, string? message) + { + status.Message = message; + status.Finished = _time.UtcNow; + status.State = state; + } + + private static (string, string) Key(string operation, string repository) + => (operation, repository.ToLowerInvariant()); +} diff --git a/src/BaGet.Core/Operations/DownloadsImportOperation.cs b/src/BaGet.Core/Operations/DownloadsImportOperation.cs new file mode 100644 index 000000000..5c95f0884 --- /dev/null +++ b/src/BaGet.Core/Operations/DownloadsImportOperation.cs @@ -0,0 +1,26 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Core; + +/// The import downloads command as an . +public sealed class DownloadsImportOperation : IAdminOperation +{ + public string Name => "downloads-import"; + + public string Title => "Import download counts"; + + public string Description => "Imports the download counts from the configured downloads file into the repository's packages."; + + public bool IsAvailable(IServiceProvider services) + => services.GetRequiredService() is not NullContext; + + public async Task RunAsync(IServiceProvider services, CancellationToken cancellationToken) + { + await services.GetRequiredService().ImportAsync(cancellationToken).ConfigureAwait(false); + + return "Download counts imported."; + } +} diff --git a/src/BaGet.Core/Operations/IAdminAudit.cs b/src/BaGet.Core/Operations/IAdminAudit.cs new file mode 100644 index 000000000..23b8fc149 --- /dev/null +++ b/src/BaGet.Core/Operations/IAdminAudit.cs @@ -0,0 +1,32 @@ +using System; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// Records an administrator's action for the audit trail. This is the seam the access-audit table (access control +/// plan, U2) replaces: until then writes a log line. Implementations must not throw. +/// +public interface IAdminAudit +{ + /// The signed-in administrator's name, or null when not known. + /// A short verb phrase, e.g. validation.release. + /// What it was done to, e.g. repository default, Contoso.Lib 1.0.0. + /// Extra context, or null. + void Record(string? actor, string action, string subject, string? details = null); +} + +/// The default : one Information log line per action. +public sealed class LoggingAdminAudit : IAdminAudit +{ + private readonly ILogger _logger; + + public LoggingAdminAudit(ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + public void Record(string? actor, string action, string subject, string? details = null) + => _logger.LogInformation("Audit: {Actor} {Action} {Subject} {Details}", actor ?? "(unknown)", action, subject, details); +} diff --git a/src/BaGet.Core/Operations/IValidationAdministration.cs b/src/BaGet.Core/Operations/IValidationAdministration.cs new file mode 100644 index 000000000..5904727cb --- /dev/null +++ b/src/BaGet.Core/Operations/IValidationAdministration.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// Where a submission stands: still to run, or stopped without being indexed. +public enum ValidationSubmissionState +{ + Pending, + + /// A validator failed or indexing failed; the package stays staged for an administrator to decide. + Quarantined, +} + +/// One submission awaiting validation or quarantined. +public sealed record ValidationSubmissionSummary( + string SubmissionId, + string Repository, + string? PackageId, + string? PackageVersion, + ValidationSubmissionState State, + DateTime Created, + IReadOnlyList FailureMessages); + +/// +/// The administrator's view of the validation queue across every repository, and the three decisions on a stuck +/// submission. Every write throws while the gate is closed. +/// +public interface IValidationAdministration +{ + /// Whether validation can be administered (a relational database; false on Azure Table). + bool IsSupported { get; } + + /// Pending and quarantined submissions, oldest first. + Task> ListAsync(CancellationToken cancellationToken); + + /// Resets a submission's steps to pending and queues it again. + /// Null on success, else why not. + Task RetryAsync(string submissionId, string? actor, CancellationToken cancellationToken); + + /// + /// Indexes a quarantined package although validation failed. Audited. The failed steps keep their verdicts. + /// + /// Null on success, else why not. + Task ReleaseAsync(string submissionId, string? actor, CancellationToken cancellationToken); + + /// Deletes the staged file and the submission's rows. Audited. A pending submission can be rejected too (one that keeps failing would never leave the queue). + /// Null on success, else why not. + Task RejectAsync(string submissionId, string? actor, CancellationToken cancellationToken); +} diff --git a/src/BaGet.Core/PackageDatabase.cs b/src/BaGet.Core/PackageDatabase.cs index 98f5168cc..9aa728fed 100644 --- a/src/BaGet.Core/PackageDatabase.cs +++ b/src/BaGet.Core/PackageDatabase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -6,142 +6,351 @@ using Microsoft.EntityFrameworkCore; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageDatabase : IPackageDatabase { - public class PackageDatabase : IPackageDatabase + private const int MaxUpdateAttempts = 3; + + private readonly IContext _context; + + public PackageDatabase(IContext context) { - private readonly IContext _context; + _context = context ?? throw new ArgumentNullException(nameof(context)); + } - public PackageDatabase(IContext context) + public async Task AddAsync(Package package, CancellationToken cancellationToken) + { + try { - _context = context ?? throw new ArgumentNullException(nameof(context)); + _context.Packages?.Add(package); + + await _context.SaveChangesAsync(cancellationToken); + + return PackageAddResult.Success; + } + catch (DbUpdateException e) + when (_context.IsUniqueConstraintViolationException(e)) + { + return PackageAddResult.PackageAlreadyExists; } + } + + public async Task ExistsAsync(string? id, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + return await _context + .Packages + .Where(p => p.Id == id) + .AnyAsync(cancellationToken); + #pragma warning restore CS8604 + } + + public async Task ExistsAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + return await _context + .Packages + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) + .AnyAsync(cancellationToken); + #pragma warning restore CS8604 + } - public async Task AddAsync(Package package, CancellationToken cancellationToken) + public async Task> FindManyAsync( + IReadOnlyCollection ids, + bool includeUnlisted, + CancellationToken cancellationToken) + { + if (ids.Count == 0) { - try - { - _context.Packages.Add(package); + return new List(); + } - await _context.SaveChangesAsync(cancellationToken); + var idList = ids.ToList(); + #pragma warning disable CS8604 + var query = _context.Packages + .Include(p => p.Dependencies) + .Include(p => p.PackageTypes) + .Include(p => p.TargetFrameworks) + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .Where(p => idList.Contains(p.Id!)); + #pragma warning restore CS8604 - return PackageAddResult.Success; - } - catch (DbUpdateException e) - when (_context.IsUniqueConstraintViolationException(e)) - { - return PackageAddResult.PackageAlreadyExists; - } + if (!includeUnlisted) + { + query = query.Where(p => p.Listed); } - public async Task ExistsAsync(string id, CancellationToken cancellationToken) + return await query.ToListAsync(cancellationToken); + } + + public async Task> FindAsync(string? id, bool includeUnlisted, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var query = _context.Packages + .Include(p => p.Dependencies) + .Include(p => p.PackageTypes) + .Include(p => p.TargetFrameworks) + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .Where(p => p.Id == id); + #pragma warning restore CS8604 + + if (!includeUnlisted) { - return await _context - .Packages - .Where(p => p.Id == id) - .AnyAsync(cancellationToken); + query = query.Where(p => p.Listed); } - public async Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + return (await query.ToListAsync(cancellationToken)).AsReadOnly(); + } + + public Task FindOrNullAsync( + string? id, + NuGetVersion version, + bool includeUnlisted, + CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var query = _context.Packages + .Include(p => p.Dependencies) + .Include(p => p.TargetFrameworks) + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()); + #pragma warning restore CS8604 + + if (!includeUnlisted) { - return await _context - .Packages - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) - .AnyAsync(cancellationToken); + query = query.Where(p => p.Listed); } - public async Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken) + return query.FirstOrDefaultAsync(cancellationToken); + } + + public Task UnlistPackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + return TryUpdatePackageAsync(id, version, p => p.Listed = false, cancellationToken); + } + + public Task RelistPackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + return TryUpdatePackageAsync(id, version, p => p.Listed = true, cancellationToken); + } + + public async Task AddDownloadAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + try { - var query = _context.Packages - .Include(p => p.Dependencies) - .Include(p => p.PackageTypes) - .Include(p => p.TargetFrameworks) - .Where(p => p.Id == id); + await TryUpdatePackageAsync(id, version, p => p.Downloads += 1, cancellationToken, bestEffort: true); + } + catch (MaintenanceException) + { + // The counter is best effort: a read-only database must not stop a package from being served. + } + } - if (!includeUnlisted) - { - query = query.Where(p => p.Listed); - } + public async Task HardDeletePackageAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var package = await _context.Packages + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) + .Include(p => p.Dependencies) + .Include(p => p.TargetFrameworks) + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .FirstOrDefaultAsync(cancellationToken); + #pragma warning restore CS8604 - return (await query.ToListAsync(cancellationToken)).AsReadOnly(); + if (package == null) + { + return false; } - public Task FindOrNullAsync( - string id, - NuGetVersion version, - bool includeUnlisted, - CancellationToken cancellationToken) + // The package to dependency relationship is optional in the database, so EF would + // null the foreign key and leave these rows behind rather than delete them. + #pragma warning disable CS8604 + _context.PackageDependencies?.RemoveRange(package.Dependencies); + #pragma warning restore CS8604 + + // The same holds for a package's deprecation and vulnerabilities. + if (package.Deprecation != null) { - var query = _context.Packages - .Include(p => p.Dependencies) - .Include(p => p.TargetFrameworks) - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()); + _context.PackageDeprecations?.Remove(package.Deprecation); + } - if (!includeUnlisted) - { - query = query.Where(p => p.Listed); - } + #pragma warning disable CS8604 + _context.PackageVulnerabilities?.RemoveRange(package.Vulnerabilities); + #pragma warning restore CS8604 + _context.Packages.Remove(package); + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + public async Task SetDeprecationAsync( + string? id, + NuGetVersion version, + PackageDeprecation deprecation, + CancellationToken cancellationToken) + { + if (deprecation == null) throw new ArgumentNullException(nameof(deprecation)); + + var package = await FindForUpdateAsync(id, version, cancellationToken); + if (package == null) + { + return false; + } - return query.FirstOrDefaultAsync(cancellationToken); + // A version has at most one deprecation, so setting one replaces the last. + if (package.Deprecation != null) + { + _context.PackageDeprecations?.Remove(package.Deprecation); } - public Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + package.Deprecation = deprecation; + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + public async Task RemoveDeprecationAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken) + { + var package = await FindForUpdateAsync(id, version, cancellationToken); + if (package == null) { - return TryUpdatePackageAsync(id, version, p => p.Listed = false, cancellationToken); + return false; } - public Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + if (package.Deprecation != null) { - return TryUpdatePackageAsync(id, version, p => p.Listed = true, cancellationToken); + _context.PackageDeprecations?.Remove(package.Deprecation); + await _context.SaveChangesAsync(cancellationToken); } - public async Task AddDownloadAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + return true; + } + + public async Task SetVulnerabilitiesAsync( + string? id, + NuGetVersion version, + IReadOnlyList vulnerabilities, + CancellationToken cancellationToken) + { + if (vulnerabilities == null) throw new ArgumentNullException(nameof(vulnerabilities)); + + var package = await FindForUpdateAsync(id, version, cancellationToken); + if (package == null) { - await TryUpdatePackageAsync(id, version, p => p.Downloads += 1, cancellationToken); + return false; } - public async Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + // The list replaces the entries set by hand, so an empty list clears them; what the vulnerability scanner recorded + // (Source set) is the scanner's and stays until the next scan. + var manual = (package.Vulnerabilities ?? new List()).Where(v => v.Source == null).ToList(); + #pragma warning disable CS8604 + _context.PackageVulnerabilities?.RemoveRange(manual); + #pragma warning restore CS8604 + var scanned = (package.Vulnerabilities ?? new List()).Where(v => v.Source != null); + foreach (var vulnerability in vulnerabilities) vulnerability.Source = null; + package.Vulnerabilities = scanned.Concat(vulnerabilities).ToList(); + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + public async Task> GetAllVulnerabilitiesAsync( + CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + return await _context.PackageVulnerabilities + .Include(v => v.Package) + .Where(v => v.Package != null) + .AsNoTracking() + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + } + + private Task FindForUpdateAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + return _context.Packages + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) + .FirstOrDefaultAsync(cancellationToken); + #pragma warning restore CS8604 + } + + /// + /// Rows carry a concurrency token on SQL Server and MySQL, so a save racing another writer of the same row + /// (a download, an unlist) throws . The change is re-applied to a + /// fresh copy of the row up to times; then the exception is rethrown, or + /// dropped when (the download counter) is set. + /// + private async Task TryUpdatePackageAsync( + string? id, + NuGetVersion version, + Action action, + CancellationToken cancellationToken, + bool bestEffort = false) + { + for (var attempt = 1; ; attempt++) { + #pragma warning disable CS8604 var package = await _context.Packages .Where(p => p.Id == id) .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) - .Include(p => p.Dependencies) - .Include(p => p.TargetFrameworks) .FirstOrDefaultAsync(cancellationToken); + #pragma warning restore CS8604 if (package == null) { return false; } - _context.Packages.Remove(package); - await _context.SaveChangesAsync(cancellationToken); - - return true; - } - - private async Task TryUpdatePackageAsync( - string id, - NuGetVersion version, - Action action, - CancellationToken cancellationToken) - { - var package = await _context.Packages - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) - .FirstOrDefaultAsync(); + action(package); - if (package != null) + try { - action(package); await _context.SaveChangesAsync(cancellationToken); return true; } + catch (DbUpdateConcurrencyException e) + { + foreach (var entry in e.Entries) + { + entry.State = EntityState.Detached; + } - return false; + if (attempt < MaxUpdateAttempts) + { + continue; + } + + if (bestEffort) + { + return false; + } + + throw; + } } } } diff --git a/src/BaGet.Core/PackageService.cs b/src/BaGet.Core/PackageService.cs index 1f1763461..b54a182cd 100644 --- a/src/BaGet.Core/PackageService.cs +++ b/src/BaGet.Core/PackageService.cs @@ -1,149 +1,249 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageService : IPackageService { - public class PackageService : IPackageService + // Serialises the first fetch of one version, so a second request waits and finds it instead of failing. + private static readonly KeyedLocks Mirrors = new(); + + private readonly IPackageDatabase _db; + private readonly IUpstreamClient _upstream; + private readonly IPackageIndexingService _indexer; + private readonly ILogger _logger; + private readonly IRepositoryContext? _repository; + private readonly ArtifactUsageRecorder? _usage; + + public PackageService( + IPackageDatabase db, + IUpstreamClient upstream, + IPackageIndexingService indexer, + ILogger logger, + IRepositoryContext? repository = null, + ArtifactUsageRecorder? usage = null) { - private readonly IPackageDatabase _db; - private readonly IUpstreamClient _upstream; - private readonly IPackageIndexingService _indexer; - private readonly ILogger _logger; - - public PackageService( - IPackageDatabase db, - IUpstreamClient upstream, - IPackageIndexingService indexer, - ILogger logger) + _repository = repository; + _usage = usage; + _db = db ?? throw new ArgumentNullException(nameof(db)); + _upstream = upstream ?? throw new ArgumentNullException(nameof(upstream)); + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task> FindPackageVersionsAsync( + string id, + CancellationToken cancellationToken) + { + var upstreamVersions = await _upstream.ListPackageVersionsAsync(id, cancellationToken); + + // Merge the local package versions into the upstream package versions. + var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); + var localVersions = localPackages.Select(p => p.Version); + + if (!upstreamVersions.Any()) return localVersions.ToList(); + if (!localPackages.Any()) return upstreamVersions; + + return upstreamVersions.Concat(localVersions).Distinct().ToList(); + } + + public async Task> FindPackagesAsync(string id, CancellationToken cancellationToken) + { + var upstreamPackages = await _upstream.ListPackagesAsync(id, cancellationToken); + var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); + + if (!upstreamPackages.Any()) return localPackages; + if (!localPackages.Any()) return upstreamPackages; + + // Merge the local packages into the upstream packages. + var result = upstreamPackages.ToDictionary(p => p.Version); + var local = localPackages.ToDictionary(p => p.Version); + + foreach (var localPackage in local) { - _db = db ?? throw new ArgumentNullException(nameof(db)); - _upstream = upstream ?? throw new ArgumentNullException(nameof(upstream)); - _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + result[localPackage.Key] = localPackage.Value; } - public async Task> FindPackageVersionsAsync( - string id, - CancellationToken cancellationToken) + return result.Values.ToList(); + } + + public async Task FindPackageOrNullAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken) + { + if (await IsPassThroughAsync(cancellationToken)) { - var upstreamVersions = await _upstream.ListPackageVersionsAsync(id, cancellationToken); + var stored = await _db.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); + if (stored != null || id == null) return stored; - // Merge the local package versions into the upstream package versions. - var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); - var localVersions = localPackages.Select(p => p.Version); + var upstream = await _upstream.ListPackagesAsync(id, cancellationToken); - if (!upstreamVersions.Any()) return localVersions.ToList(); - if (!localPackages.Any()) return upstreamVersions; + return upstream.FirstOrDefault(p => p.Version == version); + } - return upstreamVersions.Concat(localVersions).Distinct().ToList(); + if (!await MirrorAsync(id, version, cancellationToken)) + { + return null; } - public async Task> FindPackagesAsync(string id, CancellationToken cancellationToken) + return await _db.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); + } + + public async Task ExistsAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + if (await IsPassThroughAsync(cancellationToken)) { - var upstreamPackages = await _upstream.ListPackagesAsync(id, cancellationToken); - var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); + if (await _db.ExistsAsync(id, version, cancellationToken)) return true; + if (id == null) return false; - if (!upstreamPackages.Any()) return localPackages; - if (!localPackages.Any()) return upstreamPackages; + return (await _upstream.ListPackageVersionsAsync(id, cancellationToken)).Contains(version); + } - // Merge the local packages into the upstream packages. - var result = upstreamPackages.ToDictionary(p => p.Version); - var local = localPackages.ToDictionary(p => p.Version); + return await MirrorAsync(id, version, cancellationToken); + } - foreach (var localPackage in local) - { - result[localPackage.Key] = localPackage.Value; - } + public async Task OpenUncachedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!await IsPassThroughAsync(cancellationToken)) return null; + if (await _db.ExistsAsync(id, version, cancellationToken)) return null; - return result.Values.ToList(); - } + _logger.LogInformation( + "Streaming package {PackageId} {PackageVersion} through from the upstream feed (not stored)", + id, + version); - public async Task FindPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) - { - if (!await MirrorAsync(id, version, cancellationToken)) - { - return null; - } + return await _upstream.DownloadPackageOrNullAsync(id, version, cancellationToken); + } - return await _db.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); - } + /// + /// What a request for this version would find in this repository, without fetching or storing anything: stored, or + /// held by its upstream (it would be fetched), or neither. The same two steps as (the + /// stored copy, then the upstream, whose own rules for offline mode and remembered answers + /// applies), so the resolution preview of a virtual repository cannot + /// disagree with a real download. + /// + public async Task ProbeAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + if (await _db.ExistsAsync(id, version, cancellationToken).ConfigureAwait(false)) return ResolutionOutcome.Stored; - public async Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + return await _upstream.ProbeAsync(id, version, cancellationToken).ConfigureAwait(false) switch { - return await MirrorAsync(id, version, cancellationToken); - } + UpstreamProbe.Available => ResolutionOutcome.WouldFetch, + UpstreamProbe.Offline => ResolutionOutcome.Offline, + UpstreamProbe.Unavailable => ResolutionOutcome.Unavailable, + _ => ResolutionOutcome.NotFound, + }; + } + + // The repository fetches from an upstream but keeps nothing (RemoteRepositorySettings.StoreLocally off). + private async Task IsPassThroughAsync(CancellationToken cancellationToken) + => _upstream is IPassThroughUpstreamClient passThrough + && await passThrough.IsPassThroughAsync(cancellationToken); + + public async Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken) + { + await _db.AddDownloadAsync(packageId, version, cancellationToken); - public async Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken) + // When the version was last downloaded, for the retention rules (kept in memory, written in batches). + _usage?.Touch((_repository?.Current ?? RepositoryInfo.Default).Key, packageId, version.ToNormalizedString()); + + BaGetDiagnostics.Downloads.Add(1); + } + + /// + /// Index the package from an upstream if it does not exist locally. + /// + /// The package ID to index from an upstream. + /// The package version to index from an upstream. + /// + /// True if the package exists locally or was indexed from an upstream source. + private async Task MirrorAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + if (await _db.ExistsAsync(id, version, cancellationToken)) { - await _db.AddDownloadAsync(packageId, version, cancellationToken); + return true; } - /// - /// Index the package from an upstream if it does not exist locally. - /// - /// The package ID to index from an upstream. - /// The package version to index from an upstream. - /// - /// True if the package exists locally or was indexed from an upstream source. - private async Task MirrorAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + var key = $"{(_repository?.Current ?? RepositoryInfo.Default).Key}|{id?.ToLowerInvariant()}|{version.ToNormalizedString()}"; + + using (await Mirrors.LockAsync(key, cancellationToken)) { + // A request that held the lock before us may have indexed it already. if (await _db.ExistsAsync(id, version, cancellationToken)) { return true; } - _logger.LogInformation( - "Package {PackageId} {PackageVersion} does not exist locally. Checking upstream feed...", - id, - version); + return await MirrorLockedAsync(id, version, cancellationToken); + } + } + + private async Task MirrorLockedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + _logger.LogInformation( + "Package {PackageId} {PackageVersion} does not exist locally. Checking upstream feed...", + id, + version); + + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.MirrorFetch); + activity?.SetTag(BaGetDiagnostics.Tags.PackageId, id); + activity?.SetTag(BaGetDiagnostics.Tags.PackageVersion, version.ToNormalizedString()); - try + try + { + using (var packageStream = await _upstream.DownloadPackageOrNullAsync(id, version, cancellationToken)) { - using (var packageStream = await _upstream.DownloadPackageOrNullAsync(id, version, cancellationToken)) + if (packageStream == null) { - if (packageStream == null) - { - _logger.LogWarning( - "Upstream feed does not have package {PackageId} {PackageVersion}", - id, - version); - return false; - } - - _logger.LogInformation( - "Downloaded package {PackageId} {PackageVersion}, indexing...", + activity?.SetTag(BaGetDiagnostics.Tags.Result, "NotFound"); + _logger.LogWarning( + "Upstream feed does not have package {PackageId} {PackageVersion}", id, version); + return false; + } - var result = await _indexer.IndexAsync(packageStream, cancellationToken); + _logger.LogInformation( + "Downloaded package {PackageId} {PackageVersion}, indexing...", + id, + version); - _logger.LogInformation( - "Finished indexing package {PackageId} {PackageVersion} from upstream feed with result {Result}", - id, - version, - result); + var result = await _indexer.IndexAsync(packageStream, cancellationToken); - return result == PackageIndexingResult.Success; - } - } - catch (Exception e) - { - _logger.LogError( - e, - "Failed to index package {PackageId} {PackageVersion} from upstream", + _logger.LogInformation( + "Finished indexing package {PackageId} {PackageVersion} from upstream feed with result {Result}", id, - version); + version, + result); + + activity?.SetTag(BaGetDiagnostics.Tags.Result, result.ToString()); - return false; + // Another node (or a push) may have stored it between our check and the index: it exists, so serve it. + return result == PackageIndexingResult.Success + || (result == PackageIndexingResult.PackageAlreadyExists + && await _db.ExistsAsync(id, version, cancellationToken)); } } + catch (Exception e) when (e is not MaintenanceException) + { + // A closed MaintenanceGate is not a failed fetch: it propagates so the caller answers 503 + Retry-After + // (and a virtual repository does not fall through to its next member). + BaGetDiagnostics.Fail(activity, e); + + _logger.LogError( + e, + "Failed to index package {PackageId} {PackageVersion} from upstream", + id, + version); + + return false; + } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/README.md b/src/BaGet.Core/README.md new file mode 100644 index 000000000..b718aee76 --- /dev/null +++ b/src/BaGet.Core/README.md @@ -0,0 +1,45 @@ +# Extension.BaGet.Core + +The core libraries of [BaGet Extension](https://pieroviano.github.io/BaGet/): domain entities, options, indexing, +storage, search and mirroring. Every other BaGet package depends on it. + +```powershell +dotnet add package Extension.BaGet.Core +``` + +## Extension points + +| Type / method | Use | +|---|---| +| `BaGetApplication` | Passed to `AddBaGetWebApplication`; provider packages add `AddXyz()` extensions to it | +| `AddFileStorage()`, `AddNullStorage()`, `AddNullSearch()` | Built-in storage and search providers | +| `IStorageService`, `IPackageDatabase`, `ISearchService`, `ISearchIndexer` | Subsystems resolved at runtime through `IProvider` chains, chosen by `Storage:Type`, `Database:Type`, `Search:Type` | +| `IPackageAuthorizationService` | Push/delete authorization; accounts plug in here | +| `IDatabaseContextFactory` | Opens an `IContext` on any connection string; each relational provider registers one (none for Azure Table). Used by the Settings page's database copy | +| `MaintenanceGate` | In-memory read-only switch: while closed, `MaintenanceSaveChangesInterceptor` makes `SaveChanges` throw `MaintenanceException`. `AllowWrites(builder)` exempts a context | +| `IPackageChangeHandler` | Told about every package change (catalog, validation) | +| `IServiceIndexResourceProvider` | Adds resources to the service index | +| `AddBaGetOptions(section)` | Binds an options type and records it in the settings schema | + +## Folders + +| Folder | Content | +|---|---| +| Authentication | API key authentication, `IPackageAuthorizationService` | +| Configuration | Options (`BaGetOptions`, `AccountsOptions`, `ValidationOptions`, ...) | +| Content | Serves package content | +| Entities | Database model shared by every database provider; `IContext` (incl. `BeginKeyedInsertAsync`/`EndKeyedInsertAsync` for explicit-key inserts), the read-only gate, and `Entities/Copy` (`DatabaseCopyService`: dependency-ordered, batched, verified copy to another database) | +| Indexing | Package and symbol upload, `IPackageChangeHandler` | +| Metadata | Registration (package metadata) responses | +| Repositories | `Repository`, `Project`, `IRepositoryContext` (the repository in effect, scoped), `IRepositoryService`, `RepositoryNames` | +| Search | Package search | +| ServiceIndex | Service index, `IServiceIndexResourceProvider` | +| Staging | `IPackageStagingService`: holds a browser upload (`/upload`) between preview and confirmation | +| Statistics | Feed-wide download statistics | +| Storage | Package and symbol content storage | +| Upstream | Upstream NuGet feed interactions, for mirroring | +| Validation | Validation of BaGet's own configuration (package validation is in `Extension.BaGet.Validation`) | + +## Links + +[Documentation](https://pieroviano.github.io/BaGet/) · [Architecture](https://pieroviano.github.io/BaGet/advanced/architecture/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Core/Replication/DockerReplicator.cs b/src/BaGet.Core/Replication/DockerReplicator.cs new file mode 100644 index 000000000..44e399986 --- /dev/null +++ b/src/BaGet.Core/Replication/DockerReplicator.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Docker's . An item is a tag of an image (name = the image, version = the tag, digest = the +/// manifest's digest, which is equal on two servers holding the same image, so a tag that points at different manifests is a conflict). +/// Replicating a tag copies the manifest or index, its child manifests and every blob they use that the receiver does not hold, through +/// the Distribution Spec the peer speaks (HEAD a blob, monolithic POST …/blobs/uploads/?digest=, PUT manifests children +/// first, the tag last). Blobs are streamed from the store to the socket (or the other way); memory is never a layer. Referrers and +/// untagged manifests are not replicated unless a tagged index names them. Deleting a tag at the peer is DELETE …/manifests/{tag}. +/// +public sealed class DockerReplicator : IFormatReplicator +{ + private static readonly string[] ManifestTypes = OciNames.ImageManifestTypes.Concat(OciNames.IndexTypes).ToArray(); + + private readonly IContext _context; + private readonly IOciRegistry _registry; + private readonly IScanGate _scanGate; + + public DockerReplicator(IContext context, IOciRegistry registry, IScanGate scanGate) + { + _scanGate = scanGate ?? throw new ArgumentNullException(nameof(scanGate)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Docker; + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + var rows = await (from t in _context.OciTags!.AsNoTracking() + join m in _context.OciManifests!.AsNoTracking() on t.ManifestKey equals m.Key + join i in _context.OciRepositories!.AsNoTracking() on m.ImageKey equals i.Key + select new { Image = i.Name, Tag = t.Name, m.Digest, m.Size }).ToListAsync(cancellationToken).ConfigureAwait(false); + + return rows + .Select(r => new ReplicaItem(r.Image!, r.Tag!, string.Empty, r.Size, r.Digest ?? string.Empty)) + .OrderBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Version, StringComparer.Ordinal) + .ToList(); + } + + /// A tag is moved by the manifest PUT, so a replacing push deletes nothing at the peer first. + public bool PushReplacesInPlace => true; + + private static Uri Url(ReplicationPeer peer, ReplicaItem item, string tail) => peer.Root($"v2/{Uri.EscapeDataString(peer.Repository)}/{item.Name}/{tail}"); + + /// + public async Task PushAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + var root = await _registry.GetManifestAsync(item.Name, item.Version, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException($"The tag {item} is listed but its manifest is no longer stored."); + + // Children and blobs first, then the document that names them, the tag last (the receiver checks references). + var order = new List(); + await CollectLocalAsync(item, root, order, cancellationToken).ConfigureAwait(false); + + long sent = 0; + var pushedBlobs = new HashSet(StringComparer.Ordinal); + foreach (var manifest in order) + { + var parsed = OciManifestParser.Parse(manifest.MediaType, manifest.Content); + foreach (var digest in parsed.BlobDigests) + { + if (pushedBlobs.Add(digest)) sent += await PushBlobAsync(item, peer, digest, cancellationToken).ConfigureAwait(false); + } + + var reference = ReferenceEquals(manifest, root) ? item.Version : manifest.Digest; + var put = new HttpRequestMessage(HttpMethod.Put, Url(peer, item, "manifests/" + Uri.EscapeDataString(reference))) { Content = new ByteArrayContent(manifest.Content) }; + put.Content.Headers.ContentType = new MediaTypeHeaderValue(manifest.MediaType); + await ReplicationTransfer.SendAsync(peer, put, "manifest push", item, cancellationToken).ConfigureAwait(false); + sent += manifest.Content.Length; + } + + return sent; + } + + private async Task CollectLocalAsync(ReplicaItem item, OciManifestContent manifest, List order, CancellationToken cancellationToken) + { + var parsed = OciManifestParser.Parse(manifest.MediaType, manifest.Content); + foreach (var child in parsed.Children) + { + var content = await _registry.GetManifestAsync(item.Name, child.Descriptor.Digest, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException($"The index {item} names the manifest {child.Descriptor.Digest}, which is not stored."); + if (order.All(m => m.Digest != content.Digest)) await CollectLocalAsync(item, content, order, cancellationToken).ConfigureAwait(false); + } + + order.Add(manifest); + } + + private async Task PushBlobAsync(ReplicaItem item, ReplicationPeer peer, string digest, CancellationToken cancellationToken) + { + using (var head = await peer.SendAsync(new HttpRequestMessage(HttpMethod.Head, Url(peer, item, "blobs/" + digest)), HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false)) + { + if (head.IsSuccessStatusCode) return 0; + } + + using var blob = await _registry.OpenBlobAsync(item.Name, digest, 0, null, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException($"The blob {digest} of {item} is not stored."); + var content = new StreamContent(blob.Content, 81920); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + content.Headers.ContentLength = blob.Length; + var post = new HttpRequestMessage(HttpMethod.Post, Url(peer, item, "blobs/uploads/?digest=" + Uri.EscapeDataString(digest))) { Content = content }; + await ReplicationTransfer.SendAsync(peer, post, "blob push", item, cancellationToken).ConfigureAwait(false); + + return blob.Length; + } + + /// + public async Task PullAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + var root = await GetPeerManifestAsync(item, peer, item.Version, cancellationToken).ConfigureAwait(false); + + var order = new List(); + await CollectPeerAsync(item, peer, root, order, cancellationToken).ConfigureAwait(false); + + long received = 0; + var pulledBlobs = new HashSet(StringComparer.Ordinal); + foreach (var manifest in order) + { + var parsed = OciManifestParser.Parse(manifest.MediaType, manifest.Content); + foreach (var digest in parsed.BlobDigests) + { + if (pulledBlobs.Add(digest)) received += await PullBlobAsync(item, peer, digest, cancellationToken).ConfigureAwait(false); + } + + var reference = ReferenceEquals(manifest, root) ? item.Version : manifest.Digest; + OciManifestPut put; + try + { + put = await _registry.PutManifestAsync(item.Name, reference, manifest.MediaType, manifest.Content, cancellationToken).ConfigureAwait(false); + } + catch (OciException e) + { + throw new ReplicationItemException($"Storing {item} failed: {e.Message}", inner: e); + } + + // The same rule as a push to the registry: an image is judged once stored (and a scan queued when nothing refuses it), and a + // refused one is taken back. Indexes and artifacts whose config is not an image config are not images (`subject`/`artifactType` are ignored). + if (DockerFormatScanner.IsImage(manifest.MediaType, System.Text.Encoding.UTF8.GetString(manifest.Content))) + { + try + { + await _scanGate.CheckStoredAsync(item.Name, put.Digest, cancellationToken).ConfigureAwait(false); + } + catch (ScanBlockedException e) + { + await OciPushUndo.UndoAsync(_registry, item.Name, reference, put).ConfigureAwait(false); + + throw new ReplicationItemException($"The scanning policy refused {item}: {e.Message}", inner: e); + } + } + + received += manifest.Content.Length; + } + + return received; + } + + private static async Task GetPeerManifestAsync(ReplicaItem item, ReplicationPeer peer, string reference, CancellationToken cancellationToken) + { + using var response = await ReplicationTransfer.GetAsync(peer, Url(peer, item, "manifests/" + Uri.EscapeDataString(reference)), item, cancellationToken, + r => { foreach (var type in ManifestTypes) r.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(type)); }).ConfigureAwait(false); + var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); + var mediaType = response.Content.Headers.ContentType?.MediaType ?? string.Empty; + var digest = OciNames.DigestOf(Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant()); + + return new OciManifestContent(digest, mediaType, bytes, null, null, DateTime.UtcNow); + } + + private static async Task CollectPeerAsync(ReplicaItem item, ReplicationPeer peer, OciManifestContent manifest, List order, CancellationToken cancellationToken) + { + OciParsedManifest parsed; + try + { + parsed = OciManifestParser.Parse(manifest.MediaType, manifest.Content); + } + catch (OciException e) + { + throw new ReplicationItemException($"The peer's manifest of {item} is not valid: {e.Message}", inner: e); + } + + foreach (var child in parsed.Children) + { + if (order.Any(m => m.Digest == child.Descriptor.Digest)) continue; + + var content = await GetPeerManifestAsync(item, peer, child.Descriptor.Digest, cancellationToken).ConfigureAwait(false); + await CollectPeerAsync(item, peer, content, order, cancellationToken).ConfigureAwait(false); + } + + order.Add(manifest); + } + + private async Task PullBlobAsync(ReplicaItem item, ReplicationPeer peer, string digest, CancellationToken cancellationToken) + { + // A first pull of an image: the image does not exist locally yet, so it holds no blob. + if (await _registry.ImageExistsAsync(item.Name, cancellationToken).ConfigureAwait(false) + && await _registry.GetBlobInfoAsync(item.Name, digest, cancellationToken).ConfigureAwait(false) != null) + { + return 0; + } + + using var response = await ReplicationTransfer.GetAsync(peer, Url(peer, item, "blobs/" + digest), item, cancellationToken).ConfigureAwait(false); + await using var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using var spooled = await ReplicationTransfer.SpoolAsync(body, cancellationToken).ConfigureAwait(false); + try + { + await _registry.PutBlobAsync(item.Name, digest, spooled, cancellationToken).ConfigureAwait(false); + } + catch (OciException e) + { + throw new ReplicationItemException($"Storing the blob {digest} of {item} failed: {e.Message}", inner: e); + } + + return spooled.Length; + } + + /// + /// A tag is not immutable: pulling the peer's manifest moves it, and a refused image puts the previous manifest back + /// (), so nothing is deleted first. + /// + public Task PullReplacingAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + => PullAsync(item, peer, cancellationToken); + + /// + public async Task DeleteLocalAsync(ReplicaItem item, CancellationToken cancellationToken) + => await _registry.DeleteTagAsync(item.Name, item.Version, cancellationToken).ConfigureAwait(false); + + /// + public async Task DeletePeerAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + var request = new HttpRequestMessage(HttpMethod.Delete, Url(peer, item, "manifests/" + Uri.EscapeDataString(item.Version))); + await ReplicationTransfer.SendAsync(peer, request, "tag delete", item, cancellationToken, allowNotFound: true).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Core/Replication/MavenReplicator.cs b/src/BaGet.Core/Replication/MavenReplicator.cs new file mode 100644 index 000000000..ba8aef9d0 --- /dev/null +++ b/src/BaGet.Core/Replication/MavenReplicator.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Maven's . An item is one file of a version ( is the file name, +/// the digest its SHA-256), so a version whose files arrive over several runs converges and a file stored with different content on +/// the two sides is a conflict. A push is the layout's own PUT of the file (the peer applies its release/snapshot policy: an +/// existing release file is a 409); a pull downloads the file and stores it through the repository's own deploy path. The generated +/// maven-metadata.xml and checksum files are never items (each server derives them). Deleting a file at the peer is the +/// layout's DELETE. +/// +public sealed class MavenReplicator : IFormatReplicator +{ + private readonly IContext _context; + private readonly MavenRepositoryService _repository; + + public MavenReplicator(IContext context, MavenRepositoryService repository) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Maven; + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + var rows = await (from f in _context.MavenFiles!.AsNoTracking() + join v in _context.MavenVersions!.AsNoTracking() on f.VersionKey equals v.Key + join a in _context.MavenArtifacts!.AsNoTracking() on v.ArtifactKey equals a.Key + select new { a.GroupId, a.ArtifactId, v.Version, f.FileName, f.Size, f.Sha256 }).ToListAsync(cancellationToken).ConfigureAwait(false); + + return rows + .Select(r => new ReplicaItem(MavenNames.ArtifactName(r.GroupId!, r.ArtifactId!), r.Version!, r.FileName!, r.Size, r.Sha256 ?? string.Empty)) + .OrderBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Version, StringComparer.Ordinal).ThenBy(i => i.Part, StringComparer.Ordinal) + .ToList(); + } + + /// + public async Task PushAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + var (group, artifact) = Split(item); + var path = MavenNames.ParsePath(MavenNames.ClientPath(group, artifact, item.Version, item.Part)) + ?? throw new ReplicationItemException($"{item} is not a valid Maven path."); + using var download = await _repository.OpenAsync(path, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException($"The file {item} is listed but no longer stored."); + using var file = await ReplicationTransfer.SpoolAsync(download.Content, cancellationToken).ConfigureAwait(false); + var length = file.Length; + + var request = new HttpRequestMessage(HttpMethod.Put, peer.Feed("maven/" + MavenNames.ClientPath(group, artifact, item.Version, item.Part))) { Content = ReplicationTransfer.Binary(file) }; + await ReplicationTransfer.SendAsync(peer, request, "deploy", item, cancellationToken).ConfigureAwait(false); + + return length; + } + + /// + public Task PullAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + => PullCoreAsync(item, peer, replace: false, cancellationToken); + + /// Fetches and judges the file (checksum, scanning policy) first; only then deletes the local copy and stores the peer's. + public Task PullReplacingAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + => PullCoreAsync(item, peer, replace: true, cancellationToken); + + private async Task PullCoreAsync(ReplicaItem item, ReplicationPeer peer, bool replace, CancellationToken cancellationToken) + { + var (group, artifact) = Split(item); + var relative = MavenNames.ClientPath(group, artifact, item.Version, item.Part); + var path = MavenNames.ParsePath(relative) ?? throw new ReplicationItemException($"{item} is not a valid Maven path."); + + using var response = await ReplicationTransfer.GetAsync(peer, peer.Feed("maven/" + relative), item, cancellationToken).ConfigureAwait(false); + await using var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using var spooled = await ReplicationTransfer.SpoolAsync(body, cancellationToken).ConfigureAwait(false); + var length = spooled.Length; + + if (item.Digest.Length > 0) + { + var actual = Convert.ToHexString(await SHA256.HashDataAsync(spooled, cancellationToken).ConfigureAwait(false)).ToLowerInvariant(); + spooled.Position = 0; + if (!string.Equals(actual, item.Digest, StringComparison.OrdinalIgnoreCase)) + { + throw new ReplicationItemException($"The file {item} arrived with another SHA-256 than the peer announced; it was not stored."); + } + } + + if (replace) + { + try + { + await _repository.PreflightReplacementAsync(path, spooled, cancellationToken).ConfigureAwait(false); + } + catch (ScanBlockedException e) + { + throw new ReplicationItemException($"The scanning policy refused {item}: {e.Message}", inner: e); + } + + await DeleteLocalAsync(item, cancellationToken).ConfigureAwait(false); + } + + var result = await _repository.PutAsync(BaGetPrincipal.Superuser, path, spooled, cancellationToken).ConfigureAwait(false); + if (!result.Succeeded) + { + throw new ReplicationItemException($"Storing {item} failed: {result.Message}", conflict: result.Status == MavenStatus.Conflict); + } + + return length; + } + + /// + public async Task DeleteLocalAsync(ReplicaItem item, CancellationToken cancellationToken) + { + var (group, artifact) = Split(item); + var result = await _repository.DeleteFileAsync(BaGetPrincipal.Superuser, new MavenCoordinate(group, artifact, item.Version), item.Part, cancellationToken).ConfigureAwait(false); + if (!result.Succeeded && result.Status != MavenStatus.NotFound) throw new ReplicationItemException($"Deleting {item} failed: {result.Message}"); + } + + /// + public async Task DeletePeerAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + var (group, artifact) = Split(item); + var request = new HttpRequestMessage(HttpMethod.Delete, peer.Feed("maven/" + MavenNames.ClientPath(group, artifact, item.Version, item.Part))); + await ReplicationTransfer.SendAsync(peer, request, "delete", item, cancellationToken, allowNotFound: true).ConfigureAwait(false); + } + + private static (string Group, string Artifact) Split(ReplicaItem item) + => MavenNames.TryParseArtifactName(item.Name, out var group, out var artifact) + ? (group, artifact) + : throw new ReplicationItemException($"'{item.Name}' is not a Maven group:artifact."); +} diff --git a/src/BaGet.Core/Replication/NpmReplicator.cs b/src/BaGet.Core/Replication/NpmReplicator.cs new file mode 100644 index 000000000..877bd5f40 --- /dev/null +++ b/src/BaGet.Core/Replication/NpmReplicator.cs @@ -0,0 +1,378 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// npm's . Items are versions; the digest is the tarball's integrity, so a version held with a +/// different tarball on the two sides is a conflict. A push is the registry's own publish (PUT {name} with the tarball as a +/// base64 attachment, streamed from a temporary file so memory is the metadata, never the tarball); a pull reads the peer's packument +/// and tarball like a client and publishes them locally. The dist-tags that point at a version travel with it; moving a tag later, +/// without a new version, is not replicated. Deleting a version at the peer is npm unpublish's own requests. +/// +public sealed class NpmReplicator : IFormatReplicator +{ + private const string Placeholder = "replica"; + + private readonly IContext _context; + private readonly NpmRegistryService _registry; + + public NpmReplicator(IContext context, NpmRegistryService registry) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.Npm; + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + var rows = await (from v in _context.NpmVersions!.AsNoTracking() + join p in _context.NpmPackages!.AsNoTracking() on v.PackageKey equals p.Key + select new { p.Name, v.Version, v.Integrity, v.TarballSize }).ToListAsync(cancellationToken).ConfigureAwait(false); + + return rows + .Select(r => new ReplicaItem(r.Name!, r.Version!, string.Empty, r.TarballSize, r.Integrity ?? string.Empty)) + .OrderBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Version, StringComparer.Ordinal) + .ToList(); + } + + /// + public async Task PushAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + var package = await _registry.GetPackageAsync(item.Name, cancellationToken).ConfigureAwait(false); + var version = package?.Versions.FirstOrDefault(v => v.Version == item.Version) + ?? throw new ReplicationItemException($"The version {item} is listed but no longer stored."); + var file = NpmNames.TarballFileName(item.Name, item.Version); + var opened = await _registry.OpenTarballAsync(item.Name, file, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException($"The tarball of {item} is missing from the store."); + await using var tarball = opened.Content; + + var tags = package!.DistTags.Where(t => t.Value == item.Version).Select(t => t.Key).OrderBy(t => t, StringComparer.Ordinal).ToList(); + var publishTag = tags.Count > 0 ? tags[0] : Placeholder; + + var manifest = (JsonObject)version.Manifest.DeepClone(); + manifest.Remove("_attachments"); + if (manifest["dist"] is JsonObject dist) dist.Remove("tarball"); + + long length; + using (var body = await BuildPublishBodyAsync(item, manifest, publishTag, file, tarball, cancellationToken).ConfigureAwait(false)) + { + var request = new HttpRequestMessage(HttpMethod.Put, peer.Feed("npm/" + Key(item.Name))) { Content = ReplicationTransfer.Binary(body.File, "application/json") }; + await ReplicationTransfer.SendAsync(peer, request, "publish", item, cancellationToken).ConfigureAwait(false); + length = body.TarballLength; + } + + // The other tags of this version, and the removal of the placeholder when nothing named the version. + foreach (var tag in tags.Skip(1)) + { + var set = new HttpRequestMessage(HttpMethod.Put, peer.Feed($"npm/-/package/{Key(item.Name)}/dist-tags/{Uri.EscapeDataString(tag)}")) + { + Content = new StringContent(JsonSerializer.Serialize(item.Version), Encoding.UTF8, "application/json"), + }; + await ReplicationTransfer.SendAsync(peer, set, "tag", item, cancellationToken).ConfigureAwait(false); + } + + if (tags.Count == 0) + { + var remove = new HttpRequestMessage(HttpMethod.Delete, peer.Feed($"npm/-/package/{Key(item.Name)}/dist-tags/{Placeholder}")); + await ReplicationTransfer.SendAsync(peer, remove, "tag removal", item, cancellationToken, allowNotFound: true).ConfigureAwait(false); + } + + return length; + } + + /// + public Task PullAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + => PullCoreAsync(item, peer, replace: false, cancellationToken); + + /// Fetches and judges the version (integrity, scanning policy) first; only then purges the local copy and stores the peer's. + public Task PullReplacingAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + => PullCoreAsync(item, peer, replace: true, cancellationToken); + + private async Task PullCoreAsync(ReplicaItem item, ReplicationPeer peer, bool replace, CancellationToken cancellationToken) + { + JsonObject packument; + using (var response = await ReplicationTransfer.GetAsync(peer, peer.Feed("npm/" + Key(item.Name)), item, cancellationToken, r => r.Headers.TryAddWithoutValidation("Accept", "application/json")).ConfigureAwait(false)) + { + packument = await response.Content.ReadJsonObjectAsync(cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException($"The peer's packument of {item.Name} is not a JSON object."); + } + + if ((packument["versions"] as JsonObject)?[item.Version] is not JsonObject manifest) + { + throw new ReplicationItemException($"The peer no longer has {item}."); + } + + var tags = (packument["dist-tags"] as JsonObject)? + .Where(t => t.Value is JsonValue v && v.TryGetValue(out var tagged) && tagged == item.Version) + .Select(t => t.Key).OrderBy(t => t, StringComparer.Ordinal).ToList() ?? new List(); + var publishTag = tags.Count > 0 ? tags[0] : Placeholder; + + var file = NpmNames.TarballFileName(item.Name, item.Version); + long length; + using (var response = await ReplicationTransfer.GetAsync(peer, peer.Feed($"npm/{Key(item.Name)}/-/{Uri.EscapeDataString(file)}"), item, cancellationToken).ConfigureAwait(false)) + { + await using var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using var spooled = await ReplicationTransfer.SpoolAsync(body, cancellationToken).ConfigureAwait(false); + length = spooled.Length; + + var dist = manifest["dist"] as JsonObject; + var integrity = item.Digest.Length > 0 ? item.Digest : dist?["integrity"] is JsonValue i && i.TryGetValue(out var text) ? text : null; + if (replace) + { + try + { + await _registry.PreflightReplacementAsync(item.Name, item.Version, (JsonObject)manifest.DeepClone(), spooled, integrity, cancellationToken).ConfigureAwait(false); + } + catch (ScanBlockedException e) + { + throw new ReplicationItemException($"The scanning policy refused {item}: {e.Message}", inner: e); + } + catch (InvalidDataException e) + { + throw new ReplicationItemException($"Storing {item} failed: {e.Message}", inner: e); + } + + await DeleteLocalAsync(item, cancellationToken).ConfigureAwait(false); + } + + var result = await _registry.PublishAsync( + BaGetPrincipal.Superuser, + new NpmPublication(item.Name, item.Version, (JsonObject)manifest.DeepClone(), publishTag, spooled, integrity), + cancellationToken).ConfigureAwait(false); + if (!result.Succeeded) + { + throw new ReplicationItemException($"Storing {item} failed: {result.Message}", conflict: result.Status == NpmStatus.Conflict); + } + } + + foreach (var tag in tags.Skip(1)) + { + await _registry.SetDistTagAsync(BaGetPrincipal.Superuser, item.Name, tag, item.Version, cancellationToken).ConfigureAwait(false); + } + + if (tags.Count == 0) await _registry.RemoveDistTagAsync(BaGetPrincipal.Superuser, item.Name, Placeholder, cancellationToken).ConfigureAwait(false); + + return length; + } + + /// + public async Task DeleteLocalAsync(ReplicaItem item, CancellationToken cancellationToken) + => await _registry.PurgeAsync(item.Name, item.Version, cancellationToken).ConfigureAwait(false); + + /// + public async Task DeletePeerAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + JsonObject packument; + using (var response = await peer.SendAsync(new HttpRequestMessage(HttpMethod.Get, peer.Feed("npm/" + Key(item.Name) + "?write=true")), HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false)) + { + if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return; + + await ReplicationPeer.EnsureAsync(response, "lookup", item).ConfigureAwait(false); + packument = await response.Content.ReadJsonObjectAsync(cancellationToken).ConfigureAwait(false) ?? new JsonObject(); + } + + var versions = packument["versions"] as JsonObject ?? new JsonObject(); + if (!versions.ContainsKey(item.Version)) return; + + var rev = packument["_rev"] is JsonValue r && r.TryGetValue(out var revision) ? revision : "0"; + var file = NpmNames.TarballFileName(item.Name, item.Version); + if (versions.Count == 1) + { + await ReplicationTransfer.SendAsync(peer, new HttpRequestMessage(HttpMethod.Delete, peer.Feed($"npm/{Key(item.Name)}/-rev/{Uri.EscapeDataString(rev)}")), "unpublish", item, cancellationToken, allowNotFound: true).ConfigureAwait(false); + + return; + } + + versions.Remove(item.Version); + var tags = packument["dist-tags"] as JsonObject ?? new JsonObject(); + foreach (var tag in tags.Where(t => t.Value is JsonValue v && v.TryGetValue(out var tagged) && tagged == item.Version).Select(t => t.Key).ToList()) tags.Remove(tag); + var put = new HttpRequestMessage(HttpMethod.Put, peer.Feed($"npm/{Key(item.Name)}/-rev/{Uri.EscapeDataString(rev)}")) + { + Content = new StringContent(packument.ToJsonString(), Encoding.UTF8, "application/json"), + }; + await ReplicationTransfer.SendAsync(peer, put, "unpublish", item, cancellationToken).ConfigureAwait(false); + await ReplicationTransfer.SendAsync(peer, new HttpRequestMessage(HttpMethod.Delete, peer.Feed($"npm/{Key(item.Name)}/-/{Uri.EscapeDataString(file)}/-rev/{Uri.EscapeDataString(rev)}")), "unpublish", item, cancellationToken, allowNotFound: true).ConfigureAwait(false); + } + + // The scope's slash travels as %2f (what npm sends and what the registry routes). + private static string Key(string name) => name.Replace("/", "%2f", StringComparison.Ordinal); + + private sealed class PublishBody : IDisposable + { + public PublishBody(FileStream file, long tarballLength) + { + File = file; + TarballLength = tarballLength; + } + + public FileStream File { get; } + + public long TarballLength { get; } + + public void Dispose() => File.Dispose(); + } + + // The publish document with the tarball inlined as base64, written to a temporary file in one pass: the JSON around it is small, + // the base64 goes through a streaming transform, so the tarball is never held in memory. + private static async Task BuildPublishBodyAsync(ReplicaItem item, JsonObject manifest, string tag, string file, Stream tarball, CancellationToken cancellationToken) + { + var path = Path.Combine(Path.GetTempPath(), "baget-replication-" + Guid.NewGuid().ToString("N")); + var output = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 81920, FileOptions.Asynchronous | FileOptions.DeleteOnClose); + try + { + var name = JsonSerializer.Serialize(item.Name); + var prefix = $"{{\"_id\":{name},\"name\":{name},\"dist-tags\":{{{JsonSerializer.Serialize(tag)}:{JsonSerializer.Serialize(item.Version)}}}," + + $"\"versions\":{{{JsonSerializer.Serialize(item.Version)}:{manifest.ToJsonString()}}}," + + $"\"_attachments\":{{{JsonSerializer.Serialize(file)}:{{\"content_type\":\"application/octet-stream\",\"data\":\""; + var head = Encoding.UTF8.GetBytes(prefix); + await output.WriteAsync(head, cancellationToken).ConfigureAwait(false); + + long length = 0; + await using (var counting = new CountingStream(tarball)) + { + // Base64 in 3-byte groups: CryptoStream with ToBase64Transform flushes the final group on dispose. + await using (var base64 = new CryptoStream(new NonClosingStream(output), new ToBase64Transform(), CryptoStreamMode.Write)) + { + await counting.CopyToAsync(base64, 81920, cancellationToken).ConfigureAwait(false); + } + + length = counting.Count; + } + + var tail = Encoding.UTF8.GetBytes($"\",\"length\":{length}}}}}}}"); + await output.WriteAsync(tail, cancellationToken).ConfigureAwait(false); + await output.FlushAsync(cancellationToken).ConfigureAwait(false); + output.Position = 0; + + return new PublishBody(output, length); + } + catch + { + await output.DisposeAsync().ConfigureAwait(false); + + throw; + } + } + + private sealed class CountingStream : Stream + { + private readonly Stream _inner; + + public CountingStream(Stream inner) + { + _inner = inner; + } + + public long Count { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) + { + var read = _inner.Read(buffer, offset, count); + Count += read; + + return read; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = await _inner.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + Count += read; + + return read; + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + // The wrapped stream belongs to the caller. + protected override void Dispose(bool disposing) + { + } + } + + // A CryptoStream disposes what it writes to; the file is still needed. + private sealed class NonClosingStream : Stream + { + private readonly Stream _inner; + + public NonClosingStream(Stream inner) + { + _inner = inner; + } + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override void Flush() => _inner.Flush(); + + public override Task FlushAsync(CancellationToken cancellationToken) => _inner.FlushAsync(cancellationToken); + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => _inner.Write(buffer, offset, count); + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => _inner.WriteAsync(buffer, cancellationToken); + + protected override void Dispose(bool disposing) + { + } + } +} + +internal static class ReplicationJson +{ + public static async Task ReadJsonObjectAsync(this HttpContent content, CancellationToken cancellationToken) + { + await using var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + try + { + return await JsonNode.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false) as JsonObject; + } + catch (JsonException) + { + return null; + } + } +} diff --git a/src/BaGet.Core/Replication/NuGetReplicator.cs b/src/BaGet.Core/Replication/NuGetReplicator.cs new file mode 100644 index 000000000..a6f8976b6 --- /dev/null +++ b/src/BaGet.Core/Replication/NuGetReplicator.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// NuGet's . Items are package versions (id compared without regard to case, version normalized). A push +/// is the protocol's PUT api/v2/package with the peer's key in X-NuGet-ApiKey; a pull downloads the flat-container +/// .nupkg and submits it through the same pipeline a push uses (validation included). NuGet keeps no content digest, so two +/// servers holding the same id and version are taken to hold the same package (versions are immutable) and a conflict cannot be detected. +/// Deleting at the peer is the protocol's DELETE api/v2/package/{id}/{version}, which honours the peer's +/// PackageDeletionBehavior (an unlist leaves the version there). +/// +public sealed class NuGetReplicator : IFormatReplicator +{ + private readonly IContext _context; + private readonly IPackageStorageService _storage; + private readonly IPackageSubmissionService _submissions; + private readonly IPackageDeletionService _deletion; + private readonly MaintenanceGate _gate; + private readonly IScanGate _scanGate; + + public NuGetReplicator( + IContext context, + IPackageStorageService storage, + IPackageSubmissionService submissions, + IPackageDeletionService deletion, + MaintenanceGate gate, + IScanGate scanGate) + { + _scanGate = scanGate ?? throw new ArgumentNullException(nameof(scanGate)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _submissions = submissions ?? throw new ArgumentNullException(nameof(submissions)); + _deletion = deletion ?? throw new ArgumentNullException(nameof(deletion)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + } + + /// + public RepositoryFormat Format => RepositoryFormat.NuGet; + + /// + public StringComparer NameComparer => StringComparer.OrdinalIgnoreCase; + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + var rows = await _context.Packages!.AsNoTracking() + .Select(p => new { p.Id, p.NormalizedVersionString }) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return rows + .Select(r => new ReplicaItem(r.Id!, r.NormalizedVersionString!, string.Empty, 0, string.Empty)) + .OrderBy(i => i.Name, StringComparer.OrdinalIgnoreCase).ThenBy(i => i.Version, StringComparer.Ordinal) + .ToList(); + } + + /// + public async Task PushAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + using var stored = await _storage.GetPackageStreamAsync(item.Name, NuGetVersion.Parse(item.Version), cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException($"The package {item} is listed but its file is not in the store."); + using var file = await ReplicationTransfer.SpoolAsync(stored, cancellationToken).ConfigureAwait(false); + var length = file.Length; + + var request = new HttpRequestMessage(HttpMethod.Put, peer.Feed("api/v2/package")) { Content = ReplicationTransfer.Binary(file) }; + peer.AddCredentials(request); + await ReplicationTransfer.SendAsync(peer, request, "push", item, cancellationToken).ConfigureAwait(false); + + return length; + } + + /// + public Task PullAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + => PullCoreAsync(item, peer, replace: false, cancellationToken); + + /// Downloads and judges the package (scanning policy) first; only then removes the local copy and submits the peer's. + public Task PullReplacingAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + => PullCoreAsync(item, peer, replace: true, cancellationToken); + + private async Task PullCoreAsync(ReplicaItem item, ReplicationPeer peer, bool replace, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + + var id = item.Name.ToLowerInvariant(); + var version = item.Version.ToLowerInvariant(); + using var response = await ReplicationTransfer.GetAsync(peer, peer.Feed($"v3/package/{Uri.EscapeDataString(id)}/{Uri.EscapeDataString(version)}/{Uri.EscapeDataString(id)}.{Uri.EscapeDataString(version)}.nupkg"), item, cancellationToken).ConfigureAwait(false); + await using var body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + using var file = await ReplicationTransfer.SpoolAsync(body, cancellationToken).ConfigureAwait(false); + var length = file.Length; + + // A push checks the scanning policy before it stores; a pull must refuse the same packages. + if (_scanGate.Enabled && await _scanGate.BlocksDeploysAsync(cancellationToken).ConfigureAwait(false)) + { + var components = NuGetScanComponents.TryRead(file); + if (components != null) + { + try + { + await _scanGate.CheckDeployAsync(components, cancellationToken).ConfigureAwait(false); + } + catch (ScanBlockedException e) + { + throw new ReplicationItemException($"The scanning policy refused {item}: {e.Message}", inner: e); + } + } + } + + if (replace) await DeleteLocalAsync(item, cancellationToken).ConfigureAwait(false); + + var result = await _submissions.SubmitAsync(file, cancellationToken).ConfigureAwait(false); + switch (result) + { + case PackageIndexingResult.Success: + case PackageIndexingResult.Accepted: + return length; + + case PackageIndexingResult.PackageAlreadyExists: + throw new ReplicationItemException($"The package {item} exists already.", conflict: true); + + default: + throw new ReplicationItemException($"The package {item} from the peer is not a valid package."); + } + } + + /// + public async Task DeleteLocalAsync(ReplicaItem item, CancellationToken cancellationToken) + => await _deletion.TryHardDeletePackageAsync(item.Name, NuGetVersion.Parse(item.Version), cancellationToken).ConfigureAwait(false); + + /// + public async Task DeletePeerAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + var request = new HttpRequestMessage(HttpMethod.Delete, peer.Feed($"api/v2/package/{Uri.EscapeDataString(item.Name)}/{Uri.EscapeDataString(item.Version)}")); + peer.AddCredentials(request); + await ReplicationTransfer.SendAsync(peer, request, "delete", item, cancellationToken, allowNotFound: true).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Core/Replication/ReplicationAdministration.cs b/src/BaGet.Core/Replication/ReplicationAdministration.cs new file mode 100644 index 000000000..01a6c0131 --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationAdministration.cs @@ -0,0 +1,407 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// What the administrator types to create or change a replication. 0 creates. +/// The configuration, or 0. +/// Its unique name. +/// The local repository. +/// Push or pull. +/// The peer server's base address. +/// The peer's repository (default or its name). +/// The peer's API key. Null or empty keeps the stored one (changing the peer's address drops it). +/// Forget the stored key (an anonymous peer). +/// Whether runs are allowed. +/// Push only: start a run after a deploy to the local repository. +/// Run every this many minutes, or null. +/// Delete at the target what was copied and is deleted at the source. +/// What happens when both sides hold the item with different content. +public sealed record ReplicationInput( + int Key, + string? Name, + string? Repository, + ReplicationDirection Direction, + string? PeerUrl, + string? PeerRepository, + string? ApiKey, + bool ClearApiKey, + bool Enabled, + bool OnDeploy, + int? ScheduleMinutes, + bool PropagateDeletes, + ReplicationConflict Conflict); + +/// A configuration with the names the page shows; the API key is never part of it. +/// The configuration (its must not be shown). +/// The local repository's name, or null when it no longer exists. +/// Its format. +/// Whether a key is stored. +/// The newest log entry, or null. +public sealed record ReplicationConfigView(ReplicationConfig Config, string? Repository, RepositoryFormat? Format, bool HasApiKey, ReplicationRun? LastRun); + +/// What found. +/// Whether the peer answered as a BaGet server with this repository. +/// A sentence for the administrator (never the key). +/// How long it took. +/// The peer repository's format, when it answered. +/// How many items it holds, when it answered. +public sealed record ReplicationTestResult(bool Ok, string Message, long ElapsedMilliseconds, RepositoryFormat? PeerFormat, int? PeerItems); + +/// +/// Manages replication configurations and reads their log. Every change calls and is +/// audited (, in the same save). Authorization is the caller's (the administrator pages and API). Starting a +/// run is . +/// +public interface IReplicationAdministration +{ + /// Every configuration, by name. + Task> ListAsync(CancellationToken cancellationToken); + + /// One configuration, or null. + Task GetAsync(int key, CancellationToken cancellationToken); + + /// Creates ( 0) or changes a configuration. + /// The input is not valid. + Task SaveAsync(ReplicationInput input, string? actor, CancellationToken cancellationToken); + + /// Deletes a configuration with its log and ledger (what it copied stays). + /// A run is going. + Task DeleteAsync(int key, string? actor, CancellationToken cancellationToken); + + /// The log of a configuration, newest first. + Task> ListRunsAsync(int configKey, int take, CancellationToken cancellationToken); + + /// One log entry, or null. + Task GetRunAsync(int runKey, CancellationToken cancellationToken); + + /// + /// Asks the peer for its inventory summary with the typed (or, for a stored configuration, saved) settings; saves nothing. A stored key + /// is sent only while the peer's origin is unchanged. + /// + Task TestAsync(ReplicationInput input, CancellationToken cancellationToken); +} + +/// over the relational database. +public sealed class ReplicationAdministration : IReplicationAdministration +{ + private readonly IContext _context; + private readonly IServiceProvider _services; + private readonly IReplicationPeerFactory _peers; + private readonly RemoteSettingsCodec _codec; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ReplicationJobs? _jobs; + private readonly IOptions? _remoteOptions; + + public ReplicationAdministration( + IContext context, + IServiceProvider services, + IReplicationPeerFactory peers, + RemoteSettingsCodec codec, + SystemTime time, + MaintenanceGate gate, + ReplicationJobs? jobs = null, + IOptions? remoteOptions = null) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + _peers = peers ?? throw new ArgumentNullException(nameof(peers)); + _codec = codec ?? throw new ArgumentNullException(nameof(codec)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _jobs = jobs; + _remoteOptions = remoteOptions; + } + + private IContext Db => _context is NullContext ? throw new ReplicationException("Replication needs a relational database.") : _context; + + private bool BlockPrivate => _remoteOptions?.Value?.BlockPrivateAddresses == true; + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + var configs = await Db.ReplicationConfigs!.AsNoTracking().OrderBy(c => c.Name).ToListAsync(cancellationToken).ConfigureAwait(false); + + return await ViewsAsync(configs, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task GetAsync(int key, CancellationToken cancellationToken) + { + var config = await Db.ReplicationConfigs!.AsNoTracking().FirstOrDefaultAsync(c => c.Key == key, cancellationToken).ConfigureAwait(false); + + return config == null ? null : (await ViewsAsync(new[] { config }, cancellationToken).ConfigureAwait(false)).Single(); + } + + private async Task> ViewsAsync(IReadOnlyList configs, CancellationToken cancellationToken) + { + var repositories = await Db.Repositories!.AsNoTracking().Select(r => new { r.Key, r.Name, r.Format }).ToListAsync(cancellationToken).ConfigureAwait(false); + var keys = configs.Select(c => c.Key).ToList(); + var runs = await Db.ReplicationRuns!.AsNoTracking().Where(r => keys.Contains(r.ConfigKey)).ToListAsync(cancellationToken).ConfigureAwait(false); + var last = runs.GroupBy(r => r.ConfigKey).ToDictionary(g => g.Key, g => g.OrderByDescending(r => r.Started).ThenByDescending(r => r.Key).First()); + + return configs.Select(c => + { + var repository = repositories.FirstOrDefault(r => r.Key == c.RepositoryKey); + + return new ReplicationConfigView(Redact(c), repository?.Name, repository?.Format, !string.IsNullOrEmpty(c.ProtectedApiKey), last.TryGetValue(c.Key, out var run) ? run : null); + }).ToList(); + } + + // A copy without the protected key: a view must never carry it to a page or the API. + private static ReplicationConfig Redact(ReplicationConfig c) => new() + { + Key = c.Key, + Name = c.Name, + RepositoryKey = c.RepositoryKey, + Direction = c.Direction, + PeerUrl = c.PeerUrl, + PeerRepository = c.PeerRepository, + ProtectedApiKey = null, + Enabled = c.Enabled, + OnDeploy = c.OnDeploy, + ScheduleMinutes = c.ScheduleMinutes, + PropagateDeletes = c.PropagateDeletes, + Conflict = c.Conflict, + ScheduleStart = c.ScheduleStart, + LastRun = c.LastRun, + LastResult = c.LastResult, + Created = c.Created, + Modified = c.Modified, + }; + + /// + public async Task SaveAsync(ReplicationInput input, string? actor, CancellationToken cancellationToken) + { + if (input == null) throw new ArgumentNullException(nameof(input)); + var db = Db; + _gate.ThrowIfClosed(); + + var name = input.Name?.Trim(); + if (!AccessNames.IsValid(name, out var nameError)) throw new ReplicationException(nameError ?? "The name is not valid."); + + var repository = await db.Repositories!.AsNoTracking().FirstOrDefaultAsync(r => r.Name == input.Repository!.Trim(), cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationException($"There is no repository '{input.Repository?.Trim()}'."); + if (repository.Kind != RepositoryKind.Local) throw new ReplicationException("Only a local repository is replicated: a remote one caches an upstream and a virtual one stores nothing."); + if (_services.GetFormatService(repository.Format) == null) throw new ReplicationException($"Replication is not available for {repository.Format} repositories."); + + var peerUrl = ValidatePeer(input.PeerUrl, input.PeerRepository, out var peerRepository); + if (!Enum.IsDefined(input.Direction)) throw new ReplicationException("Unknown direction."); + if (!Enum.IsDefined(input.Conflict)) throw new ReplicationException("Unknown conflict rule."); + if (input.OnDeploy && input.Direction != ReplicationDirection.Push) throw new ReplicationException("Only a push starts after a deploy."); + if (input.ScheduleMinutes is int minutes && (minutes < 1 || minutes > 525_600)) throw new ReplicationException("Repeat every (minutes) must be between 1 and 525600."); + if (input.ApiKey != null && input.ApiKey.Length > 512) throw new ReplicationException("The API key is too long."); + + // Compared in memory, case-insensitively, whatever the engine's collation. + var names = await db.ReplicationConfigs!.AsNoTracking().Select(c => new { c.Key, c.Name }).ToListAsync(cancellationToken).ConfigureAwait(false); + if (names.Any(c => c.Key != input.Key && string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase))) throw new ReplicationException($"There is already a replication named '{name}'."); + + var now = _time.UtcNow; + ReplicationConfig row; + string action; + if (input.Key == 0) + { + row = new ReplicationConfig { Created = now }; + db.ReplicationConfigs!.Add(row); + action = "replication.create"; + } + else + { + row = await db.ReplicationConfigs!.FirstOrDefaultAsync(c => c.Key == input.Key, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationException("The replication no longer exists."); + if (_jobs?.IsRunning(row.Key) == true) throw new ReplicationException("The replication is running; stop it before changing it."); + + action = "replication.update"; + } + + var originChanged = input.Key != 0 && !SameOrigin(row.PeerUrl, peerUrl); + var targetChanged = input.Key != 0 + && (row.RepositoryKey != repository.Key || row.Direction != input.Direction || originChanged + || !string.Equals(row.PeerRepository, peerRepository, StringComparison.Ordinal)); + + // The ledger says what *this* relationship copied; a different repository, direction or peer makes it meaningless. + if (targetChanged) + { + db.ReplicationItems!.RemoveRange(await db.ReplicationItems!.Where(i => i.ConfigKey == row.Key).ToListAsync(cancellationToken).ConfigureAwait(false)); + } + + var keyChanged = false; + if (input.ClearApiKey || (originChanged && string.IsNullOrEmpty(input.ApiKey))) + { + // A key is sent to the address it was typed for and to no other. + keyChanged = row.ProtectedApiKey != null; + row.ProtectedApiKey = null; + } + + if (!string.IsNullOrEmpty(input.ApiKey)) + { + try + { + row.ProtectedApiKey = _codec.ProtectSecret(input.ApiKey); + } + catch (InvalidOperationException e) + { + throw new ReplicationException(e.Message); + } + + keyChanged = true; + } + + // A changed schedule counts from now, so enabling a stale replication does not run it at once for the time it was off. + var restartSchedule = input.Key == 0 || row.ScheduleMinutes != input.ScheduleMinutes || (!row.Enabled && input.Enabled); + + row.Name = name; + row.RepositoryKey = repository.Key; + row.Direction = input.Direction; + row.PeerUrl = peerUrl; + row.PeerRepository = peerRepository; + row.Enabled = input.Enabled; + row.OnDeploy = input.OnDeploy; + row.ScheduleMinutes = input.ScheduleMinutes; + row.PropagateDeletes = input.PropagateDeletes; + row.Conflict = input.Conflict; + row.Modified = now; + if (restartSchedule && row.ScheduleMinutes != null) row.ScheduleStart = now; + + AccessAdministration.Audit(db, now, actor, action, name, new + { + repository = repository.Name, + direction = input.Direction.ToString(), + peer = new Uri(peerUrl).GetLeftPart(UriPartial.Path), + peerRepository, + input.Enabled, + input.OnDeploy, + input.ScheduleMinutes, + input.PropagateDeletes, + conflict = input.Conflict.ToString(), + apiKeyChanged = keyChanged, + }); + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return Redact(row); + } + + private string ValidatePeer(string? url, string? repository, out string peerRepository) + { + var settings = new RemoteRepositorySettings { Url = url?.Trim(), Protocol = RemoteProtocol.Npm }; + var problems = settings.Validate(BlockPrivate); + if (problems.Count > 0) throw new ReplicationException(string.Join(" ", problems).Replace("upstream", "peer", StringComparison.Ordinal)); + + peerRepository = repository?.Trim() ?? string.Empty; + if (!string.Equals(peerRepository, Repository.DefaultName, StringComparison.Ordinal) && !RepositoryNames.IsValid(peerRepository, out var error)) + { + throw new ReplicationException("The peer repository: " + (error ?? "not a valid name.")); + } + + return settings.UrlOrNull!.AbsoluteUri; + } + + private static bool SameOrigin(string? a, string? b) + => Uri.TryCreate(a, UriKind.Absolute, out var x) && Uri.TryCreate(b, UriKind.Absolute, out var y) + && string.Equals(x.GetLeftPart(UriPartial.Authority), y.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); + + /// + public async Task DeleteAsync(int key, string? actor, CancellationToken cancellationToken) + { + var db = Db; + _gate.ThrowIfClosed(); + + var row = await db.ReplicationConfigs!.FirstOrDefaultAsync(c => c.Key == key, cancellationToken).ConfigureAwait(false); + if (row == null) return false; + if (_jobs?.IsRunning(key) == true) throw new ReplicationException("The replication is running; stop it before deleting it."); + + db.ReplicationRuns!.RemoveRange(await db.ReplicationRuns!.Where(r => r.ConfigKey == key).ToListAsync(cancellationToken).ConfigureAwait(false)); + db.ReplicationItems!.RemoveRange(await db.ReplicationItems!.Where(i => i.ConfigKey == key).ToListAsync(cancellationToken).ConfigureAwait(false)); + db.ReplicationConfigs!.Remove(row); + AccessAdministration.Audit(db, _time.UtcNow, actor, "replication.delete", row.Name, new { }); + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return true; + } + + /// + public async Task> ListRunsAsync(int configKey, int take, CancellationToken cancellationToken) + { + var runs = await Db.ReplicationRuns!.AsNoTracking().Where(r => r.ConfigKey == configKey).ToListAsync(cancellationToken).ConfigureAwait(false); + + return runs.OrderByDescending(r => r.Started).ThenByDescending(r => r.Key).Take(Math.Clamp(take, 1, 500)).ToList(); + } + + /// + public async Task GetRunAsync(int runKey, CancellationToken cancellationToken) + => await Db.ReplicationRuns!.AsNoTracking().FirstOrDefaultAsync(r => r.Key == runKey, cancellationToken).ConfigureAwait(false); + + /// + public async Task TestAsync(ReplicationInput input, CancellationToken cancellationToken) + { + if (input == null) throw new ArgumentNullException(nameof(input)); + var db = Db; + + string peerUrl; + string peerRepository; + try + { + peerUrl = ValidatePeer(input.PeerUrl, input.PeerRepository, out peerRepository); + } + catch (ReplicationException e) + { + return new ReplicationTestResult(false, e.Message, 0, null, null); + } + + var apiKey = string.IsNullOrEmpty(input.ApiKey) ? null : input.ApiKey; + if (apiKey == null && !input.ClearApiKey && input.Key != 0) + { + var stored = await db.ReplicationConfigs!.AsNoTracking().FirstOrDefaultAsync(c => c.Key == input.Key, cancellationToken).ConfigureAwait(false); + if (stored != null && SameOrigin(stored.PeerUrl, peerUrl)) apiKey = _codec.TryUnprotectSecret(stored.ProtectedApiKey); + } + + var watch = Stopwatch.StartNew(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + try + { + if (BlockPrivate) + { + var refused = await RemoteAddressPolicy.CheckResolvedAsync(new Uri(peerUrl), timeout.Token).ConfigureAwait(false); + if (refused != null) return new ReplicationTestResult(false, refused.Replace("upstream", "peer", StringComparison.Ordinal), watch.ElapsedMilliseconds, null, null); + } + + using var peer = _peers.Create(peerUrl, peerRepository, apiKey, 30); + var inventory = await peer.GetInventoryAsync(summary: true, timeout.Token).ConfigureAwait(false); + + var message = $"Connected: '{peerRepository}' is a {inventory.Kind.ToString().ToLowerInvariant()} {inventory.Format} repository holding {inventory.Count} item(s)."; + if (!string.IsNullOrWhiteSpace(input.Repository)) + { + var local = await db.Repositories!.AsNoTracking().FirstOrDefaultAsync(r => r.Name == input.Repository!.Trim(), cancellationToken).ConfigureAwait(false); + if (local != null && local.Format != inventory.Format) + { + return new ReplicationTestResult(false, $"The peer's repository is a {inventory.Format} repository; '{local.Name}' is {local.Format}.", watch.ElapsedMilliseconds, inventory.Format, inventory.Count); + } + + if (input.Direction == ReplicationDirection.Push && inventory.Kind != RepositoryKind.Local) + { + return new ReplicationTestResult(false, $"The peer's repository is {inventory.Kind.ToString().ToLowerInvariant()}, so it cannot receive.", watch.ElapsedMilliseconds, inventory.Format, inventory.Count); + } + } + + return new ReplicationTestResult(true, message, watch.ElapsedMilliseconds, inventory.Format, inventory.Count); + } + catch (ReplicationItemException e) + { + return new ReplicationTestResult(false, e.Message, watch.ElapsedMilliseconds, null, null); + } + catch (Exception e) when (e is System.Net.Http.HttpRequestException or OperationCanceledException or TimeoutException) + { + if (cancellationToken.IsCancellationRequested) throw; + + return new ReplicationTestResult(false, "The peer could not be reached: " + e.GetBaseException().Message, watch.ElapsedMilliseconds, null, null); + } + } +} diff --git a/src/BaGet.Core/Replication/ReplicationEngine.cs b/src/BaGet.Core/Replication/ReplicationEngine.cs new file mode 100644 index 000000000..9f4e9bbde --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationEngine.cs @@ -0,0 +1,398 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// A refusal the administrator can fix (invalid input, unknown repository, a disabled configuration); the message is shown on the page. +public sealed class ReplicationException : AccessModelException +{ + public ReplicationException(string message) + : base(message) + { + } +} + +/// +/// Creates the connection to a peer BaGet server. The credential is the peer's API key, sent as a bearer token to the peer's own +/// origin only (never to a redirect target); the transport is , so Remote:BlockPrivateAddresses +/// applies to every connection and tests replace the transport in one place. +/// +public interface IReplicationPeerFactory +{ + /// The peer's base address. + /// The peer's repository. + /// The peer's API key, or null for an anonymous peer. + /// The time a request may take. + ReplicationPeer Create(string peerUrl, string peerRepository, string? apiKey, int timeoutSeconds = 600); +} + +/// The default . +public sealed class ReplicationPeerFactory : IReplicationPeerFactory +{ + private readonly IRemoteHttpClientFactory _http; + + public ReplicationPeerFactory(IRemoteHttpClientFactory http) + { + _http = http ?? throw new ArgumentNullException(nameof(http)); + } + + /// + public ReplicationPeer Create(string peerUrl, string peerRepository, string? apiKey, int timeoutSeconds = 600) + { + // A password with no user name is sent as a bearer token to the URL's origin: exactly an API key. + var settings = new RemoteRepositorySettings + { + Url = peerUrl, + Protocol = RemoteProtocol.Npm, + Password = string.IsNullOrEmpty(apiKey) ? null : apiKey, + DownloadTimeoutSeconds = timeoutSeconds, + }; + var uri = settings.UrlOrNull ?? throw new ReplicationException("The peer URL must be an absolute http or https address."); + + return new ReplicationPeer(_http.CreateProbe(settings), uri, peerRepository, ownsClient: true, apiKey: string.IsNullOrEmpty(apiKey) ? null : apiKey); + } +} + +/// +/// Runs one replication of a configuration: lists both sides, plans (), copies what the target lacks +/// through the format's own protocol, applies the conflict rule, propagates deletes of what it copied, and writes the log +/// () and the ledger () as it goes. Because every run plans from what both +/// sides hold now, a run that was interrupted (the server stopped, the peer vanished, an administrator stopped it) is continued +/// by starting another: what was copied is skipped, what is left is copied. +/// +public sealed class ReplicationEngine +{ + /// The items between two saves of the run's progress. + internal const int SaveEvery = 10; + + private const int MaxDetailLines = 40; + + private readonly IContext _context; + private readonly IServiceScopeFactory _scopes; + private readonly IRepositoryService _repositories; + private readonly IReplicationPeerFactory _peers; + private readonly RemoteSettingsCodec _codec; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + + public ReplicationEngine( + IContext context, + IServiceScopeFactory scopes, + IRepositoryService repositories, + IReplicationPeerFactory peers, + RemoteSettingsCodec codec, + SystemTime time, + MaintenanceGate gate, + ILogger logger) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _peers = peers ?? throw new ArgumentNullException(nameof(peers)); + _codec = codec ?? throw new ArgumentNullException(nameof(codec)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// Test seam: called after each item with the number of items handled so far; throwing or cancelling here interrupts the run. + internal Func? AfterItem { get; set; } + + /// Runs the configuration to the end and returns its log entry (also stored). + /// The configuration. + /// manual, resume, schedule or deploy. + /// The administrator, or scheduler. + /// The run this one continues, or null. + /// Cancelling ends the run as . + /// The configuration does not exist, is disabled, or its repository cannot take part. + /// The server is read-only. + public async Task RunAsync(int configKey, string trigger, string? actor, int? resumedFrom, CancellationToken cancellationToken) + { + if (_context is NullContext) throw new ReplicationException("Replication needs a relational database."); + _gate.ThrowIfClosed(); + + var config = await _context.ReplicationConfigs!.FirstOrDefaultAsync(c => c.Key == configKey, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationException("The replication no longer exists."); + if (!config.Enabled) throw new ReplicationException($"The replication '{config.Name}' is disabled."); + + var repository = await _repositories.FindAsync(config.RepositoryKey, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationException($"The repository of the replication '{config.Name}' no longer exists."); + if (repository.Kind != RepositoryKind.Local) throw new ReplicationException($"The repository '{repository.Name}' is not a local repository."); + + var started = _time.UtcNow; + var run = new ReplicationRun + { + ConfigKey = config.Key, + Status = ReplicationRunStatus.Running, + Trigger = trigger, + Actor = actor, + ResumedFrom = resumedFrom, + Started = started, + }; + _context.ReplicationRuns!.Add(run); + config.LastRun = started; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + var detail = new List(); + try + { + await ExecuteAsync(config, repository, run, detail, cancellationToken).ConfigureAwait(false); + run.Status = run.Failures > 0 ? ReplicationRunStatus.Failed : ReplicationRunStatus.Succeeded; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + run.Status = ReplicationRunStatus.Interrupted; + run.Error = "Stopped before the end; start the replication again to continue."; + } + catch (MaintenanceException) + { + run.Status = ReplicationRunStatus.Interrupted; + run.Error = "The server became read-only; start the replication again to continue."; + } + catch (Exception e) when (IsTransport(e)) + { + run.Status = ReplicationRunStatus.Failed; + run.Error = Truncate("The peer could not be reached: " + Safe(e), ReplicationLimits.MaxResultLength); + } + catch (ReplicationItemException e) + { + run.Status = ReplicationRunStatus.Failed; + run.Error = Truncate(e.Message, ReplicationLimits.MaxResultLength); + } + catch (Exception e) + { + _logger.LogError(e, "Replication {Replication} failed", config.Name); + run.Status = ReplicationRunStatus.Failed; + run.Error = Truncate($"{e.GetType().Name}: {e.Message}", ReplicationLimits.MaxResultLength); + } + + await FinishAsync(config, run, detail, repository).ConfigureAwait(false); + + return run; + } + + private async Task FinishAsync(ReplicationConfig config, ReplicationRun run, List detail, RepositoryInfo repository) + { + run.Finished = _time.UtcNow; + run.Detail = detail.Count == 0 ? null : Truncate(string.Join("\n", detail), ReplicationLimits.MaxDetailLength); + config.LastResult = Truncate(Summary(run), ReplicationLimits.MaxResultLength); + AccessAdministration.Audit(_context, _time.UtcNow, run.Actor, "replication.run", config.Name, new + { + repository = repository.Name, + run.Trigger, + status = run.Status.ToString(), + run.Transferred, + run.Deleted, + run.Conflicts, + run.Failures, + }); + + // The run is over whatever stopped it: saving must not be cancelled with it. + await _context.SaveChangesAsync(CancellationToken.None).ConfigureAwait(false); + } + + /// The one-line account of a run, as the list shows it. + public static string Summary(ReplicationRun run) + { + var text = $"{run.Status}: {run.Transferred} copied, {run.Skipped} already there, {run.Deleted} deleted, {run.Conflicts} conflicts, {run.Failures} failed"; + + return string.IsNullOrEmpty(run.Error) ? text : text + ". " + run.Error; + } + + private async Task ExecuteAsync(ReplicationConfig config, RepositoryInfo repository, ReplicationRun run, List detail, CancellationToken cancellationToken) + { + string? apiKey = null; + if (!string.IsNullOrEmpty(config.ProtectedApiKey)) + { + apiKey = _codec.TryUnprotectSecret(config.ProtectedApiKey) + ?? throw new ReplicationItemException("The stored API key cannot be read (the data protection keys changed); enter it again."); + } + + using var peer = _peers.Create(config.PeerUrl!, config.PeerRepository!, apiKey); + using var scope = _scopes.CreateRepositoryScope(repository); + var replicator = scope.ServiceProvider.GetFormatService(repository.Format) + ?? throw new ReplicationItemException($"Replication is not available for {repository.Format} repositories."); + + var push = config.Direction == ReplicationDirection.Push; + var inventory = await peer.GetInventoryAsync(summary: false, cancellationToken).ConfigureAwait(false); + if (inventory.Format != repository.Format) + { + throw new ReplicationItemException($"The peer's repository '{peer.Repository}' is a {inventory.Format} repository; '{repository.Name}' is {repository.Format}."); + } + + if (push && inventory.Kind != RepositoryKind.Local) + { + throw new ReplicationItemException($"The peer's repository '{peer.Repository}' is {inventory.Kind.ToString().ToLowerInvariant()}, so it cannot receive."); + } + + var local = await replicator.ListAsync(cancellationToken).ConfigureAwait(false); + var names = replicator.NameComparer; + var ledgerRows = await _context.ReplicationItems!.Where(i => i.ConfigKey == config.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var ledger = new Dictionary(ReplicationPlanner.KeyComparer(names)); + foreach (var row in ledgerRows) ledger[new ReplicaItem(row.Name!, row.Version!, row.Part ?? string.Empty, 0, row.Digest ?? string.Empty)] = row; + + var plan = ReplicationPlanner.Plan( + push ? local : inventory.Items, + push ? inventory.Items : local, + ledger.Keys.ToList(), + names, + config.Conflict, + config.PropagateDeletes); + run.Examined = plan.Examined; + run.Skipped = plan.Skipped; + + var handled = 0; + async Task StepAsync() + { + handled++; + if (handled % SaveEvery == 0) await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (AfterItem != null) await AfterItem(handled, cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + } + + foreach (var item in plan.Conflicts) + { + run.Conflicts++; + AddDetail(detail, $"conflict: {item} is held differently on both sides; the {(push ? "peer" : "local")} copy was kept"); + } + + foreach (var item in plan.Replace) + { + run.Conflicts++; + AddDetail(detail, $"conflict: {item} is held differently on both sides; the {(push ? "peer" : "local")} copy is replaced"); + + // A pull replaces the local copy only once the peer's item is fetched and accepted (PullReplacingAsync), so a refusal + // (scanning policy, integrity) or a transport failure keeps what was there. A push moves a Docker tag in place and + // deletes at the peer first for the formats whose peers refuse to overwrite (IFormatReplicator.PushReplacesInPlace). + if (push && !replicator.PushReplacesInPlace && !await TryAsync(item, "delete", () => DeleteTargetAsync(replicator, peer, push, item, cancellationToken), run, detail).ConfigureAwait(false)) continue; + + await CopyAsync(config, replicator, peer, push, item, ledger, run, detail, cancellationToken, replace: true).ConfigureAwait(false); + await StepAsync().ConfigureAwait(false); + } + + foreach (var item in plan.Copy) + { + await CopyAsync(config, replicator, peer, push, item, ledger, run, detail, cancellationToken).ConfigureAwait(false); + await StepAsync().ConfigureAwait(false); + } + + foreach (var item in plan.Delete) + { + if (await TryAsync(item, "delete", () => DeleteTargetAsync(replicator, peer, push, item, cancellationToken), run, detail).ConfigureAwait(false)) + { + run.Deleted++; + Forget(ledger, item); + } + + await StepAsync().ConfigureAwait(false); + } + + foreach (var item in plan.Forget) Forget(ledger, item); + } + + private static Task DeleteTargetAsync(IFormatReplicator replicator, ReplicationPeer peer, bool push, ReplicaItem item, CancellationToken cancellationToken) + => push ? replicator.DeletePeerAsync(item, peer, cancellationToken) : replicator.DeleteLocalAsync(item, cancellationToken); + + private async Task CopyAsync( + ReplicationConfig config, + IFormatReplicator replicator, + ReplicationPeer peer, + bool push, + ReplicaItem item, + Dictionary ledger, + ReplicationRun run, + List detail, + CancellationToken cancellationToken, + bool replace = false) + { + long bytes = 0; + if (!await TryAsync(item, push ? "push" : "pull", async () => bytes = push + ? await replicator.PushAsync(item, peer, cancellationToken).ConfigureAwait(false) + : replace + ? await replicator.PullReplacingAsync(item, peer, cancellationToken).ConfigureAwait(false) + : await replicator.PullAsync(item, peer, cancellationToken).ConfigureAwait(false), run, detail).ConfigureAwait(false)) + { + return; + } + + run.Transferred++; + run.Bytes += bytes; + if (!ledger.TryGetValue(item, out var row)) + { + row = new ReplicationItem { ConfigKey = config.Key, Name = item.Name, Version = item.Version, Part = item.Part }; + _context.ReplicationItems!.Add(row); + ledger[item] = row; + } + + row.Digest = item.Digest; + row.Synced = _time.UtcNow; + } + + private void Forget(Dictionary ledger, ReplicaItem item) + { + if (!ledger.TryGetValue(item, out var row)) return; + + ledger.Remove(item); + _context.ReplicationItems!.Remove(row); // an added row (never saved) is simply detached + } + + // One item's failure is the item's: logged, counted, and the run goes on. A transport failure, a stop and a read-only server + // end the run (they would fail every remaining item the same way). + private async Task TryAsync(ReplicaItem item, string what, Func action, ReplicationRun run, List detail) + { + try + { + await action().ConfigureAwait(false); + + return true; + } + catch (ReplicationItemException e) + { + if (e.Conflict) + { + run.Conflicts++; + AddDetail(detail, $"conflict: {item}: {e.Message}"); + } + else + { + run.Failures++; + AddDetail(detail, $"failed ({what}): {item}: {e.Message}"); + } + + return false; + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException && !IsTransport(e)) + { + run.Failures++; + AddDetail(detail, $"failed ({what}): {item}: {e.GetType().Name}: {Safe(e)}"); + _logger.LogWarning(e, "Replication of {Item} failed", item); + + return false; + } + } + + // HttpClient wraps connection and socket failures in HttpRequestException; a timeout is a TaskCanceledException the run's own + // token did not cause. + private static bool IsTransport(Exception e) + => e is HttpRequestException or TaskCanceledException or TimeoutException + || e.InnerException is HttpRequestException; + + // Transport messages can name the URL; never a credential (the key travels in a header), but cut anyway. + private static string Safe(Exception e) => Truncate(e.GetBaseException().Message, 300); + + private static void AddDetail(List detail, string line) + { + if (detail.Count < MaxDetailLines) detail.Add(Truncate(line, 300)); + else if (detail.Count == MaxDetailLines) detail.Add("... more entries are not listed"); + } + + private static string Truncate(string text, int length) => text.Length <= length ? text : text.Substring(0, length - 3) + "..."; +} diff --git a/src/BaGet.Core/Replication/ReplicationEntities.cs b/src/BaGet.Core/Replication/ReplicationEntities.cs new file mode 100644 index 000000000..d177e2f60 --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationEntities.cs @@ -0,0 +1,182 @@ +using System; + +namespace BaGet.Core; + +/// Column limits of the replication tables; the name limit is the retention one (a Maven group:artifact fits). +public static class ReplicationLimits +{ + public const int MaxNameLength = RetentionLimits.MaxNameLength; + public const int MaxVersionLength = RetentionLimits.MaxVersionLength; + public const int MaxPartLength = 256; + public const int MaxDigestLength = 160; + public const int MaxUrlLength = RemoteRepositorySettings.MaxUrlLength; + public const int MaxSecretLength = 2048; + public const int MaxResultLength = 1024; + public const int MaxDetailLength = 4000; +} + +/// Which way a copies. +public enum ReplicationDirection +{ + /// This server's repository is the source; the peer's repository receives. + Push = 0, + + /// The peer's repository is the source; this server's repository receives. + Pull = 1, +} + +/// What happens when both sides hold the same item with different content. +public enum ReplicationConflict +{ + /// The receiving side keeps its item; the run logs a conflict. + TargetWins = 0, + + /// The receiving side's item is deleted and replaced by the source's. + SourceWins = 1, +} + +/// How a ended. +public enum ReplicationRunStatus +{ + Running = 0, + + /// Everything the plan held was done. + Succeeded = 1, + + /// Finished, but some items failed (see the detail) or the peer could not be used. + Failed = 2, + + /// Stopped before the end (the server stopped, or an administrator cancelled); a later run continues from what is in place. + Interrupted = 3, +} + +/// +/// One replication relationship: a local repository and a repository of another BaGet server, copied in one direction. Not +/// repository-scoped (the administrator lists configurations across repositories). Its RepositoryKey is a Restrict foreign key, and +/// so is ConfigKey of its runs and ledger: deleting the repository deletes its configurations, runs and ledger first (code, not cascade). +/// +public class ReplicationConfig +{ + public int Key { get; set; } + + /// Unique, rules. + public string? Name { get; set; } + + /// The local : a local (not remote, not virtual) repository. + public int RepositoryKey { get; set; } + + public ReplicationDirection Direction { get; set; } + + /// The peer server's base address (https://other.example/), not a repository feed. + public string? PeerUrl { get; set; } + + /// The peer's repository (default or its name); it must be of the same format. + public string? PeerRepository { get; set; } + + /// + /// The peer's API key, protected like a remote repository's password (); never shown by a + /// page or the API and never logged. The key needs the peer's admin:api scope (inventory) and the format's push or read rights. + /// + [System.Text.Json.Serialization.JsonIgnore] + public string? ProtectedApiKey { get; set; } + + /// A disabled configuration is never run by the schedule or a deploy; a manual run is refused. + public bool Enabled { get; set; } + + /// Push only: a deploy to the local repository starts a run (after a short quiet period). + public bool OnDeploy { get; set; } + + /// Run every this many minutes. Null: only when started (or on deploy). + public int? ScheduleMinutes { get; set; } + + /// What was replicated and is later deleted at the source is deleted at the target too (only items this configuration copied). + public bool PropagateDeletes { get; set; } + + public ReplicationConflict Conflict { get; set; } + + /// When the schedule was set or the configuration enabled; the first scheduled run is due this long after it. + public DateTime? ScheduleStart { get; set; } + + /// When the last run started (the schedule counts from the later of this and ). + public DateTime? LastRun { get; set; } + + /// One line about the last run. + public string? LastResult { get; set; } + + public DateTime Created { get; set; } + + public DateTime Modified { get; set; } +} + +/// One run of a configuration: the replication log. +public class ReplicationRun +{ + public int Key { get; set; } + + /// The . + public int ConfigKey { get; set; } + + public ReplicationRunStatus Status { get; set; } + + /// manual, resume, schedule or deploy. + public string? Trigger { get; set; } + + /// The administrator, or scheduler. + public string? Actor { get; set; } + + /// The interrupted or failed run this one continues, when started with Resume. + public int? ResumedFrom { get; set; } + + public DateTime Started { get; set; } + + public DateTime? Finished { get; set; } + + /// Items the plan looked at (both sides listed). + public int Examined { get; set; } + + /// Items copied to the target. + public int Transferred { get; set; } + + /// Items the target already had. + public int Skipped { get; set; } + + /// Items deleted at the target because they were deleted at the source. + public int Deleted { get; set; } + + /// Items held differently on both sides that were left alone (target wins) or replaced (source wins). + public int Conflicts { get; set; } + + public int Failures { get; set; } + + /// Bytes of artifact content sent or received. + public long Bytes { get; set; } + + /// Why the run failed as a whole, or null. + public string? Error { get; set; } + + /// The first failures and conflicts, one per line. + public string? Detail { get; set; } +} + +/// +/// An item a configuration copied: the ledger that tells "deleted at the source since" from "never copied", so delete propagation +/// removes only what replication put there. Not repository-scoped. +/// +public class ReplicationItem +{ + public int Key { get; set; } + + public int ConfigKey { get; set; } + + public string? Name { get; set; } + + public string? Version { get; set; } + + /// The file of a Maven version; empty for the other formats. + public string? Part { get; set; } + + /// The content digest at the time of the copy, or empty. + public string? Digest { get; set; } + + public DateTime Synced { get; set; } +} diff --git a/src/BaGet.Core/Replication/ReplicationInventoryService.cs b/src/BaGet.Core/Replication/ReplicationInventoryService.cs new file mode 100644 index 000000000..8869c1c28 --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationInventoryService.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Core; + +/// +/// What a repository holds, in the form replication compares: the answer of GET /api/v1/replication/inventory/{repository} (what +/// a peer asks) and the count the replication page shows for the local side. A virtual repository stores nothing and has no items; +/// a remote one lists what it cached. +/// +public interface IReplicationInventory +{ + /// The inventory of , or null when there is no such repository. + /// The repository name. + /// Only the count and the kind ( is empty). + /// Cancels the listing. + Task GetAsync(string repository, bool summary, CancellationToken cancellationToken); +} + +/// The default : each repository is listed in a scope of its own. +public sealed class ReplicationInventoryService : IReplicationInventory +{ + private readonly IRepositoryService _repositories; + private readonly IServiceScopeFactory _scopes; + + public ReplicationInventoryService(IRepositoryService repositories, IServiceScopeFactory scopes) + { + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + } + + /// + public async Task GetAsync(string repository, bool summary, CancellationToken cancellationToken) + { + var info = await _repositories.FindAsync(repository, cancellationToken).ConfigureAwait(false); + if (info == null) return null; + if (info.Kind == RepositoryKind.Virtual) return new ReplicationInventory(info.Name, info.Format, info.Kind, 0, Array.Empty()); + + using var scope = _scopes.CreateRepositoryScope(info); + var replicator = scope.ServiceProvider.GetFormatService(info.Format); + var items = replicator == null ? Array.Empty() : (IReadOnlyList)await replicator.ListAsync(cancellationToken).ConfigureAwait(false); + + return new ReplicationInventory(info.Name, info.Format, info.Kind, items.Count, summary ? Array.Empty() : items); + } +} diff --git a/src/BaGet.Core/Replication/ReplicationJobs.cs b/src/BaGet.Core/Replication/ReplicationJobs.cs new file mode 100644 index 000000000..d25d8845b --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationJobs.cs @@ -0,0 +1,421 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// What the page knows of a replication started since the server began (in memory); the log table is the durable record. +public sealed class ReplicationJobStatus +{ + public int ConfigKey { get; init; } + + public DateTime Started { get; init; } + + public DateTime? Finished { get; internal set; } + + /// True while the run is going. + public bool Running => Finished == null; + + /// Why the job did not even begin a run (read-only server, disabled configuration, lease held elsewhere), or null. + public string? Refusal { get; internal set; } +} + +/// +/// Remembers which repositories received something (a package, a version, a file, a tag) so deploy-triggered pushes can start after a +/// short quiet period instead of once per file. Filled by . +/// +public sealed class ReplicationTrigger +{ + /// How long a repository must be quiet before its deploy-triggered replications start. + internal static readonly TimeSpan QuietPeriod = TimeSpan.FromSeconds(5); + + private readonly ConcurrentDictionary _pending = new(); + private readonly SystemTime _time; + + public ReplicationTrigger(SystemTime time) + { + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + /// Records that the repository received something now. + public void Notify(int repositoryKey) => _pending[repositoryKey] = _time.UtcNow; + + /// Removes and returns the repositories that have been quiet for . + public IReadOnlyList TakeQuiet(TimeSpan quiet) + { + var now = _time.UtcNow; + var due = _pending.Where(p => now - p.Value >= quiet).Select(p => p.Key).ToList(); + foreach (var key in due) _pending.TryRemove(key, out _); + + return due; + } +} + +/// A database context that knows the repository it works in (every ). +public interface IRepositoryScopedContext +{ + /// The repository this context works in now. + int ScopeRepositoryKey { get; } +} + +/// +/// Tells after a save that committed a new package, npm version, Maven file or Docker tag (or moved +/// one), in the repository the context worked in. It never reads or changes the rows. +/// +public sealed class ReplicationDeployInterceptor : SaveChangesInterceptor +{ + private readonly ReplicationTrigger _trigger; + private readonly ConditionalWeakTable> _pending = new(); + + public ReplicationDeployInterceptor(ReplicationTrigger trigger) + { + _trigger = trigger ?? throw new ArgumentNullException(nameof(trigger)); + } + + public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + { + Mark(eventData.Context); + return result; + } + + public override ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + Mark(eventData.Context); + return new ValueTask>(result); + } + + public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) + { + Commit(eventData.Context); + return result; + } + + public override ValueTask SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default) + { + Commit(eventData.Context); + return new ValueTask(result); + } + + public override void SaveChangesFailed(DbContextErrorEventData eventData) => Forget(eventData.Context); + + public override Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = default) + { + Forget(eventData.Context); + return Task.CompletedTask; + } + + private void Mark(DbContext? context) + { + if (context is not IRepositoryScopedContext db) return; + + // A package row is also modified by every download count; only a new row is a deploy. A Docker tag is also a deploy when it moves. + var deployed = context.ChangeTracker.Entries().Any(e => e.Entity switch + { + Package or NpmVersion or MavenFile => e.State == EntityState.Added, + OciTag => e.State is EntityState.Added or EntityState.Modified, + _ => false, + }); + if (deployed) _pending.AddOrUpdate(context, new StrongBox(db.ScopeRepositoryKey)); + } + + private void Commit(DbContext? context) + { + if (context != null && _pending.TryGetValue(context, out var key)) + { + _pending.Remove(context); + _trigger.Notify(key.Value); + } + } + + private void Forget(DbContext? context) + { + if (context != null) _pending.Remove(context); + } +} + +/// +/// Runs replications in the background, one run per configuration at a time (and, through , one in the cluster). +/// Stopping the server cancels the runs; each ends as and a later run continues. +/// +public sealed class ReplicationJobs +{ + private readonly IServiceScopeFactory _scopes; + private readonly IJobLease _lease; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + private readonly IHostApplicationLifetime? _lifetime; + private readonly ConcurrentDictionary _status = new(); + private readonly ConcurrentDictionary _running = new(); + private readonly object _lock = new(); + + public ReplicationJobs(IServiceScopeFactory scopes, IJobLease lease, SystemTime time, MaintenanceGate gate, ILogger logger, IHostApplicationLifetime? lifetime = null) + { + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _lease = lease ?? throw new ArgumentNullException(nameof(lease)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _lifetime = lifetime; + } + + /// The name of the lease that guards a configuration's runs. + public static string LeaseName(int configKey) => "replication:" + configKey; + + /// The last job of the configuration since the server started, or null. + public ReplicationJobStatus? Get(int configKey) => _status.TryGetValue(configKey, out var status) ? status : null; + + /// Whether this process is running the configuration now. + public bool IsRunning(int configKey) => _running.ContainsKey(configKey); + + /// Asks the running replication to stop (it ends as interrupted); false when none is running here. + public bool Cancel(int configKey) + { + if (!_running.TryGetValue(configKey, out var running)) return false; + + try + { + running.Cancel.Cancel(); + } + catch (ObjectDisposedException) + { + return false; + } + + return true; + } + + /// Starts a run in the background. + /// The configuration. + /// manual, resume, schedule or deploy. + /// Who started it. + /// The interrupted or failed run being continued, or null. + /// Why it was not started. + /// Called when the run was accepted here but never ran because another node holds the configuration's lease + /// (the caller puts back what it had consumed to start the run, e.g. a deploy notice). + /// The server is read-only. + public bool TryStart(int configKey, string trigger, string? actor, int? resumedFrom, out string? refusal, Action? notRun = null) + { + _gate.ThrowIfClosed(); + + var cancel = CancellationTokenSource.CreateLinkedTokenSource(_lifetime?.ApplicationStopping ?? CancellationToken.None); + var status = new ReplicationJobStatus { ConfigKey = configKey, Started = _time.UtcNow }; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + lock (_lock) + { + if (_running.ContainsKey(configKey)) + { + cancel.Dispose(); + refusal = "This replication is already running."; + + return false; + } + + _status[configKey] = status; + _running[configKey] = (completion.Task, cancel); + } + + _ = Task.Run(async () => + { + try + { + await using var lease = await _lease.TryAcquireAsync(LeaseName(configKey), cancel.Token).ConfigureAwait(false); + if (lease == null) + { + status.Refusal = "Another node is running this replication."; + notRun?.Invoke(); + + return; + } + + using var scope = _scopes.CreateScope(); + await scope.ServiceProvider.GetRequiredService().RunAsync(configKey, trigger, actor, resumedFrom, cancel.Token).ConfigureAwait(false); + } + catch (Exception e) when (e is ReplicationException or MaintenanceException) + { + status.Refusal = e.Message; + } + catch (OperationCanceledException) + { + status.Refusal = "Stopped."; + } + catch (Exception e) + { + _logger.LogError(e, "Replication {Replication} failed", configKey); + status.Refusal = $"{e.GetType().Name}: {e.Message}"; + } + finally + { + status.Finished = _time.UtcNow; + _running.TryRemove(configKey, out _); + cancel.Dispose(); + completion.SetResult(true); + } + }); + + refusal = null; + + return true; + } + + /// Completes when the current run of the configuration ends (immediately when none). + public Task WaitAsync(int configKey) => _running.TryGetValue(configKey, out var running) ? running.Task : Task.CompletedTask; +} + +/// +/// Starts the replications that are due: scheduled ones ( after the later of the last run +/// and the time the schedule was set), deploy-triggered pushes once their repository has been quiet, and marks runs that a stopped process +/// left as as interrupted (only when the configuration's lease is free, so a run on another +/// node is left alone). Idle while the server is read-only and with a database that cannot hold configurations. +/// +public sealed class ReplicationWorker : BackgroundService +{ + /// How often the worker looks. + internal static readonly TimeSpan Interval = TimeSpan.FromSeconds(15); + + private readonly IServiceScopeFactory _scopes; + private readonly ReplicationJobs _jobs; + private readonly ReplicationTrigger _trigger; + private readonly IJobLease _lease; + private readonly MaintenanceGate _gate; + private readonly SystemTime _time; + private readonly ILogger _logger; + + public ReplicationWorker(IServiceScopeFactory scopes, ReplicationJobs jobs, ReplicationTrigger trigger, IJobLease lease, MaintenanceGate gate, SystemTime time, ILogger logger) + { + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _jobs = jobs ?? throw new ArgumentNullException(nameof(jobs)); + _trigger = trigger ?? throw new ArgumentNullException(nameof(trigger)); + _lease = lease ?? throw new ArgumentNullException(nameof(lease)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + // The wait comes first: the database may still be migrating when the host starts. + try + { + await Task.Delay(Interval, stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + + try + { + await RunDueAsync(ReplicationTrigger.QuietPeriod, stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception e) + { + _logger.LogError(e, "Replication pass failed; it is retried on the next one"); + } + } + } + + /// One pass. + /// How long a repository must have been quiet for its deploy-triggered replications to start. + /// Stops the pass. + /// The keys of the configurations started. + public async Task> RunDueAsync(TimeSpan quiet, CancellationToken cancellationToken) + { + if (_gate.IsClosed) return Array.Empty(); + + var deployed = _trigger.TakeQuiet(quiet); + List due; + using (var scope = _scopes.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + if (context is NullContext) return Array.Empty(); + + await SweepOrphansAsync(context, cancellationToken).ConfigureAwait(false); + + var now = _time.UtcNow; + var enabled = await context.ReplicationConfigs!.AsNoTracking().Where(c => c.Enabled).ToListAsync(cancellationToken).ConfigureAwait(false); + due = enabled + .Where(c => IsDue(c, now) || (c.OnDeploy && c.Direction == ReplicationDirection.Push && deployed.Contains(c.RepositoryKey))) + .OrderBy(c => c.Key) + .ToList(); + } + + var started = new List(); + foreach (var config in due) + { + var trigger = deployed.Contains(config.RepositoryKey) && config.OnDeploy && config.Direction == ReplicationDirection.Push ? "deploy" : "schedule"; + try + { + // A deploy notice is consumed by TakeQuiet; it must survive a run that does not happen, here (already running) or on + // another node that holds the lease (that run may have listed its inventory before the deploy). + var repositoryKey = config.RepositoryKey; + Action? notRun = trigger == "deploy" ? () => _trigger.Notify(repositoryKey) : null; + if (_jobs.TryStart(config.Key, trigger, "scheduler", null, out _, notRun)) + { + started.Add(config.Key); + } + else if (trigger == "deploy") + { + // Still running: the news must not be lost, the next pass starts it again. + _trigger.Notify(config.RepositoryKey); + } + } + catch (MaintenanceException) + { + break; + } + } + + return started; + } + + // A run left "Running" by a process that stopped. It is ours to mark only when nothing here runs it and its lease is free. + private async Task SweepOrphansAsync(IContext context, CancellationToken cancellationToken) + { + var running = await context.ReplicationRuns!.Where(r => r.Status == ReplicationRunStatus.Running).ToListAsync(cancellationToken).ConfigureAwait(false); + if (running.Count == 0) return; + + foreach (var run in running) + { + if (_jobs.IsRunning(run.ConfigKey)) continue; + + await using var lease = await _lease.TryAcquireAsync(ReplicationJobs.LeaseName(run.ConfigKey), cancellationToken).ConfigureAwait(false); + if (lease == null) continue; + + // The row was read before the lease: the run may have finished meanwhile. Judge it again, and save while the lease is held. + var key = run.Key; + var stillRunning = await context.ReplicationRuns!.AsNoTracking().AnyAsync(r => r.Key == key && r.Status == ReplicationRunStatus.Running, cancellationToken).ConfigureAwait(false); + if (!stillRunning) continue; + + run.Status = ReplicationRunStatus.Interrupted; + run.Finished = _time.UtcNow; + run.Error = "The server stopped during this run; start the replication again to continue."; + await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + } + + /// Whether the schedule of is due at . + public static bool IsDue(ReplicationConfig config, DateTime now) + { + if (!config.Enabled || config.ScheduleMinutes is not int minutes) return false; + + var basis = new[] { config.LastRun, config.ScheduleStart, config.Created }.Where(d => d != null).Select(d => d!.Value).DefaultIfEmpty(DateTime.MinValue).Max(); + + return basis.AddMinutes(minutes) <= now; + } +} diff --git a/src/BaGet.Core/Replication/ReplicationModel.cs b/src/BaGet.Core/Replication/ReplicationModel.cs new file mode 100644 index 000000000..aaccf78c1 --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationModel.cs @@ -0,0 +1,338 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// One replicable item, named the way the format's retention hooks name things: a NuGet package version, an npm version, a Maven +/// file () or a Docker tag. +/// +/// Package id, npm name, Maven group:artifact, image name. +/// Version; a Docker tag. +/// The Maven file name; empty for the other formats. +/// Bytes, when the listing knows them (0 otherwise). +/// A content digest that is equal on two servers holding the same content (npm integrity, Maven sha256, Docker manifest digest); empty when the format keeps none (NuGet). +public sealed record ReplicaItem(string Name, string Version, string Part, long Size, string Digest) +{ + /// Whether two sides hold different content: both digests are known and differ. + public bool DiffersFrom(ReplicaItem other) + => other != null && Digest.Length > 0 && other.Digest.Length > 0 && !string.Equals(Digest, other.Digest, StringComparison.Ordinal); + + /// The item as the ledger and the logs name it. + public override string ToString() => Part.Length == 0 ? Name + " " + Version : Name + " " + Version + " " + Part; +} + +/// What GET /api/v1/replication/inventory/{repository} answers: the repository and its items. +/// The repository's name. +/// Its format. +/// Local, remote or virtual (only a local repository can receive). +/// The number of items. +/// The items (empty when only the summary was asked for). +public sealed record ReplicationInventory(string Repository, RepositoryFormat Format, RepositoryKind Kind, int Count, IReadOnlyList Items); + +/// An item could not be replicated; the run logs the message and goes on with the next item. +public sealed class ReplicationItemException : Exception +{ + public ReplicationItemException(string message, bool conflict = false, Exception? inner = null) + : base(message, inner) + { + Conflict = conflict; + } + + /// The target refused because it holds the item already (a version cannot be published twice). + public bool Conflict { get; } +} + +/// +/// What a format needs to replicate: list what the local repository holds, copy an item to or from the peer through the format's +/// own protocol, and delete one on either side. Registered (scoped) beside the format's module and used inside the local repository's +/// scope (); the peer is another BaGet server (). Local writes are the +/// administrator's job, not a user's: no caller is checked, but the maintenance gate is. +/// +public interface IFormatReplicator : IFormatService +{ + /// How names are compared (NuGet ids ignore case). + StringComparer NameComparer => StringComparer.Ordinal; + + /// Everything the local repository holds that replication copies. A virtual repository holds none. + Task> ListAsync(CancellationToken cancellationToken); + + /// Sends the local item to the peer's repository. + /// Bytes of content sent. + /// The item could not be sent. + Task PushAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken); + + /// Fetches the item from the peer's repository and stores it locally. + /// Bytes of content received. + /// The item could not be fetched or stored. + Task PullAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken); + + /// + /// Replaces the local copy of the item with the peer's (SourceWins on a pull). A format that cannot overwrite in place must + /// fetch and judge the peer's item (integrity, scanning policy) before it removes the local copy, so a refused or failed + /// replacement leaves the local copy as it was. The default (delete, then ) is only for a format that cannot do so. + /// + /// Bytes of content received. + /// The item could not be fetched or stored. + async Task PullReplacingAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken) + { + await DeleteLocalAsync(item, cancellationToken).ConfigureAwait(false); + + return await PullAsync(item, peer, cancellationToken).ConfigureAwait(false); + } + + /// + /// Whether replaces the peer's copy of an item in place (SourceWins on a push). A Docker tag does: + /// the manifest PUT moves it. NuGet, npm and Maven peers refuse to overwrite a stored version or release file, so the engine + /// deletes the peer's copy first (default ), and a peer that then refuses the item stays without it until the next run. + /// + bool PushReplacesInPlace => false; + + /// Deletes the item from the local repository for good. + Task DeleteLocalAsync(ReplicaItem item, CancellationToken cancellationToken); + + /// Deletes the item from the peer's repository through the format's protocol. + Task DeletePeerAsync(ReplicaItem item, ReplicationPeer peer, CancellationToken cancellationToken); +} + +/// +/// Another BaGet server's repository, reached with an HTTP client that already carries the credential for that server's origin +/// (and no other). The replicators build their protocol URLs from it. The credential is the peer's API key, sent as a bearer token. +/// +public sealed class ReplicationPeer : IDisposable +{ + private static readonly JsonSerializerOptions Json = CreateJson(); + + private readonly bool _ownsClient; + + /// A client that authenticates to . + /// The server's base address. + /// The peer's repository name. + /// Whether disposes . + /// The key the client sends, for the protocols that read it from their own header (NuGet's X-NuGet-ApiKey); never logged. + public ReplicationPeer(HttpClient http, Uri server, string repository, bool ownsClient = true, string? apiKey = null) + { + ApiKey = apiKey; + Http = http ?? throw new ArgumentNullException(nameof(http)); + if (server == null) throw new ArgumentNullException(nameof(server)); + Repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _ownsClient = ownsClient; + var text = server.AbsoluteUri; + Server = text.EndsWith('/') ? server : new Uri(text + "/"); + } + + public HttpClient Http { get; } + + /// The peer's API key, for the one protocol (NuGet push) that wants it in a header of its own. + public string? ApiKey { get; } + + /// The server's base address, ending with a slash. + public Uri Server { get; } + + /// The header that carries the peer's key for the protocols that read it from their own header (NuGet). + internal const string ApiKeyHeader = "X-NuGet-ApiKey"; + + /// + /// Adds the peer's key to (a NuGet request, which reads it from its own header) in , only when the request goes to the peer's own origin; + /// any other origin gets no credential and an existing one is removed. + /// + public void AddCredentials(HttpRequestMessage request) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + + request.Headers.Remove(ApiKeyHeader); + if (ApiKey != null && request.RequestUri != null && SameOrigin(request.RequestUri)) request.Headers.TryAddWithoutValidation(ApiKeyHeader, ApiKey); + } + + private bool SameOrigin(Uri uri) => uri.IsAbsoluteUri + && string.Equals(uri.Scheme, Server.Scheme, StringComparison.OrdinalIgnoreCase) + && string.Equals(uri.Host, Server.Host, StringComparison.OrdinalIgnoreCase) + && uri.Port == Server.Port; + + /// The redirects a GET or HEAD follows by hand. + internal const int MaxRedirects = 5; + + /// + /// Sends to the peer. The client does not follow redirects (the factory builds it that way), so a + /// credential can never be carried to a redirect target: a GET or HEAD redirect is followed here, getting the credential header + /// only when the target is the peer's own origin; any other redirect, or a redirect of a request with a body, is returned as is + /// (and fails as a non-success answer). + /// + public async Task SendAsync(HttpRequestMessage request, HttpCompletionOption completion, CancellationToken cancellationToken) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + + // Only a request that asked for the key header (the NuGet protocol's) gets it; the others authenticate in the client's handler. + var withKey = request.Headers.Contains(ApiKeyHeader); + if (withKey) AddCredentials(request); + var response = await Http.SendAsync(request, completion, cancellationToken).ConfigureAwait(false); + for (var hops = 0; hops < MaxRedirects; hops++) + { + var location = response.Headers.Location; + var redirect = (int)response.StatusCode is 301 or 302 or 303 or 307 or 308; + if (!redirect || location == null || request.Content != null || (request.Method != HttpMethod.Get && request.Method != HttpMethod.Head)) break; + + var target = request.RequestUri != null && !location.IsAbsoluteUri ? new Uri(request.RequestUri, location) : location; + if (!target.IsAbsoluteUri || (target.Scheme != Uri.UriSchemeHttp && target.Scheme != Uri.UriSchemeHttps)) break; + // Never from https to http. + if (request.RequestUri != null && request.RequestUri.Scheme == Uri.UriSchemeHttps && target.Scheme == Uri.UriSchemeHttp) break; + + response.Dispose(); + var next = new HttpRequestMessage(request.Method, target); + foreach (var header in request.Headers) + { + if (!string.Equals(header.Key, ApiKeyHeader, StringComparison.OrdinalIgnoreCase) && !string.Equals(header.Key, "Authorization", StringComparison.OrdinalIgnoreCase)) next.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + + if (withKey) AddCredentials(next); + request = next; + response = await Http.SendAsync(request, completion, cancellationToken).ConfigureAwait(false); + } + + return response; + } + + /// The peer's repository. + public string Repository { get; } + + /// The path in front of the peer repository's routes: nothing for default, else r/{name}/. + public string PathPrefix => string.Equals(Repository, BaGet.Core.Repository.DefaultName, StringComparison.Ordinal) + ? string.Empty + : "r/" + Uri.EscapeDataString(Repository) + "/"; + + /// A URL below the peer repository's feed root ({server}/r/{name}/{relative}). + public Uri Feed(string relative) => new(Server, PathPrefix + relative); + + /// A URL below the server root ({server}/{relative}), where Docker's v2 routes live. + public Uri Root(string relative) => new(Server, relative); + + /// Asks the peer what its repository holds (summary: only the count and the kind). + /// The peer refused or answered something that is not an inventory. + public async Task GetInventoryAsync(bool summary, CancellationToken cancellationToken) + { + var url = Root("api/v1/replication/inventory/" + Uri.EscapeDataString(Repository) + (summary ? "?summary=true" : string.Empty)); + using var response = await SendAsync(new HttpRequestMessage(HttpMethod.Get, url), HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + throw new ReplicationItemException(response.StatusCode switch + { + System.Net.HttpStatusCode.Unauthorized => "The peer refused the API key (401). It needs the admin:api scope of an administrator.", + System.Net.HttpStatusCode.Forbidden => "The peer refused the API key (403). It needs the admin:api scope of an administrator.", + System.Net.HttpStatusCode.NotFound => $"The peer has no repository '{Repository}' (or is not a BaGet server with replication).", + _ => $"The peer answered {(int)response.StatusCode} to the inventory request.", + }); + } + + try + { + return await response.Content.ReadFromJsonAsync(Json, cancellationToken).ConfigureAwait(false) + ?? throw new ReplicationItemException("The peer's inventory is empty."); + } + catch (JsonException e) + { + throw new ReplicationItemException("The peer did not answer with an inventory.", inner: e); + } + } + + /// Fails with a message (never the credential) unless succeeded. + /// The peer's answer. + /// What was asked, for the message (push, download). + /// The item. + public static async Task EnsureAsync(HttpResponseMessage response, string what, ReplicaItem item) + { + if (response.IsSuccessStatusCode) return; + + var body = string.Empty; + try + { + body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + } + catch (Exception e) when (e is HttpRequestException or InvalidOperationException) + { + // The status alone is the message. + } + + body = body.Length > 200 ? body.Substring(0, 200) : body; + throw new ReplicationItemException( + $"The peer answered {(int)response.StatusCode} to the {what} of {item}{(string.IsNullOrWhiteSpace(body) ? "." : ": " + body.Trim())}", + conflict: response.StatusCode == System.Net.HttpStatusCode.Conflict); + } + + public void Dispose() + { + if (_ownsClient) Http.Dispose(); + } + + /// The serializer options of the inventory (shared with the API's response). + public static JsonSerializerOptions JsonOptions => Json; + + private static JsonSerializerOptions CreateJson() + { + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; + options.Converters.Add(new JsonStringEnumConverter()); + + return options; + } +} + +/// +/// The seam that lets a background job run once cluster-wide. Replication takes the lease named after a configuration before every +/// run; the in-process default (a single node) is replaced by (a lease in the shared store) when Ha:Enabled, so two nodes do not run the same job at once. Retention, scanning, the staging sweep, validation and the admin operations take leases through the same service. +/// +public interface IJobLease +{ + /// Tries to take the lease for . + /// The job's name (replication:{configuration key}). + /// Cancels waiting. + /// The held lease (dispose it to release), or null when another holder has it: the caller skips the run. + ValueTask TryAcquireAsync(string job, CancellationToken cancellationToken); +} + +/// The single-node : a lease is held until it is disposed, in this process only. +public sealed class InProcessJobLease : IJobLease +{ + private readonly object _lock = new(); + private readonly HashSet _held = new(StringComparer.Ordinal); + + /// + public ValueTask TryAcquireAsync(string job, CancellationToken cancellationToken) + { + if (job == null) throw new ArgumentNullException(nameof(job)); + + lock (_lock) + { + if (!_held.Add(job)) return new ValueTask((IAsyncDisposable?)null); + } + + return new ValueTask(new Lease(this, job)); + } + + private sealed class Lease : IAsyncDisposable + { + private InProcessJobLease? _owner; + private readonly string _job; + + public Lease(InProcessJobLease owner, string job) + { + _owner = owner; + _job = job; + } + + public ValueTask DisposeAsync() + { + var owner = Interlocked.Exchange(ref _owner, null); + if (owner != null) + { + lock (owner._lock) owner._held.Remove(_job); + } + + return default; + } + } +} diff --git a/src/BaGet.Core/Replication/ReplicationPlanner.cs b/src/BaGet.Core/Replication/ReplicationPlanner.cs new file mode 100644 index 000000000..8493ce785 --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationPlanner.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Core; + +/// What a run will do, worked out from both inventories and the ledger by . +public sealed class ReplicationPlan +{ + /// Source items the target lacks: copy them. + public List Copy { get; } = new(); + + /// Items held with different content on both sides while the source wins: delete at the target, then copy. + public List Replace { get; } = new(); + + /// Items held with different content on both sides while the target wins: left alone, logged. + public List Conflicts { get; } = new(); + + /// Items copied earlier that the source no longer holds but the target still does (delete propagation). + public List Delete { get; } = new(); + + /// Ledger entries to drop: the item is gone from both sides, or from the source while propagation is off. + public List Forget { get; } = new(); + + /// Items the target holds already with the same content. + public int Skipped { get; set; } + + /// Items looked at: every source item plus every target-only ledger item. + public int Examined { get; set; } +} + +/// +/// The decision part of a run, free of I/O so it can be tested exhaustively: what to copy, replace, leave, delete or forget. +/// +public static class ReplicationPlanner +{ + /// The identity of an item: name (compared the format's way), version and part. + public static IEqualityComparer KeyComparer(StringComparer names) => new ItemKeyComparer(names); + + /// Works out the plan. + /// What the sending side holds. + /// What the receiving side holds. + /// What this configuration copied earlier (its ledger). + /// How the format compares names. + /// What to do when both sides hold the item with different content. + /// Whether an item copied earlier and gone from the source is deleted at the target. + public static ReplicationPlan Plan( + IReadOnlyCollection source, + IReadOnlyCollection target, + IReadOnlyCollection ledger, + StringComparer names, + ReplicationConflict conflict, + bool propagateDeletes) + { + var comparer = new ItemKeyComparer(names); + var sourceByKey = source.GroupBy(i => i, comparer).ToDictionary(g => g.Key, g => g.First(), comparer); + var targetByKey = target.GroupBy(i => i, comparer).ToDictionary(g => g.Key, g => g.First(), comparer); + var plan = new ReplicationPlan(); + + foreach (var item in sourceByKey.Values.OrderBy(i => i.Name, names).ThenBy(i => i.Version, StringComparer.Ordinal).ThenBy(i => i.Part, StringComparer.Ordinal)) + { + plan.Examined++; + if (!targetByKey.TryGetValue(item, out var held)) plan.Copy.Add(item); + else if (!item.DiffersFrom(held)) plan.Skipped++; + else if (conflict == ReplicationConflict.SourceWins) plan.Replace.Add(item); + else plan.Conflicts.Add(item); + } + + foreach (var entry in ledger) + { + if (sourceByKey.ContainsKey(entry)) continue; + + plan.Examined++; + if (propagateDeletes && targetByKey.TryGetValue(entry, out var held)) + { + // Content the target changed after it was replicated is deleted only when the source wins; else it is left alone. + if (!entry.DiffersFrom(held) || conflict == ReplicationConflict.SourceWins) plan.Delete.Add(held); + else plan.Forget.Add(entry); + } + else plan.Forget.Add(entry); + } + + return plan; + } + + private sealed class ItemKeyComparer : IEqualityComparer + { + private readonly StringComparer _names; + + public ItemKeyComparer(StringComparer names) + { + _names = names; + } + + public bool Equals(ReplicaItem? x, ReplicaItem? y) + => x != null && y != null + && _names.Equals(x.Name, y.Name) + && string.Equals(x.Version, y.Version, StringComparison.Ordinal) + && string.Equals(x.Part, y.Part, StringComparison.Ordinal); + + public int GetHashCode(ReplicaItem item) => HashCode.Combine(_names.GetHashCode(item.Name), item.Version, item.Part); + } +} diff --git a/src/BaGet.Core/Replication/ReplicationTransfer.cs b/src/BaGet.Core/Replication/ReplicationTransfer.cs new file mode 100644 index 000000000..83f5c257f --- /dev/null +++ b/src/BaGet.Core/Replication/ReplicationTransfer.cs @@ -0,0 +1,92 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// The HTTP and file plumbing the format replicators share: a download spooled to a temporary file (memory is the metadata, never the +/// artifact), an upload streamed from a file or a store, and the mapping of transport failures. A transport failure +/// (, a timeout) is deliberately not turned into a : the +/// run treats it as "the peer cannot be reached" and stops, so it can be resumed, instead of failing every remaining item. +/// +internal static class ReplicationTransfer +{ + /// GET , failing with a message unless it succeeds. The caller disposes the response. + public static async Task GetAsync(ReplicationPeer peer, Uri url, ReplicaItem item, CancellationToken cancellationToken, Action? configure = null) + { + var request = new HttpRequestMessage(HttpMethod.Get, url); + configure?.Invoke(request); + var response = await peer.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + try + { + await ReplicationPeer.EnsureAsync(response, "download", item).ConfigureAwait(false); + + return response; + } + catch + { + response.Dispose(); + + throw; + } + } + + /// Copies to a temporary file that deletes itself when closed; positioned at the start. + public static async Task SpoolAsync(Stream source, CancellationToken cancellationToken) + { + var path = Path.Combine(Path.GetTempPath(), "baget-replication-" + Guid.NewGuid().ToString("N")); + var file = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 81920, FileOptions.Asynchronous | FileOptions.DeleteOnClose); + try + { + await source.CopyToAsync(file, 81920, cancellationToken).ConfigureAwait(false); + file.Position = 0; + + return file; + } + catch + { + file.Dispose(); + + throw; + } + } + + /// Sends ; a success is returned, anything else fails with a message naming . + public static async Task SendAsync(ReplicationPeer peer, HttpRequestMessage request, string what, ReplicaItem item, CancellationToken cancellationToken, bool allowNotFound = false) + { + using (request) + { + using var response = await peer.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (allowNotFound && response.StatusCode == System.Net.HttpStatusCode.NotFound) return; + + await ReplicationPeer.EnsureAsync(response, what, item).ConfigureAwait(false); + } + } + + /// A binary body of a known length. + public static StreamContent Binary(Stream content, string mediaType = "application/octet-stream") + { + var body = new StreamContent(content, 81920); + body.Headers.ContentType = new MediaTypeHeaderValue(mediaType); + if (content.CanSeek) body.Headers.ContentLength = content.Length - content.Position; + + return body; + } + + /// The length of a stream the store hands out (counted when it cannot say). + public static async Task LengthAsync(Stream stream, CancellationToken cancellationToken) + { + if (stream.CanSeek) return stream.Length; + + long total = 0; + var buffer = new byte[81920]; + int read; + while ((read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) total += read; + + return total; + } +} diff --git a/src/BaGet.Core/Repositories/IRepositoryAccess.cs b/src/BaGet.Core/Repositories/IRepositoryAccess.cs new file mode 100644 index 000000000..58fdd2a9b --- /dev/null +++ b/src/BaGet.Core/Repositories/IRepositoryAccess.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Which repositories a caller may see and publish to in the web UI. The one place the pages ask, so an access model +/// (groups, permission targets) replaces without touching a page: the header +/// switcher lists , a repository page answers 404 unless , and +/// the upload page offers and opens only for . +/// +public interface IRepositoryAccess +{ + /// + /// Whether the UI offers repositories beyond default at all. False when the database or the search index can + /// hold the default repository only (Azure Table, Azure Search): switchers and pickers are then hidden. + /// + bool SupportsMultipleRepositories { get; } + + /// The repositories (of every format) may read, ordered by name (default first). + Task> ReadableAsync(ClaimsPrincipal? user, CancellationToken cancellationToken); + + /// The repositories may publish to, ordered like . + Task> WritableAsync(ClaimsPrincipal? user, CancellationToken cancellationToken); + + /// + /// Whether may open the upload page of . The page shows no + /// package data of the repository (only the file being staged), so it needs the right to publish, not to read: a + /// drop box (Deploy without Read) is usable. A visitor who is not signed in pushes with an API key typed into the + /// page, authorized per package on submit, so the default is . + /// + Task CanWriteAsync(ClaimsPrincipal? user, RepositoryInfo repository, CancellationToken cancellationToken) + => CanReadAsync(user, repository, cancellationToken); + + /// Whether may read (open pages of) . + Task CanReadAsync(ClaimsPrincipal? user, RepositoryInfo repository, CancellationToken cancellationToken); + + /// + /// Whether may read the pages of package in + /// : plus the include/exclude patterns of the Read grants. + /// The default ignores the package, for an implementation without package-level rules. + /// + Task CanReadPackageAsync(ClaimsPrincipal? user, RepositoryInfo repository, string packageId, CancellationToken cancellationToken) + => CanReadAsync(user, repository, cancellationToken); +} + +/// +/// Today's rule: every repository is readable, and writable by whoever the package authorization lets push (which +/// the upload page still checks per package). Replaced when an access model exists. +/// +public sealed class OpenRepositoryAccess : IRepositoryAccess +{ + private readonly IRepositoryService _repositories; + + public OpenRepositoryAccess(IRepositoryService repositories) + { + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + } + + /// + public bool SupportsMultipleRepositories => _repositories.SupportsMultipleRepositories; + + /// + public async Task> ReadableAsync(ClaimsPrincipal? user, CancellationToken cancellationToken) + { + if (!SupportsMultipleRepositories) return new[] { RepositoryInfo.Default }; + + var all = await _repositories.ListAsync(cancellationToken); + + return all + .OrderBy(r => r.IsDefault ? 0 : 1) + .ThenBy(r => r.Name, StringComparer.Ordinal) + .ToList(); + } + + /// + public Task> WritableAsync(ClaimsPrincipal? user, CancellationToken cancellationToken) + => ReadableAsync(user, cancellationToken); + + /// + public Task CanReadAsync(ClaimsPrincipal? user, RepositoryInfo repository, CancellationToken cancellationToken) + => Task.FromResult(true); +} diff --git a/src/BaGet.Core/Repositories/IRepositoryAdministration.cs b/src/BaGet.Core/Repositories/IRepositoryAdministration.cs new file mode 100644 index 000000000..fa0fc63a6 --- /dev/null +++ b/src/BaGet.Core/Repositories/IRepositoryAdministration.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// A repository as the administration pages list it. +/// +/// The . +/// The . +/// The package format served. +/// How the repository gets its content. +/// Whether requests without credentials may read it. +/// When the repository was created (UTC). +/// How many package versions it holds. +public sealed record RepositorySummary( + int Key, + string Name, + RepositoryFormat Format, + RepositoryKind Kind, + bool AnonymousRead, + DateTime Created, + int PackageCount) +{ + /// + /// Whether this is the repository, which can be neither renamed nor deleted. + /// + public bool IsDefault => Key == Repository.DefaultKey; +} + +/// +/// The one rule that narrows a repository list by format, kind or a name fragment, shared by the Repositories page and +/// GET /api/v1/repositories so the two cannot answer differently. +/// +public static class RepositorySummaryFilter +{ + /// + /// Keeps the repositories whose format name and kind name equal and + /// (ignoring case) and whose name contains (ignoring case); an empty filter keeps everything. + /// + public static IEnumerable Apply(IEnumerable repositories, string? format, string? kind, string? nameFragment) + => repositories + .Where(r => string.IsNullOrEmpty(format) || string.Equals(r.Format.ToString(), format, StringComparison.OrdinalIgnoreCase)) + .Where(r => string.IsNullOrEmpty(kind) || string.Equals(r.Kind.ToString(), kind, StringComparison.OrdinalIgnoreCase)) + .Where(r => string.IsNullOrEmpty(nameFragment) || r.Name.Contains(nameFragment, StringComparison.OrdinalIgnoreCase)); +} + +/// +/// Lists, edits and deletes repositories (creating goes through ). What the +/// administrator pages use; writes go through the database context, so they are refused while the +/// is closed. +/// +public interface IRepositoryAdministration +{ + /// + /// Every repository with its package count, ordered by name; the default one included. + /// + Task> ListAsync(CancellationToken cancellationToken); + + /// + /// Finds a repository by exact name. + /// + /// The repository, or null. + Task FindAsync(string? name, CancellationToken cancellationToken); + + /// + /// Sets , the shortcut for the Everyone group's Read on the repository. + /// Off, the group's Read grants no longer apply there (callers need a Read grant of their own). On, it applies + /// again, and when no target grants Everyone Read on the repository any more (an administrator deleted + /// the seeded one) a target Anonymous read {name} is created, so the flag never claims what the grants deny. + /// Audited. A repository is never renamed: its name is in URLs and storage paths. + /// + /// The repository. + /// The new value. + /// The cancellation token. + /// The user name recorded in the audit log. + /// No such repository. + Task SetAnonymousReadAsync(string name, bool anonymousRead, CancellationToken cancellationToken, string? actor = null); + + /// + /// Deletes a repository that holds no packages and no submission awaiting validation, together with its catalog + /// entries, owner rows, validations and abuse reports, and every file it kept in storage (repos/{name}/) when + /// the store can list its content. + /// + /// No such repository. + /// It is the default repository. + /// It still holds packages (delete them first) or a submission awaiting + /// validation (wait for it or let it fail). Its catalog entries, owners, finished validations and abuse reports are + /// history and are removed with the repository. + Task DeleteAsync(string name, CancellationToken cancellationToken); +} + +/// +/// The default repository cannot be renamed or deleted. +/// +public sealed class RepositoryProtectedException : InvalidOperationException +{ + public RepositoryProtectedException() + : base($"The '{Repository.DefaultName}' repository is served at the root and cannot be deleted.") + { } +} + +/// +/// The repository still has content, so it cannot be deleted. +/// +/// +/// Thrown when a repository that virtual repositories list as a member is deleted: they would lose a member. +/// +public sealed class RepositoryReferencedException : InvalidOperationException +{ + public RepositoryReferencedException(string name, IReadOnlyList virtualRepositories) + : base($"The repository '{name}' is a member of the virtual repositor{(virtualRepositories.Count == 1 ? "y" : "ies")} {string.Join(", ", virtualRepositories.Select(v => "'" + v + "'"))}. Remove it from {(virtualRepositories.Count == 1 ? "it" : "them")} first.") + { + VirtualRepositories = virtualRepositories; + } + + /// The virtual repositories that list the repository. + public IReadOnlyList VirtualRepositories { get; } +} + +public sealed class RepositoryNotEmptyException : InvalidOperationException +{ + public RepositoryNotEmptyException(string name, bool awaitingValidation = false, bool remote = false) + : base(awaitingValidation + ? $"The repository '{name}' still has submissions awaiting validation. Wait for them to finish; its history (catalog entries, owners) is removed with the repository." + : remote + ? $"The repository '{name}' still holds cached packages. Purge its cache first; its history (catalog entries) is removed with the repository." + : $"The repository '{name}' still holds packages. Delete them first; its history (catalog entries, owners) is removed with the repository.") + { } +} diff --git a/src/BaGet.Core/Repositories/IRepositoryContext.cs b/src/BaGet.Core/Repositories/IRepositoryContext.cs new file mode 100644 index 000000000..73dff3799 --- /dev/null +++ b/src/BaGet.Core/Repositories/IRepositoryContext.cs @@ -0,0 +1,75 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Core; + +/// +/// The repository the current request, job or command works in. Scoped. Defaults to the +/// repository, so code that never selects one behaves as before repositories. +/// +/// +/// Whoever decides the repository (the routing middleware from /r/{repo}, a background worker, the CLI) +/// calls once, before anything queries the database: the database context filters its +/// repository-scoped tables on . +/// creates a DI scope already pinned to a +/// repository, for code outside a request. +/// +public interface IRepositoryContext +{ + /// + /// The repository in effect. + /// + RepositoryInfo Current { get; } + + /// + /// Selects the repository for the rest of this scope. + /// + void Use(RepositoryInfo repository); +} + +/// +/// The scoped . +/// +public sealed class RepositoryContext : IRepositoryContext +{ + private volatile RepositoryInfo _current = RepositoryInfo.Default; + + /// + public RepositoryInfo Current => _current; + + /// + public void Use(RepositoryInfo repository) + { + _current = repository ?? throw new ArgumentNullException(nameof(repository)); + } +} + +public static class RepositoryScopeExtensions +{ + /// + /// Creates a DI scope whose is already set to . + /// For background services and commands that work on a given repository; dispose it when done. + /// + public static IServiceScope CreateRepositoryScope(this IServiceScopeFactory factory, RepositoryInfo repository) + { + if (factory == null) throw new ArgumentNullException(nameof(factory)); + if (repository == null) throw new ArgumentNullException(nameof(repository)); + + var scope = factory.CreateScope(); + scope.ServiceProvider.GetRequiredService().Use(repository); + return scope; + } +} + +/// +/// The context used when nothing selected a repository: always the default one. +/// +internal sealed class DefaultRepositoryContext : IRepositoryContext +{ + public static readonly DefaultRepositoryContext Instance = new(); + + public RepositoryInfo Current => RepositoryInfo.Default; + + public void Use(RepositoryInfo repository) + => throw new InvalidOperationException("No repository scope is available; create one with CreateRepositoryScope."); +} diff --git a/src/BaGet.Core/Repositories/IRepositoryService.cs b/src/BaGet.Core/Repositories/IRepositoryService.cs new file mode 100644 index 000000000..add1a2839 --- /dev/null +++ b/src/BaGet.Core/Repositories/IRepositoryService.cs @@ -0,0 +1,111 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Looks up and creates repositories. What routing uses to turn /r/{name} into the +/// it passes to . +/// +public interface IRepositoryService +{ + /// + /// Whether the database can hold repositories beyond . False for a + /// non-relational database (Azure Table): there only the default repository exists. + /// + bool SupportsMultipleRepositories { get; } + + /// + /// Finds a repository by name (exact, as names are lowercase). + /// + /// The repository, or null. The default repository is always found. + Task FindAsync(string? name, CancellationToken cancellationToken); + + /// + /// Finds a repository by key; for code that holds a row's and must + /// work in that repository (a queued validation, for one). + /// + /// The repository, or null. The default repository is always found. + Task FindAsync(int key, CancellationToken cancellationToken); + + /// + /// Every repository, ordered by name; the default one included. + /// + Task> ListAsync(CancellationToken cancellationToken); + + /// + /// Creates a repository. A one needs its upstream: use + /// . + /// + /// The name is invalid per . + /// The database cannot hold repositories, or the format/kind is not available yet. + /// The name is taken. + Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + CancellationToken cancellationToken); + + /// + /// Creates a repository; is the upstream of a one + /// (required for it, refused for the other kinds). The password is stored protected. + /// + /// The name is invalid, or the upstream settings are missing, unneeded or invalid (the message lists the problems). + /// The database cannot hold repositories, or the format/kind is not available yet (virtual). + /// A password was given and nothing can protect it (no data protection on the host). + /// The name is taken. + Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + RemoteRepositorySettings? remote, + CancellationToken cancellationToken); + + /// + /// Like + /// with chosen by the caller. The overload without it creates a remote + /// repository with credentials (a user name or password) readable only by authenticated callers, since otherwise + /// everything its credentials can fetch would be served to anyone; every other repository starts anonymously + /// readable, like the default one. + /// + Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + RemoteRepositorySettings? remote, + bool anonymousRead, + CancellationToken cancellationToken); + + /// + /// Creates a repository of a format whose asks for fields of its own + /// (): are turned into the repository's settings by + /// . Not for remote repositories, which take their upstream through + /// . + /// + /// The name or a field is invalid. + /// The database cannot hold repositories, or no module of the format offers the kind. + /// The name is taken. + Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + System.Collections.Generic.IReadOnlyDictionary fields, + bool anonymousRead, + CancellationToken cancellationToken); + + /// + /// Creates the default repository if the database has none. Idempotent; called at startup, after migrations. + /// + Task EnsureDefaultAsync(CancellationToken cancellationToken); +} + +/// +/// A repository with that name exists. +/// +public sealed class RepositoryExistsException : System.InvalidOperationException +{ + public RepositoryExistsException(string name) + : base($"A repository named '{name}' already exists.") + { } +} diff --git a/src/BaGet.Core/Repositories/Remote/KeyedLocks.cs b/src/BaGet.Core/Repositories/Remote/KeyedLocks.cs new file mode 100644 index 000000000..99cd4c315 --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/KeyedLocks.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// One holder per key at a time; a key's semaphore is dropped when nobody holds or waits for it. +internal sealed class KeyedLocks +{ + private readonly object _sync = new(); + private readonly Dictionary _entries = new(); + + public async Task LockAsync(string key, CancellationToken cancellationToken) + { + SemaphoreSlim gate; + lock (_sync) + { + if (!_entries.TryGetValue(key, out var entry)) entry = (new SemaphoreSlim(1, 1), 0); + _entries[key] = (entry.Gate, entry.Users + 1); + gate = entry.Gate; + } + + try + { + await gate.WaitAsync(cancellationToken).ConfigureAwait(false); + } + catch + { + Release(key, held: false); + + throw; + } + + return new Releaser(this, key); + } + + private void Release(string key, bool held) + { + lock (_sync) + { + var entry = _entries[key]; + if (held) entry.Gate.Release(); + if (entry.Users <= 1) + { + _entries.Remove(key); + } + else + { + _entries[key] = (entry.Gate, entry.Users - 1); + } + } + } + + private sealed class Releaser : IDisposable + { + private readonly KeyedLocks _owner; + private readonly string _key; + private int _done; + + public Releaser(KeyedLocks owner, string key) + { + _owner = owner; + _key = key; + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _done, 1) == 0) _owner.Release(_key, held: true); + } + } +} diff --git a/src/BaGet.Core/Repositories/Remote/PolicyAwareProxy.cs b/src/BaGet.Core/Repositories/Remote/PolicyAwareProxy.cs new file mode 100644 index 000000000..4b1f7940d --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/PolicyAwareProxy.cs @@ -0,0 +1,30 @@ +using System; +using System.Net; +using System.Net.Http; + +namespace BaGet.Core; + +/// +/// The system proxy, except while Remote:BlockPrivateAddresses is on: a connection through a proxy reaches the proxy's address, so the +/// policy could not see (or refuse) the target's. With the policy on every request is made directly. +/// +internal sealed class PolicyAwareProxy : IWebProxy +{ + private readonly Func _blocking; + private readonly IWebProxy _system = HttpClient.DefaultProxy; + + public PolicyAwareProxy(Func blocking) + { + _blocking = blocking ?? throw new ArgumentNullException(nameof(blocking)); + } + + public ICredentials? Credentials + { + get => _system.Credentials; + set => _system.Credentials = value; + } + + public Uri? GetProxy(Uri destination) => _blocking() ? destination : _system.GetProxy(destination); + + public bool IsBypassed(Uri host) => _blocking() || _system.IsBypassed(host); +} diff --git a/src/BaGet.Core/Repositories/Remote/RemoteAddressPolicy.cs b/src/BaGet.Core/Repositories/Remote/RemoteAddressPolicy.cs new file mode 100644 index 000000000..79930a066 --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/RemoteAddressPolicy.cs @@ -0,0 +1,126 @@ +using System; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Raised when a connection is refused because Remote:BlockPrivateAddresses forbids the address. +/// +internal sealed class PrivateAddressException : Exception +{ + public PrivateAddressException() : base(RemoteAddressPolicy.Message) + { + } +} + +/// +/// Decides which upstream addresses refuses. +/// +public static class RemoteAddressPolicy +{ + /// The reason shown when an address is refused. + public const string Message = "The upstream is a loopback, private, link-local or otherwise non-public address, which Remote:BlockPrivateAddresses refuses."; + + /// Whether is not a public unicast address. + public static bool IsBlocked(IPAddress address) + { + if (address == null) throw new ArgumentNullException(nameof(address)); + + if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4(); + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) return true; + + var bytes = address.GetAddressBytes(); + if (address.AddressFamily == AddressFamily.InterNetwork) + { + return bytes[0] == 0 // 0.0.0.0/8 + || bytes[0] == 10 // 10.0.0.0/8 + || (bytes[0] == 100 && (bytes[1] & 0xC0) == 64) // 100.64.0.0/10 carrier-grade NAT + || (bytes[0] == 169 && bytes[1] == 254) // 169.254.0.0/16 link-local, cloud metadata + || (bytes[0] == 172 && (bytes[1] & 0xF0) == 16) // 172.16.0.0/12 + || (bytes[0] == 192 && bytes[1] == 168) // 192.168.0.0/16 + || (bytes[0] == 192 && bytes[1] == 0 && bytes[2] == 0) // 192.0.0.0/24 + || bytes[0] >= 224; // multicast, reserved, broadcast + } + + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + // IPv6 forms that carry an IPv4 address are judged by the address they carry: IPv4-compatible ::a.b.c.d, + // NAT64 64:ff9b::/96 and 6to4 2002::/16. Local-use NAT64 64:ff9b:1::/48 is refused whole. + var embedded = EmbeddedIPv4(bytes); + if (embedded != null) return IsBlocked(embedded); + if (bytes[0] == 0x00 && bytes[1] == 0x64 && bytes[2] == 0xff && bytes[3] == 0x9b && bytes[4] == 0x00 && bytes[5] == 0x01) return true; + + return address.IsIPv6LinkLocal + || address.IsIPv6SiteLocal + || address.IsIPv6Multicast + || (bytes[0] & 0xFE) == 0xFC; // fc00::/7 unique-local + } + + return true; + } + + private static IPAddress? EmbeddedIPv4(byte[] v6) + { + var tail = new byte[4]; + if (v6.Take(12).All(b => b == 0) && !(v6[12] == 0 && v6[13] == 0 && v6[14] == 0 && v6[15] <= 1)) + { + Array.Copy(v6, 12, tail, 0, 4); // ::a.b.c.d (:: and ::1 are judged as IPv6) + } + else if (v6[0] == 0x00 && v6[1] == 0x64 && v6[2] == 0xff && v6[3] == 0x9b && v6.Skip(4).Take(8).All(b => b == 0)) + { + Array.Copy(v6, 12, tail, 0, 4); // 64:ff9b::/96 + } + else if (v6[0] == 0x20 && v6[1] == 0x02) + { + Array.Copy(v6, 2, tail, 0, 4); // 2002::/16, the IPv4 address follows the prefix + } + else + { + return null; + } + + return new IPAddress(tail); + } + + /// + /// A problem with the host named in that needs no DNS lookup (localhost or a literal + /// address), or null. + /// + public static string? CheckLiteral(Uri? url) + { + if (url == null) return null; + + var host = url.IdnHost; + if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase)) + { + return Message; + } + + return IPAddress.TryParse(host.Trim('[', ']'), out var address) && IsBlocked(address) ? Message : null; + } + + /// + /// A problem with the host of after resolving it (any resolved address refused refuses the + /// host), or null. A name that does not resolve is not a policy problem (the connection will fail on its own). + /// + public static async Task CheckResolvedAsync(Uri? url, CancellationToken cancellationToken) + { + var literal = CheckLiteral(url); + if (literal != null || url == null) return literal; + + try + { + var addresses = await Dns.GetHostAddressesAsync(url.IdnHost, cancellationToken).ConfigureAwait(false); + + return addresses.Any(IsBlocked) ? Message : null; + } + catch (SocketException) + { + return null; + } + } +} diff --git a/src/BaGet.Core/Repositories/Remote/RemoteHttpClientFactory.cs b/src/BaGet.Core/Repositories/Remote/RemoteHttpClientFactory.cs new file mode 100644 index 000000000..94a05202c --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/RemoteHttpClientFactory.cs @@ -0,0 +1,169 @@ +using System; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// Creates the that talks to a remote repository's upstream. Replace it (a test, a host +/// with its own proxy or certificate rules) by registering another implementation. +/// +public interface IRemoteHttpClientFactory +{ + /// + /// A client for : the download timeout applied and, when credentials are configured, + /// HTTP Basic sent to the upstream's own host only (never to a host a redirect or a service index points to). + /// + HttpClient Create(RemoteRepositorySettings settings); + + /// + /// Like for a one-off probe (Test connection): the client must not follow redirects itself, so + /// the caller decides whether to follow one. The default returns . + /// + HttpClient CreateProbe(RemoteRepositorySettings settings) => Create(settings); +} + +/// +/// The default . +/// +public class RemoteHttpClientFactory : IRemoteHttpClientFactory +{ + private readonly IOptionsMonitor? _options; + + /// A factory that connects to any address. + public RemoteHttpClientFactory() + { + } + + /// The Remote:* options; with on every connection to a non-public address is refused (read on each connection, so the setting is live). + public RemoteHttpClientFactory(IOptionsMonitor options) + { + _options = options; + } + + /// + public HttpClient Create(RemoteRepositorySettings settings) => Build(settings, followRedirects: true); + + /// + public HttpClient CreateProbe(RemoteRepositorySettings settings) => Build(settings, followRedirects: false); + + private HttpClient Build(RemoteRepositorySettings settings, bool followRedirects) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + var handler = CreateInnerHandler(); + if (!followRedirects && handler is SocketsHttpHandler sockets) sockets.AllowAutoRedirect = false; + // A Docker upstream authenticates per request (a challenge, then a token from the realm it names, or Basic): its client + // sends the credentials itself, to the right place, so no handler adds them to every request. + if (settings.HasCredentials && settings.UrlOrNull != null && settings.Protocol != RemoteProtocol.Docker) + { + // An npm upstream with only a password is given a token (npm's _authToken), which is a bearer credential. + var bearer = settings.Protocol == RemoteProtocol.Npm && string.IsNullOrEmpty(settings.Username); + handler = new HostScopedBasicAuthHandler(settings.UrlOrNull, settings.Username, settings.Password, bearer) { InnerHandler = handler }; + } + + var assembly = Assembly.GetEntryAssembly(); + var version = assembly?.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + + var client = new HttpClient(handler) + { + Timeout = TimeSpan.FromSeconds(settings.DownloadTimeoutSeconds), + }; + client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", $"{assembly?.GetName().Name ?? "BaGet"}/{version}"); + + return client; + } + + /// The handler that sends the requests; tests replace it with an in-memory one. + protected virtual HttpMessageHandler CreateInnerHandler() + { + var handler = new SocketsHttpHandler + { + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + }; + + if (_options != null) + { + handler.ConnectCallback = ConnectAsync; + + // Through a proxy the connect callback would see the proxy's address, not the target's: while the policy is on + // (read per request, so the setting stays live) the system proxy is not used and the target is connected to directly. + handler.Proxy = new PolicyAwareProxy(() => _options.CurrentValue.BlockPrivateAddresses); + } + + return handler; + } + + // The ordinary TCP connect, refusing a non-public address while Remote:BlockPrivateAddresses is on. It checks the + // addresses actually connected to, so a name that resolves differently later, or a redirect, cannot get around it. + private async ValueTask ConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken) + { + var endpoint = context.DnsEndPoint; + var addresses = IPAddress.TryParse(endpoint.Host, out var literal) + ? new[] { literal } + : await Dns.GetHostAddressesAsync(endpoint.Host, cancellationToken).ConfigureAwait(false); + + if (_options!.CurrentValue.BlockPrivateAddresses + && (addresses.Any(RemoteAddressPolicy.IsBlocked) + || endpoint.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase))) + { + throw new PrivateAddressException(); + } + + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(addresses, endpoint.Port, cancellationToken).ConfigureAwait(false); + + return new NetworkStream(socket, ownsSocket: true); + } + catch + { + socket.Dispose(); + + throw; + } + } +} + +/// +/// Adds HTTP Basic (or, for a token, Bearer) credentials to requests for one origin (scheme, host, port) and to no other. +/// +internal sealed class HostScopedBasicAuthHandler : DelegatingHandler +{ + private readonly Uri _origin; + private readonly AuthenticationHeaderValue _header; + + public HostScopedBasicAuthHandler(Uri origin, string? username, string? password, bool bearer = false) + { + _origin = origin; + _header = bearer + ? new AuthenticationHeaderValue("Bearer", password ?? string.Empty) + : new AuthenticationHeaderValue( + "Basic", + Convert.ToBase64String(Encoding.UTF8.GetBytes((username ?? string.Empty) + ":" + (password ?? string.Empty)))); + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var uri = request.RequestUri; + if (request.Headers.Authorization == null + && uri != null + && uri.IsAbsoluteUri + && Uri.Compare(uri, _origin, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0) + { + request.Headers.Authorization = _header; + } + + return base.SendAsync(request, cancellationToken); + } +} diff --git a/src/BaGet.Core/Repositories/Remote/RemoteRepositoryAdministration.cs b/src/BaGet.Core/Repositories/Remote/RemoteRepositoryAdministration.cs new file mode 100644 index 000000000..cf75d2d42 --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/RemoteRepositoryAdministration.cs @@ -0,0 +1,850 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// A remote repository as the administration pages edit it. +/// +/// The repository. +/// Its upstream settings. is always null here: the password is never read back to a page. +/// Whether a password is stored. +/// Whether it is the repository the default repository fetches through while Mirror:Enabled is set (its URL, protocol and timeout then come from Mirror:*). +public sealed record RemoteRepositoryDetail( + RepositoryInfo Repository, + RemoteRepositorySettings Settings, + bool HasPassword, + bool IsMirror); + +/// +/// The outcome of asking an upstream whether it answers. +/// +/// Whether the upstream answered as the configured protocol requires. +/// What was found or what failed, without URLs or credentials. +/// The HTTP status, when there was an answer. +/// How long the attempt took. +public sealed record RemoteConnectionResult(bool Success, string Message, int? StatusCode, long ElapsedMilliseconds); + +/// +/// What a remote repository holds and remembers. +/// +/// The in-memory cache and upstream health (this node). +/// Package versions stored. +/// Distinct package ids stored. +/// Bytes of the blobs stored (a Docker repository: its layers); 0 when the format does not report it. +public sealed record RemoteCacheOverview(RemoteCacheStatus Status, int PackageCount, int PackageIdCount, long StoredBytes = 0); + +/// +/// What a purge removed. +/// +/// Stored package versions deleted (database rows and files). +/// Remembered upstream answers dropped. +public sealed record PurgeResult(int Packages, int CachedAnswers); + +/// +/// Edits, tests and empties remote repositories (creating goes through ). +/// What the administrator pages use; writes go through the database context, so they are refused while the +/// is closed. +/// +public interface IRemoteRepositoryAdministration +{ + /// A remote repository by exact name, or null when there is none (or it is not remote). + Task FindAsync(string? name, CancellationToken cancellationToken); + + /// + /// Saves the upstream settings of a remote repository and forgets what was cached from the old ones. A blank + /// keeps the stored one unless . + /// Audited (the audit entry says whether the password changed, never what it is). + /// + /// No such remote repository. + /// The settings are invalid; the message lists the problems. + /// A password cannot be stored (no data protection). + Task UpdateAsync(string name, RemoteRepositorySettings input, bool clearPassword, CancellationToken cancellationToken, string? actor = null); + + /// + /// Asks the upstream described by (unsaved) whether it answers, sending the credentials + /// as a client would. When is given a blank password means the stored one. Saves nothing. + /// + Task TestConnectionAsync(string? name, RemoteRepositorySettings input, CancellationToken cancellationToken); + + /// What the repository stores and what this node remembers about its upstream. + /// No such remote repository. + Task GetCacheAsync(string name, CancellationToken cancellationToken); + + /// + /// Deletes every package the repository stored (database and files) and drops the remembered answers; the next + /// request fetches again. Audited. + /// + /// No such remote repository. + Task PurgeAsync(string name, CancellationToken cancellationToken, string? actor = null); + + /// + /// Deletes one stored package (every version when is null) and drops the answers + /// remembered about it. Audited. + /// + /// No such remote repository. + Task PurgePackageAsync(string name, string packageId, NuGetVersion? version, CancellationToken cancellationToken, string? actor = null); + + /// + /// Deletes one stored artifact of a Maven repository (group:artifact; every version when is + /// null) and drops the answers remembered about it. Like for a format whose versions are not NuGet + /// versions. Audited. + /// + /// No such remote repository. + /// The repository is not a Maven one, or the artifact or version is not valid. + Task PurgeArtifactAsync(string name, string artifact, string? version, CancellationToken cancellationToken, string? actor = null); + + /// + /// Deletes what a Docker repository cached of one image: the image with everything in it, or with only + /// that tag or digest (and the manifest it points at), and drops the answers remembered about it. Like + /// for a format whose versions are tags. Audited. + /// + /// No such remote repository. + /// The repository is not a Docker one, or the image or reference is not valid. + Task PurgeImageAsync(string name, string image, string? reference, CancellationToken cancellationToken, string? actor = null); + + /// + /// When Mirror:Enabled: creates the remote repository from Mirror:* if + /// it is missing, else brings its URL, protocol and timeout in line with the options. Idempotent; called at startup. + /// A non-remote repository with that name is left alone (the default repository then reads Mirror:* directly). + /// + Task EnsureMirrorRepositoryAsync(CancellationToken cancellationToken); +} + +/// +/// over the relational database. +/// +public class RemoteRepositoryAdministration : IRemoteRepositoryAdministration +{ + private readonly IContext _context; + private readonly IRepositoryService _repositories; + private readonly RemoteSettingsCodec _codec; + private readonly RemoteRepositoryState _state; + private readonly IRemoteHttpClientFactory _http; + private readonly IServiceScopeFactory _scopes; + private readonly IOptions _mirror; + private readonly ILogger _logger; + private readonly MaintenanceGate? _gate; + private readonly SystemTime? _time; + private readonly IOptionsSnapshot? _remoteOptions; + + public RemoteRepositoryAdministration( + IContext context, + IRepositoryService repositories, + RemoteSettingsCodec codec, + RemoteRepositoryState state, + IRemoteHttpClientFactory http, + IServiceScopeFactory scopes, + IOptions mirror, + ILogger logger, + MaintenanceGate? gate = null, + SystemTime? time = null, + IOptionsSnapshot? remoteOptions = null) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _codec = codec ?? throw new ArgumentNullException(nameof(codec)); + _state = state ?? throw new ArgumentNullException(nameof(state)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _mirror = mirror ?? throw new ArgumentNullException(nameof(mirror)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _gate = gate; + _time = time; + _remoteOptions = remoteOptions; + } + + private bool BlockPrivate => _remoteOptions?.Value?.BlockPrivateAddresses == true; + + private DateTime Now => _time?.UtcNow ?? DateTime.UtcNow; + + private bool Relational => !(_context is NullContext); + + private bool MirrorActive => _mirror.Value.Enabled && _mirror.Value.PackageSource != null; + + /// + public async Task FindAsync(string? name, CancellationToken cancellationToken) + { + var row = await FindRowOrNullAsync(name, cancellationToken).ConfigureAwait(false); + if (row == null) return null; + + var settings = _codec.Deserialize(row.Settings) ?? new RemoteRepositorySettings(); + var hasPassword = !string.IsNullOrEmpty(settings.ProtectedPassword); + settings.Password = null; + settings.ProtectedPassword = null; + + return new RemoteRepositoryDetail(row.ToInfo(), settings, hasPassword, IsMirror: row.Name == Repository.MirrorName && row.Format == RepositoryFormat.NuGet && MirrorActive); + } + + /// + public async Task UpdateAsync(string name, RemoteRepositorySettings input, bool clearPassword, CancellationToken cancellationToken, string? actor = null) + { + if (input == null) throw new ArgumentNullException(nameof(input)); + _gate?.ThrowIfClosed(); + + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + var stored = _codec.Deserialize(row.Settings) ?? new RemoteRepositorySettings(); + + var settings = input.ForFormat(row.Format); + var passwordChanged = false; + if (clearPassword) + { + settings.Password = null; + settings.ProtectedPassword = null; + passwordChanged = !string.IsNullOrEmpty(stored.ProtectedPassword); + } + else if (string.IsNullOrEmpty(settings.Password)) + { + settings.Password = null; + settings.ProtectedPassword = stored.ProtectedPassword; + } + else + { + passwordChanged = true; + } + + // While Mirror:* drives the default repository, where the upstream is stays in the options. + if (row.Name == Repository.MirrorName && row.Format == RepositoryFormat.NuGet && MirrorActive) + { + settings.Url = stored.Url; + settings.Protocol = stored.Protocol; + settings.DownloadTimeoutSeconds = stored.DownloadTimeoutSeconds; + } + + // A stored password belongs to the origin and user name it was stored for: pointing the repository elsewhere + // without typing a new one must not send it to the new server (see TestConnectionAsync). + if (string.IsNullOrEmpty(settings.Password) + && !string.IsNullOrEmpty(settings.ProtectedPassword) + && !SameCredentialScope(stored, settings)) + { + settings.ProtectedPassword = null; + passwordChanged = true; + } + + Validate(settings, BlockPrivate); + + row.Settings = _codec.Serialize(settings); + AccessAdministration.Audit(_context, Now, actor, "repository.remote.update", name, new + { + url = settings.UrlOrNull?.GetLeftPart(UriPartial.Path), + protocol = settings.Protocol.ToString(), + username = settings.Username, + passwordChanged, + settings.MetadataTtlSeconds, + settings.NegativeTtlSeconds, + settings.Offline, + settings.StoreLocally, + }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + _state.InvalidateSettings(row.Key); + _state.Clear(row.Key); + } + + /// + public async Task TestConnectionAsync(string? name, RemoteRepositorySettings input, CancellationToken cancellationToken) + { + if (input == null) throw new ArgumentNullException(nameof(input)); + + var settings = input.Clone(); + var storedPasswordWithheld = false; + if (!string.IsNullOrEmpty(name)) + { + // The repository's format decides the protocol (an npm repository speaks the npm registry protocol only). + var format = (await FindRowOrNullAsync(name, cancellationToken).ConfigureAwait(false))?.Format; + if (format != null) settings = settings.ForFormat(format.Value); + } + + if (string.IsNullOrEmpty(settings.Password) && !string.IsNullOrEmpty(name)) + { + // The stored password goes only to the upstream it was stored for (the rule saving applies): testing another + // origin or user name with it would hand it to whoever runs that server. + var row = await FindRowOrNullAsync(name, cancellationToken).ConfigureAwait(false); + var stored = _codec.Deserialize(row?.Settings); + if (stored != null && !string.IsNullOrEmpty(stored.Password)) + { + if (SameCredentialScope(stored, settings)) + { + settings.Password = stored.Password; + } + else + { + storedPasswordWithheld = true; + } + } + } + + var problems = settings.Validate(BlockPrivate); + if (problems.Count > 0) return new RemoteConnectionResult(false, string.Join(" ", problems), null, 0); + + var watch = Stopwatch.StartNew(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + + try + { + if (BlockPrivate) + { + var refused = await RemoteAddressPolicy.CheckResolvedAsync(settings.UrlOrNull, timeout.Token).ConfigureAwait(false); + if (refused != null) return new RemoteConnectionResult(false, refused, null, watch.ElapsedMilliseconds); + } + + if (settings.Protocol == RemoteProtocol.Docker) + { + return await TestRegistryAsync(name, settings, storedPasswordWithheld, watch, timeout.Token).ConfigureAwait(false); + } + + using var client = _http.CreateProbe(settings); + + // An npm registry is asked for its ping (BaGet, Verdaccio, Artifactory and npmjs answer it), then for its root. + // A Maven repository is asked for its root (Maven Central, Artifactory and Nexus list it). + var targets = settings.Protocol == RemoteProtocol.Npm + ? new[] { new Uri(NpmBase(settings) + "-/ping"), new Uri(NpmBase(settings)) } + : settings.Protocol == RemoteProtocol.Maven + ? new[] { new Uri(NpmBase(settings)) } + : new[] { settings.UrlOrNull! }; + + HttpResponseMessage? response = null; + foreach (var start in targets) + { + response?.Dispose(); + + // Redirects are followed by hand and only within the origin that was typed: following one to another host + // would let a probe be steered at addresses nobody named. + var target = start; + var hops = 0; + while (true) + { + response = await client.GetAsync(target, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false); + if (!IsRedirect(response.StatusCode) || response.Headers.Location == null) break; + + var next = new Uri(target, response.Headers.Location); + var elapsed = watch.ElapsedMilliseconds; + var redirectStatus = (int)response.StatusCode; + response.Dispose(); + if (!SameOrigin(target, next) || ++hops > MaxProbeRedirects) + { + return new RemoteConnectionResult( + false, + $"The upstream answered HTTP {redirectStatus} and redirects to another host (or too many times); Test connection does not follow that. Use the final URL.", + redirectStatus, + elapsed); + } + + target = next; + } + + // Only a missing ping sends the npm probe on to the root. + if (response.StatusCode != HttpStatusCode.NotFound) break; + } + + using (response) + { + var status = (int)response!.StatusCode; + + if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) + { + return new RemoteConnectionResult( + false, + $"The upstream refused the credentials (HTTP {status})." + + (storedPasswordWithheld ? " The stored password is only sent while the URL's origin and the user name are unchanged; type the password to test them." : string.Empty), + status, + watch.ElapsedMilliseconds); + } + + if (response.StatusCode == HttpStatusCode.NotFound && settings.Protocol == RemoteProtocol.Maven) + { + // A Maven client never asks for the root: a repository may list nothing there. The host answered and accepted the + // credentials; whether the path is the repository's is only seen when an artifact is requested. + return new RemoteConnectionResult( + true, + "Connected: the server answered, but HTTP 404 for the repository root (many Maven repositories list nothing there). Check the URL by requesting an artifact.", + status, + watch.ElapsedMilliseconds); + } + + if (!response.IsSuccessStatusCode) + { + return new RemoteConnectionResult(false, $"The upstream answered HTTP {status} {response.StatusCode}.", status, watch.ElapsedMilliseconds); + } + + if (settings.Protocol == RemoteProtocol.V3) + { + var body = await ReadCappedAsync(response.Content, MaxProbeBodyBytes, timeout.Token).ConfigureAwait(false); + if (body == null) + { + return new RemoteConnectionResult(false, "The upstream answered, but with far more data than a V3 service index (over 1 MB). Is the protocol right?", status, watch.ElapsedMilliseconds); + } + + try + { + using var document = JsonDocument.Parse(body); + if (document.RootElement.ValueKind == JsonValueKind.Object + && document.RootElement.TryGetProperty("resources", out var resources) + && resources.ValueKind == JsonValueKind.Array) + { + return new RemoteConnectionResult(true, $"Connected: V3 service index with {resources.GetArrayLength()} resources.", status, watch.ElapsedMilliseconds); + } + } + catch (JsonException) + { + } + + return new RemoteConnectionResult(false, "The upstream answered, but not with a V3 service index (index.json with a resources list). Is the protocol right?", status, watch.ElapsedMilliseconds); + } + + if (settings.Protocol == RemoteProtocol.Npm) return new RemoteConnectionResult(true, "Connected: the npm registry answered.", status, watch.ElapsedMilliseconds); + if (settings.Protocol == RemoteProtocol.Maven) return new RemoteConnectionResult(true, "Connected: the Maven repository answered.", status, watch.ElapsedMilliseconds); + + return new RemoteConnectionResult(true, "Connected: the V2 feed answered.", status, watch.ElapsedMilliseconds); + } + } + catch (Exception e) when (!cancellationToken.IsCancellationRequested) + { + if (IsPrivateAddressRefusal(e)) return new RemoteConnectionResult(false, RemoteAddressPolicy.Message, null, watch.ElapsedMilliseconds); + + // A refusal the registry client raised itself (a token service that wants other credentials) already says what it is. + if (e is System.IO.InvalidDataException) return new RemoteConnectionResult(false, e.Message, null, watch.ElapsedMilliseconds); + + return new RemoteConnectionResult(false, "Could not reach the upstream: " + RemoteUpstreamClient.Describe(e), null, watch.ElapsedMilliseconds); + } + } + + // A registry is asked its version check (GET /v2/) the way a Docker client does: anonymously first, then through the token service the + // challenge names with the credentials typed, so a wrong password shows here and not on the first pull. Nothing is saved or cached: + // the client has a state of its own. + private async Task TestRegistryAsync(string? name, RemoteRepositorySettings settings, bool storedPasswordWithheld, Stopwatch watch, CancellationToken cancellationToken) + { + var probe = new OciUpstreamClient( + repository: null, + new NoUpstreamSource(), + new RemoteRepositoryState(), + _http, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + + var status = (int)await probe.PingAsync(new ResolvedUpstream(0, name ?? "test", settings), cancellationToken).ConfigureAwait(false); + if (status is 401 or 403) + { + return new RemoteConnectionResult( + false, + (settings.HasCredentials ? $"The registry refused the credentials (HTTP {status})." : $"The registry wants credentials (HTTP {status}); fill in the user name and password or token.") + + (storedPasswordWithheld ? " The stored password is only sent while the URL's origin and the user name are unchanged; type the password to test them." : string.Empty), + status, + watch.ElapsedMilliseconds); + } + + if (status == 404) + { + return new RemoteConnectionResult(false, "The upstream answered HTTP 404 for /v2/: it is not a Docker registry at this address (a registry is at the root, e.g. https://registry-1.docker.io).", status, watch.ElapsedMilliseconds); + } + + if (status is < 200 or >= 300) return new RemoteConnectionResult(false, $"The upstream answered HTTP {status}.", status, watch.ElapsedMilliseconds); + + return new RemoteConnectionResult( + true, + "Connected: the registry answered the version check" + (settings.HasCredentials ? " with the credentials." : " (anonymously)."), + status, + watch.ElapsedMilliseconds); + } + + private sealed class NoUpstreamSource : IRemoteUpstreamSource + { + public Task ResolveAsync(RepositoryInfo repository, CancellationToken cancellationToken) => Task.FromResult(null); + } + + // The upstream URL with a trailing slash (an npm registry's or a Maven repository's root). + private static string NpmBase(RemoteRepositorySettings settings) + { + var text = settings.UrlOrNull!.GetLeftPart(UriPartial.Path); + + return text.EndsWith('/') ? text : text + "/"; + } + + // The most of an answer Test connection reads: a service index is a few KB; anything bigger is not one. + private const int MaxProbeBodyBytes = 1024 * 1024; + private const int MaxProbeRedirects = 5; + + private static bool IsRedirect(HttpStatusCode status) + => status is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; + + private static bool IsPrivateAddressRefusal(Exception e) + { + for (var current = e; current != null; current = current.InnerException) + { + if (current is PrivateAddressException) return true; + } + + return false; + } + + // At most 'limit' bytes of the body as text, or null when there is more. + private static async Task ReadCappedAsync(HttpContent content, int limit, CancellationToken cancellationToken) + { + if (content.Headers.ContentLength > limit) return null; + + using var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + using var buffer = new System.IO.MemoryStream(); + var chunk = new byte[16 * 1024]; + int read; + while ((read = await stream.ReadAsync(chunk, cancellationToken).ConfigureAwait(false)) > 0) + { + if (buffer.Length + read > limit) return null; + + buffer.Write(chunk, 0, read); + } + + return System.Text.Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length); + } + + /// + public async Task GetCacheAsync(string name, CancellationToken cancellationToken) + { + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + if (row.Format == RepositoryFormat.Npm) + { + var npmPackages = _context.NpmPackages!.IgnoreQueryFilters().AsNoTracking().Where(p => p.RepositoryKey == row.Key); + var versions = await _context.NpmVersions!.AsNoTracking() + .Join(npmPackages, v => v.PackageKey, p => p.Key, (v, p) => v.Key) + .CountAsync(cancellationToken).ConfigureAwait(false); + + return new RemoteCacheOverview(_state.Status(row.Key), versions, await npmPackages.CountAsync(cancellationToken).ConfigureAwait(false)); + } + + if (row.Format == RepositoryFormat.Docker) + { + using var scope = _scopes.CreateRepositoryScope(row.ToInfo()); + var (manifests, images, bytes) = await scope.ServiceProvider.GetRequiredService().GetUsageAsync(cancellationToken).ConfigureAwait(false); + + return new RemoteCacheOverview(_state.Status(row.Key), manifests, images, bytes); + } + + if (row.Format == RepositoryFormat.Maven) + { + var artifacts = _context.MavenArtifacts!.IgnoreQueryFilters().AsNoTracking().Where(a => a.RepositoryKey == row.Key); + var mavenVersions = await _context.MavenVersions!.AsNoTracking() + .Join(artifacts, v => v.ArtifactKey, a => a.Key, (v, a) => v.Key) + .CountAsync(cancellationToken).ConfigureAwait(false); + + return new RemoteCacheOverview(_state.Status(row.Key), mavenVersions, await artifacts.CountAsync(cancellationToken).ConfigureAwait(false)); + } + + var packages = _context.Packages!.IgnoreQueryFilters().AsNoTracking().Where(p => p.RepositoryKey == row.Key); + var count = await packages.CountAsync(cancellationToken).ConfigureAwait(false); + var ids = await packages.Select(p => p.Id).Distinct().CountAsync(cancellationToken).ConfigureAwait(false); + + return new RemoteCacheOverview(_state.Status(row.Key), count, ids); + } + + /// + public async Task PurgeAsync(string name, CancellationToken cancellationToken, string? actor = null) + { + _gate?.ThrowIfClosed(); + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + + var deleted = await DeletePackagesAsync(row, packageId: null, version: null, cancellationToken).ConfigureAwait(false); + var answers = _state.Clear(row.Key); + + await AuditAsync(actor, "repository.remote.purge", name, new { packages = deleted, answers }, cancellationToken).ConfigureAwait(false); + + return new PurgeResult(deleted, answers); + } + + /// + public async Task PurgePackageAsync(string name, string packageId, NuGetVersion? version, CancellationToken cancellationToken, string? actor = null) + { + if (string.IsNullOrWhiteSpace(packageId)) throw new ArgumentException("A package id is required.", nameof(packageId)); + _gate?.ThrowIfClosed(); + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + + // A Maven artifact is group:artifact; its versions are free text, so PurgeArtifactAsync takes them as such. + if (row.Format == RepositoryFormat.Maven) return await PurgeArtifactAsync(name, packageId, version?.ToFullString(), cancellationToken, actor).ConfigureAwait(false); + if (row.Format == RepositoryFormat.Docker) return await PurgeImageAsync(name, packageId, version?.ToFullString(), cancellationToken, actor).ConfigureAwait(false); + + var id = packageId.Trim(); + if (row.Format == RepositoryFormat.Npm) + { + if (!NpmNames.TryParseLookup(id, out id, out var invalid)) throw new ArgumentException(invalid, nameof(packageId)); + } + + var deleted = await DeletePackagesAsync(row, id, version, cancellationToken).ConfigureAwait(false); + var answers = _state.ClearPackage(row.Key, row.Format == RepositoryFormat.Npm ? NpmUpstreamClient.KeyName(id) : id); + + await AuditAsync( + actor, + "repository.remote.purge-package", + name, + new { packageId = id, version = version?.ToNormalizedString(), packages = deleted, answers }, + cancellationToken).ConfigureAwait(false); + + return new PurgeResult(deleted, answers); + } + + /// + public async Task PurgeArtifactAsync(string name, string artifact, string? version, CancellationToken cancellationToken, string? actor = null) + { + if (string.IsNullOrWhiteSpace(artifact)) throw new ArgumentException("An artifact (group:artifact) is required.", nameof(artifact)); + _gate?.ThrowIfClosed(); + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + if (row.Format != RepositoryFormat.Maven) throw new ArgumentException("Only a Maven repository has artifacts with group:artifact coordinates.", nameof(name)); + + var coordinate = artifact.Trim(); + if (!MavenNames.TryParseArtifactName(coordinate, out var group, out var artifactId)) throw new ArgumentException($"{coordinate} is not an artifact: write it as group:artifact.", nameof(artifact)); + + var wanted = string.IsNullOrWhiteSpace(version) ? null : version.Trim(); + if (wanted != null && !MavenNames.IsValidVersion(wanted)) throw new ArgumentException($"{wanted} is not a valid version.", nameof(version)); + + int deleted; + using (var scope = _scopes.CreateRepositoryScope(row.ToInfo())) + { + deleted = await scope.ServiceProvider.GetRequiredService().PurgeAsync(coordinate, wanted, cancellationToken).ConfigureAwait(false); + } + + // The answers about the artifact: its files, checksums and metadata; for one version, that version's and the version list. + var folder = MavenNames.GroupPath(group) + "/" + artifactId; + var list = "mm:" + folder + "/" + MavenNames.MetadataFileName; + var answers = _state.ClearMatching(row.Key, key => wanted == null + ? MavenUpstreamClient.PathPrefix(key, folder) + : key == list || MavenUpstreamClient.PathPrefix(key, folder + "/" + wanted)); + + await AuditAsync( + actor, + "repository.remote.purge-package", + name, + new { packageId = coordinate, version = wanted, packages = deleted, answers }, + cancellationToken).ConfigureAwait(false); + + return new PurgeResult(deleted, answers); + } + + /// + public async Task PurgeImageAsync(string name, string image, string? reference, CancellationToken cancellationToken, string? actor = null) + { + if (string.IsNullOrWhiteSpace(image)) throw new ArgumentException("An image name is required.", nameof(image)); + _gate?.ThrowIfClosed(); + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + if (row.Format != RepositoryFormat.Docker) throw new ArgumentException("Only a Docker repository has images.", nameof(name)); + + var wanted = image.Trim().ToLowerInvariant(); + if (!OciNames.IsValidImage(wanted)) throw new ArgumentException($"{image.Trim()} is not an image name: lower-case letters, digits, '.', '_', '-' in components separated by '/'.", nameof(image)); + + var tagOrDigest = string.IsNullOrWhiteSpace(reference) ? null : reference.Trim(); + if (tagOrDigest != null && !(OciNames.IsValidTag(tagOrDigest) || OciNames.IsValidDigest(tagOrDigest))) throw new ArgumentException($"{tagOrDigest} is not a tag or a sha256 digest.", nameof(reference)); + + int deleted; + using (var scope = _scopes.CreateRepositoryScope(row.ToInfo())) + { + deleted = await scope.ServiceProvider.GetRequiredService().PurgeAsync(wanted, tagOrDigest, cancellationToken).ConfigureAwait(false); + } + + // The answers about the image: its manifests, tag lists and blob sizes (for one tag, that tag's and the lists). + var answers = _state.ClearMatching(row.Key, key => OciUpstreamClient.MatchesImage(key, wanted, tagOrDigest)); + + await AuditAsync( + actor, + "repository.remote.purge-package", + name, + new { packageId = wanted, version = tagOrDigest, packages = deleted, answers }, + cancellationToken).ConfigureAwait(false); + + return new PurgeResult(deleted, answers); + } + + /// + public async Task EnsureMirrorRepositoryAsync(CancellationToken cancellationToken) + { + if (!MirrorActive || !_repositories.SupportsMultipleRepositories) return; + + var existing = await _context.Repositories! + .FirstOrDefaultAsync(r => r.Name == Repository.MirrorName, cancellationToken) + .ConfigureAwait(false); + + var fromOptions = RemoteRepositorySettings.FromMirror(_mirror.Value); + if (existing == null) + { + try + { + await _repositories.CreateAsync( + Repository.MirrorName, RepositoryFormat.NuGet, RepositoryKind.Remote, fromOptions, cancellationToken).ConfigureAwait(false); + } + catch (ArgumentException e) when (BlockPrivate) + { + // Mirror:PackageSource is operator configuration; a private one that Remote:BlockPrivateAddresses refuses + // must not stop the host from starting (the default repository's fetches are refused at connection time). + _logger.LogWarning("The remote repository {Repository} was not created from the Mirror settings: {Reason}", Repository.MirrorName, e.Message); + + return; + } + + _state.InvalidateSettings(RemoteRepositoryState.MirrorLookupKey); + _logger.LogInformation( + "Created the remote repository {Repository} from the Mirror settings; the default repository fetches through it.", + Repository.MirrorName); + + return; + } + + if (existing.Kind != RepositoryKind.Remote || existing.Format != RepositoryFormat.NuGet) + { + _logger.LogWarning( + "A repository named {Repository} exists and is not a remote NuGet one; the default repository reads the Mirror settings directly. Rename or delete it to manage the mirror as a repository.", + Repository.MirrorName); + + return; + } + + var settings = _codec.Deserialize(existing.Settings); + if (settings == null) + { + existing.Settings = _codec.Serialize(fromOptions); + } + else if (settings.Url == fromOptions.Url + && settings.Protocol == fromOptions.Protocol + && settings.DownloadTimeoutSeconds == fromOptions.DownloadTimeoutSeconds) + { + return; + } + else + { + // Mirror:* carries no user name (the repository's own is kept), so only the origin can have moved. + var moved = !SameOrigin(settings, fromOptions); + settings.Url = fromOptions.Url; + settings.Protocol = fromOptions.Protocol; + settings.DownloadTimeoutSeconds = fromOptions.DownloadTimeoutSeconds; + if (moved) + { + // The stored password was for another origin: never hand it to the new one. + settings.Password = null; + settings.ProtectedPassword = null; + } + + existing.Settings = _codec.Serialize(settings); + } + + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + _state.InvalidateSettings(existing.Key); + } + + // True while the origin (scheme, host, port) is the one a stored password was saved for. + private static bool SameOrigin(RemoteRepositorySettings before, RemoteRepositorySettings after) + { + var a = before.UrlOrNull; + var b = after.UrlOrNull; + if (a == null || b == null) return a == b; + + return string.Equals(a.GetLeftPart(UriPartial.Authority), b.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); + } + + private static bool SameOrigin(Uri a, Uri b) + => string.Equals(a.GetLeftPart(UriPartial.Authority), b.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); + + // True while the origin and the user name are the ones a stored password was saved for. + private static bool SameCredentialScope(RemoteRepositorySettings before, RemoteRepositorySettings after) + { + return SameOrigin(before, after) + && string.Equals(before.Username ?? string.Empty, after.Username ?? string.Empty, StringComparison.Ordinal); + } + + private async Task DeletePackagesAsync(Repository row, string? packageId, NuGetVersion? version, CancellationToken cancellationToken) + { + var info = row.ToInfo(); + var deleted = 0; + + if (row.Format == RepositoryFormat.Npm) + { + // The registry service works in the repository of its scope and deletes rows and files together. + using var npmScope = _scopes.CreateRepositoryScope(info); + + return await npmScope.ServiceProvider.GetRequiredService() + .PurgeAsync(packageId, version?.ToFullString(), cancellationToken).ConfigureAwait(false); + } + + if (row.Format == RepositoryFormat.Docker) + { + using var dockerScope = _scopes.CreateRepositoryScope(info); + + return await dockerScope.ServiceProvider.GetRequiredService() + .PurgeAsync(packageId, version?.ToFullString(), cancellationToken).ConfigureAwait(false); + } + + if (row.Format == RepositoryFormat.Maven) + { + using var mavenScope = _scopes.CreateRepositoryScope(info); + + return await mavenScope.ServiceProvider.GetRequiredService() + .PurgeAsync(packageId, version?.ToFullString(), cancellationToken).ConfigureAwait(false); + } + + while (true) + { + var query = _context.Packages!.IgnoreQueryFilters().AsNoTracking().Where(p => p.RepositoryKey == row.Key); + if (packageId != null) query = query.Where(p => p.Id == packageId); + if (version != null) + { + var normalized = version.ToNormalizedString().ToLowerInvariant(); + query = query.Where(p => p.NormalizedVersionString == normalized); + } + + var batch = await query + .OrderBy(p => p.Key) + .Select(p => new { p.Id, p.NormalizedVersionString }) + .Take(200) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + if (batch.Count == 0) return deleted; + + // The deletion services work in the repository of their scope. + using var scope = _scopes.CreateRepositoryScope(info); + var deletion = scope.ServiceProvider.GetRequiredService(); + var progressed = 0; + foreach (var package in batch) + { + if (await deletion.TryHardDeletePackageAsync(package.Id, NuGetVersion.Parse(package.NormalizedVersionString!), cancellationToken).ConfigureAwait(false)) + { + deleted++; + progressed++; + } + } + + // A row that cannot be deleted must not loop forever. + if (progressed == 0) return deleted; + } + } + + private async Task AuditAsync(string? actor, string action, string name, object details, CancellationToken cancellationToken) + { + AccessAdministration.Audit(_context, Now, actor, action, name, details); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + private static void Validate(RemoteRepositorySettings settings, bool blockPrivateAddresses) + { + var problems = settings.Validate(blockPrivateAddresses); + if (problems.Count > 0) throw new ArgumentException(string.Join(" ", problems)); + } + + private async Task FindRowOrNullAsync(string? name, CancellationToken cancellationToken) + { + if (!Relational || string.IsNullOrEmpty(name)) return null; + + return await _context.Repositories! + .FirstOrDefaultAsync(r => r.Name == name && r.Kind == RepositoryKind.Remote, cancellationToken) + .ConfigureAwait(false); + } + + private async Task FindRowAsync(string? name, CancellationToken cancellationToken) + => await FindRowOrNullAsync(name, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"There is no remote repository named '{name}'."); +} diff --git a/src/BaGet.Core/Repositories/Remote/RemoteRepositorySettings.cs b/src/BaGet.Core/Repositories/Remote/RemoteRepositorySettings.cs new file mode 100644 index 000000000..a25715657 --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/RemoteRepositorySettings.cs @@ -0,0 +1,347 @@ +using System; +using Microsoft.AspNetCore.DataProtection; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace BaGet.Core; + +/// +/// The protocol a remote repository's upstream speaks. +/// +public enum RemoteProtocol +{ + /// NuGet V3 (index.json service index). + V3 = 0, + + /// NuGet V2 (OData/Atom feed). + V2 = 1, + + /// + /// The npm registry protocol (packuments at {url}/{name}, tarballs under {url}/{name}/-/): the only protocol of + /// an npm repository, set from its format (the create and edit forms do not offer a choice). + /// + Npm = 2, + + /// + /// The Maven 2 repository layout (files at {url}/{group/as/folders}/{artifact}/{version}/{file}, maven-metadata.xml + /// beside them): the only protocol of a Maven repository, set from its format (Maven Central is + /// https://repo.maven.apache.org/maven2/). + /// + Maven = 3, + + /// + /// The OCI Distribution Spec / Docker Registry HTTP API v2 ({url}/v2/{name}/manifests/{reference}, blobs, tags) with its + /// token authentication (WWW-Authenticate: Bearer realm=…, as Docker Hub does) or HTTP Basic: the only protocol of a + /// Docker repository, set from its format (Docker Hub is https://registry-1.docker.io). + /// + Docker = 4, +} + +/// +/// What a repository knows about its upstream: kept as JSON in +/// . The password never appears in clear there: it is stored as +/// (see ) and only +/// exists in memory. +/// +public sealed class RemoteRepositorySettings +{ + /// Longest accepted . + public const int MaxUrlLength = 2048; + + /// The largest cache period accepted: one year. + public const int MaxTtlSeconds = 365 * 24 * 3600; + + /// The upstream: a V3 index.json URL or a V2 feed URL, the base URL of an npm registry, the root of a Maven repository or the address of a Docker registry (absolute http or https). + public string? Url { get; set; } + + /// The protocol of . + [JsonConverter(typeof(JsonStringEnumConverter))] + public RemoteProtocol Protocol { get; set; } = RemoteProtocol.V3; + + /// + /// The user name sent with HTTP Basic to the upstream's own host, if any. An npm upstream with a password and no user name + /// gets the password as a bearer token (npm's _authToken) instead. A Docker upstream gets the pair at its token service + /// (HTTP Basic, the docker login flow) or, when it asks for Basic itself, at its own host; a password with no user name + /// is sent as a ready-made bearer token to the registry's own host. + /// + public string? Username { get; set; } + + /// + /// The clear password (or token). In memory only: it is not serialized; is. + /// + [JsonIgnore] + public string? Password { get; set; } + + /// The password as stored (protected). Opaque to everything but . + public string? ProtectedPassword { get; set; } + + /// + /// How long the upstream's version list and metadata of a package are reused before it is asked again. 0 asks + /// every time (what the mirror always did). + /// + public int MetadataTtlSeconds { get; set; } = 600; + + /// How long "the upstream does not have it" (404) is remembered. 0 asks every time. + public int NegativeTtlSeconds { get; set; } = 60; + + /// + /// Offline mode: the upstream is never contacted; only what is already stored (and cached in memory) is served. + /// + public bool Offline { get; set; } + + /// + /// Whether packages fetched from the upstream are stored (database and files) so later requests, and requests + /// while the upstream is down, are served locally. Off, the repository is a pass-through: metadata comes from the + /// upstream (cached by ), downloads stream through and nothing is kept (so search + /// and the package pages stay empty). + /// + public bool StoreLocally { get; set; } = true; + + /// The time before a download from the upstream times out. + public int DownloadTimeoutSeconds { get; set; } = 600; + + /// Whether a user name or password is configured. + [JsonIgnore] + public bool HasCredentials => !string.IsNullOrEmpty(Username) || !string.IsNullOrEmpty(Password); + + /// The upstream URL as a , or null when it is missing or invalid. + [JsonIgnore] + public Uri? UrlOrNull => Uri.TryCreate(Url, UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) ? uri : null; + + /// A copy that can be changed without affecting this one. + public RemoteRepositorySettings Clone() => (RemoteRepositorySettings)MemberwiseClone(); + + /// + /// A copy whose fits : an npm repository speaks + /// only, a Maven one only and a Docker one only (the forms + /// do not ask), a NuGet one V3 or V2 (a stray npm, Maven or Docker protocol becomes V3, which then fails the connection test + /// rather than silently speaking another protocol to a NuGet feed). + /// + public RemoteRepositorySettings ForFormat(RepositoryFormat format) + { + var copy = Clone(); + if (format == RepositoryFormat.Npm) + { + copy.Protocol = RemoteProtocol.Npm; + } + else if (format == RepositoryFormat.Maven) + { + copy.Protocol = RemoteProtocol.Maven; + } + else if (format == RepositoryFormat.Docker) + { + copy.Protocol = RemoteProtocol.Docker; + } + else if (copy.Protocol is RemoteProtocol.Npm or RemoteProtocol.Maven or RemoteProtocol.Docker) + { + copy.Protocol = RemoteProtocol.V3; + } + + return copy; + } + + /// The settings the Mirror:* options describe (no cache periods: the mirror always asked). + public static RemoteRepositorySettings FromMirror(MirrorOptions options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); + + return new RemoteRepositorySettings + { + Url = options.PackageSource?.AbsoluteUri, + Protocol = options.Legacy ? RemoteProtocol.V2 : RemoteProtocol.V3, + MetadataTtlSeconds = 0, + NegativeTtlSeconds = 0, + Offline = false, + StoreLocally = true, + DownloadTimeoutSeconds = options.PackageDownloadTimeoutSeconds, + }; + } + + /// The problems with these settings, empty when they are usable. + /// Also refuse localhost and a literal loopback, private or link-local address (). + public IReadOnlyList Validate(bool blockPrivateAddresses = false) + { + var problems = new List(); + + if (string.IsNullOrWhiteSpace(Url)) + { + problems.Add("The upstream URL is required."); + } + else if (Url!.Length > MaxUrlLength || UrlOrNull == null) + { + problems.Add("The upstream URL must be an absolute http or https URL."); + } + else if (UrlOrNull!.UserInfo.Length > 0) + { + problems.Add("Put the credentials in the user name and password fields, not in the URL."); + } + else if (!string.IsNullOrEmpty(UrlOrNull.Query) && Protocol == RemoteProtocol.V2) + { + problems.Add("The V2 feed URL must not have a query string."); + } + else if (!string.IsNullOrEmpty(UrlOrNull.Query) && Protocol == RemoteProtocol.Npm) + { + problems.Add("The npm registry URL must not have a query string."); + } + else if (!string.IsNullOrEmpty(UrlOrNull.Query) && Protocol == RemoteProtocol.Maven) + { + problems.Add("The Maven repository URL must not have a query string."); + } + else if (!string.IsNullOrEmpty(UrlOrNull.Query) && Protocol == RemoteProtocol.Docker) + { + problems.Add("The registry URL must not have a query string."); + } + + if (blockPrivateAddresses) + { + var refused = RemoteAddressPolicy.CheckLiteral(UrlOrNull); + if (refused != null) problems.Add(refused); + } + + if (!Enum.IsDefined(typeof(RemoteProtocol), Protocol)) problems.Add("Unknown protocol."); + if (MetadataTtlSeconds < 0 || MetadataTtlSeconds > MaxTtlSeconds) problems.Add($"The metadata cache period must be between 0 and {MaxTtlSeconds} seconds."); + if (NegativeTtlSeconds < 0 || NegativeTtlSeconds > MaxTtlSeconds) problems.Add($"The negative cache period must be between 0 and {MaxTtlSeconds} seconds."); + if (DownloadTimeoutSeconds < 1 || DownloadTimeoutSeconds > 24 * 3600) problems.Add("The download timeout must be between 1 second and 24 hours."); + if (Username != null && Username.Length > 256) problems.Add("The user name is too long."); + if (Password != null && Password.Length > 4096) problems.Add("The password is too long."); + if (!string.IsNullOrEmpty(Username) && Username!.Contains(':')) problems.Add("The user name cannot contain ':' (HTTP Basic)."); + + return problems; + } + + /// + /// A key that changes when something that affects how the upstream is contacted changes, so a pooled client is + /// rebuilt exactly then. Contains no secret (the password is hashed in). + /// + internal string TransportKey() + { + var password = Password ?? string.Empty; + var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(password)); + + return string.Join("|", Url, Protocol, Username, Convert.ToHexString(hash, 0, 8), DownloadTimeoutSeconds); + } +} + +/// +/// Turns into the JSON kept in and back, +/// protecting the password on the way out. +/// +public sealed class RemoteSettingsCodec +{ + private static readonly JsonSerializerOptions Json = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + private readonly IRemoteCredentialProtector? _protector; + + /// Protects passwords. Null refuses to store one. + public RemoteSettingsCodec(IRemoteCredentialProtector? protector = null) + { + _protector = protector; + } + + /// + /// The JSON to store. A is protected into + /// ; with none set, the already protected value is kept. + /// + /// There is a password and nothing to protect it with. + public string Serialize(RemoteRepositorySettings settings) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + var copy = settings.Clone(); + if (!string.IsNullOrEmpty(copy.Password)) + { + copy.ProtectedPassword = (_protector ?? throw new InvalidOperationException( + "Credentials cannot be stored: no data protection is configured on this host.")) + .Protect(copy.Password!); + } + + return JsonSerializer.Serialize(copy, Json); + } + + /// + /// Protects a secret that is not a repository password (a replication peer's API key) with the same protector. + /// + /// No data protection is configured on this host. + public string ProtectSecret(string secret) + => (_protector ?? throw new InvalidOperationException("Credentials cannot be stored: no data protection is configured on this host.")) + .Protect(secret ?? throw new ArgumentNullException(nameof(secret))); + + /// The secret stored, or null when it cannot be unprotected (keys lost) or there is no protector. + public string? TryUnprotectSecret(string? protectedValue) + => string.IsNullOrEmpty(protectedValue) || _protector == null ? null : _protector.TryUnprotect(protectedValue); + + /// + /// Reads stored JSON. The password is unprotected; one that cannot be (keys lost) reads as absent rather than + /// failing the repository. + /// + /// The settings, or null when is empty or not valid. + public RemoteRepositorySettings? Deserialize(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + + RemoteRepositorySettings? settings; + try + { + settings = JsonSerializer.Deserialize(json, Json); + } + catch (JsonException) + { + return null; + } + + if (settings != null && !string.IsNullOrEmpty(settings.ProtectedPassword) && _protector != null) + { + settings.Password = _protector.TryUnprotect(settings.ProtectedPassword!); + } + + return settings; + } +} + +/// +/// Protects the passwords of remote repositories at rest. +/// +public interface IRemoteCredentialProtector +{ + /// Protects . + string Protect(string secret); + + /// The secret, or null if cannot be unprotected (keys lost or changed). + string? TryUnprotect(string protectedValue); +} + +/// +/// over ASP.NET Core data protection (the host's key ring). +/// +public sealed class DataProtectionCredentialProtector : IRemoteCredentialProtector +{ + private readonly Microsoft.AspNetCore.DataProtection.IDataProtector _protector; + + public DataProtectionCredentialProtector(Microsoft.AspNetCore.DataProtection.IDataProtectionProvider provider) + { + _protector = (provider ?? throw new ArgumentNullException(nameof(provider))) + .CreateProtector("BaGet.RemoteRepositories.Credentials.v1"); + } + + /// + public string Protect(string secret) => _protector.Protect(secret); + + /// + public string? TryUnprotect(string protectedValue) + { + try + { + return _protector.Unprotect(protectedValue); + } + catch (System.Security.Cryptography.CryptographicException) + { + return null; + } + } +} diff --git a/src/BaGet.Core/Repositories/Remote/RemoteRepositoryState.cs b/src/BaGet.Core/Repositories/Remote/RemoteRepositoryState.cs new file mode 100644 index 000000000..863273277 --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/RemoteRepositoryState.cs @@ -0,0 +1,331 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Protocol; + +namespace BaGet.Core; + +/// +/// What the cache of one remote repository looks like right now (in memory, per node; resets on restart). +/// +/// Cached answers of the upstream (version lists and metadata), expired ones included until used or purged. +/// Remembered "the upstream does not have it" answers still in force. +/// Answers served from the cache. +/// Questions that went to the upstream. +/// Questions answered "not found" from the negative cache. +/// Expired answers served because the upstream could not be reached. +/// Failed attempts to reach the upstream. +/// The last time the upstream answered. +/// The last time it could not be reached. +/// When the current run of failures began, or null while it answers. +/// What failed, without URLs or credentials. +public sealed record RemoteCacheStatus( + int MetadataEntries, + int NegativeEntries, + long Hits, + long Misses, + long NegativeHits, + long StaleServed, + long Failures, + DateTime? LastSuccessUtc, + DateTime? LastFailureUtc, + DateTime? FailingSinceUtc, + string? LastError); + +/// +/// The in-memory state of the remote repositories, shared by every request: parsed settings (so a request does not +/// read the database for them), cached answers of the upstreams, counters and pooled HTTP clients. A singleton. +/// +/// +/// It is keyed by the key of the repository whose upstream it is (for the default repository's mirror, the +/// mirror repository's). Nothing here is shared between nodes: another node sees a settings change within +/// , and each node has its own cache. +/// +public sealed class RemoteRepositoryState +{ + /// How long parsed settings are reused before the database is read again. + public static readonly TimeSpan SettingsLifetime = TimeSpan.FromSeconds(5); + + /// The most cached answers kept per repository. + public const int MaxEntries = 20000; + + private readonly TimeProvider _time; + private readonly ConcurrentDictionary _entries = new(); + + public RemoteRepositoryState(TimeProvider? time = null) + { + _time = time ?? TimeProvider.System; + } + + /// The current time (UTC). + public DateTime UtcNow => _time.GetUtcNow().UtcDateTime; + + private Entry For(int key) => _entries.GetOrAdd(key, _ => new Entry()); + + /// + /// A value looked up for repository (its parsed settings, or for + /// which repository is the mirror), from the cache or else . + /// + internal async Task GetCachedAsync(int key, Func> load) + where T : class + { + var entry = For(key); + var cached = entry.Settings; + if (cached != null && UtcNow - cached.LoadedUtc < SettingsLifetime && cached.Value is T or null) return (T?)cached.Value; + + var loaded = await load().ConfigureAwait(false); + entry.Settings = new LoadedSettings(loaded, UtcNow); + + return loaded; + } + + /// The pseudo key under which the lookup of the mirror repository is cached; no repository has it. + internal const int MirrorLookupKey = -1; + + /// Forgets the parsed settings and the pooled client of a repository (after its settings changed). + public void InvalidateSettings(int key) + { + if (_entries.TryGetValue(key, out var entry)) + { + entry.Settings = null; + entry.Transport = null; + } + } + + /// Forgets everything about a repository (it was deleted). + public void Remove(int key) => _entries.TryRemove(key, out _); + + /// + /// The pooled transport for : rebuilt only when something that affects how the upstream + /// is contacted changed, so a V3 service index is not fetched again for every request. + /// + internal UpstreamTransport GetTransport(int key, RemoteRepositorySettings settings, Func create) + { + var entry = For(key); + var transportKey = settings.TransportKey(); + var current = entry.Transport; + if (current != null && current.Key == transportKey) return current; + + lock (entry) + { + current = entry.Transport; + if (current != null && current.Key == transportKey) return current; + + entry.Transport = current = create(); + + return current; + } + } + + /// The cached value for , with whether it is still fresh. + internal bool TryGet(int key, string cacheKey, out object? value, out bool negative, out bool fresh) + { + value = null; + negative = false; + fresh = false; + + if (!For(key).Metadata.TryGetValue(cacheKey, out var item)) return false; + + value = item.Value; + negative = item.Negative; + fresh = item.ExpiresUtc > UtcNow; + + return true; + } + + /// + /// Remembers an answer for . Nothing is kept for a zero period. At most + /// answers are kept per repository (the oldest go first): an npm packument can be megabytes, a NuGet version list is small. + /// + internal void Set(int key, string cacheKey, object? value, bool negative, TimeSpan ttl, int limit = MaxEntries) + { + if (ttl <= TimeSpan.Zero) return; + + var entry = For(key); + if (entry.Metadata.Count >= limit) Trim(entry, limit); + + // An expired entry stays so it can be served while the upstream is down, until purged or trimmed. + entry.Metadata[cacheKey] = new Item(value, negative, UtcNow + ttl); + } + + private void Trim(Entry entry, int limit) + { + var now = UtcNow; + foreach (var pair in entry.Metadata.Where(p => p.Value.ExpiresUtc <= now).Take(Math.Max(limit / 4, 1)).ToList()) + { + entry.Metadata.TryRemove(pair.Key, out _); + } + + if (entry.Metadata.Count < limit) return; + + foreach (var pair in entry.Metadata.OrderBy(p => p.Value.ExpiresUtc).Take(Math.Max(limit / 4, 1)).ToList()) + { + entry.Metadata.TryRemove(pair.Key, out _); + } + } + + internal void Count(int key, CacheEvent kind) + { + var entry = For(key); + switch (kind) + { + case CacheEvent.Hit: Interlocked.Increment(ref entry.Hits); break; + case CacheEvent.Miss: Interlocked.Increment(ref entry.Misses); break; + case CacheEvent.NegativeHit: Interlocked.Increment(ref entry.NegativeHits); break; + case CacheEvent.Stale: Interlocked.Increment(ref entry.Stale); break; + } + } + + /// Records that the upstream answered. + internal void Succeeded(int key) + { + var entry = For(key); + lock (entry) + { + entry.LastSuccess = UtcNow; + entry.FailingSince = null; + } + } + + /// Records that the upstream could not be reached; is shown on the status page. + internal void Failed(int key, string error) + { + var entry = For(key); + Interlocked.Increment(ref entry.Failures); + lock (entry) + { + var now = UtcNow; + entry.LastFailure = now; + entry.FailingSince ??= now; + entry.LastError = error; + } + } + + /// The cache status of a repository. + public RemoteCacheStatus Status(int key) + { + if (!_entries.TryGetValue(key, out var entry)) + { + return new RemoteCacheStatus(0, 0, 0, 0, 0, 0, 0, null, null, null, null); + } + + var now = UtcNow; + var items = entry.Metadata.Values; + lock (entry) + { + return new RemoteCacheStatus( + items.Count(i => !i.Negative), + items.Count(i => i.Negative && i.ExpiresUtc > now), + Interlocked.Read(ref entry.Hits), + Interlocked.Read(ref entry.Misses), + Interlocked.Read(ref entry.NegativeHits), + Interlocked.Read(ref entry.Stale), + Interlocked.Read(ref entry.Failures), + entry.LastSuccess, + entry.LastFailure, + entry.FailingSince, + entry.LastError); + } + } + + /// Drops every cached answer of a repository. Counters stay. + /// How many answers were dropped. + public int Clear(int key) + { + if (!_entries.TryGetValue(key, out var entry)) return 0; + + var count = entry.Metadata.Count; + entry.Metadata.Clear(); + + return count; + } + + /// Drops the cached answers about one package id (version lists, metadata, 404s of any version). + /// How many answers were dropped. + public int ClearPackage(int key, string packageId) + { + if (!_entries.TryGetValue(key, out var entry)) return 0; + + var id = packageId.ToLowerInvariant(); + var removed = 0; + foreach (var cacheKey in entry.Metadata.Keys.ToList()) + { + // Keys are ":" or ":/". + var rest = cacheKey.Substring(cacheKey.IndexOf(':') + 1); + var name = rest.Contains('/') ? rest.Substring(0, rest.IndexOf('/')) : rest; + if (name == id && entry.Metadata.TryRemove(cacheKey, out _)) removed++; + } + + return removed; + } + + /// + /// Drops the cached answers whose key satisfies (a format whose keys are paths, such as Maven's, cannot + /// use 's name split). + /// + /// How many answers were dropped. + public int ClearMatching(int key, Func match) + { + if (!_entries.TryGetValue(key, out var entry)) return 0; + + var removed = 0; + foreach (var cacheKey in entry.Metadata.Keys.ToList()) + { + if (match(cacheKey) && entry.Metadata.TryRemove(cacheKey, out _)) removed++; + } + + return removed; + } + + internal enum CacheEvent { Hit, Miss, NegativeHit, Stale } + + private sealed record LoadedSettings(object? Value, DateTime LoadedUtc); + + private sealed record Item(object? Value, bool Negative, DateTime ExpiresUtc); + + private sealed class Entry + { + public readonly ConcurrentDictionary Metadata = new(); + public volatile LoadedSettings? Settings; + public volatile UpstreamTransport? Transport; + public long Hits, Misses, NegativeHits, Stale, Failures; + public DateTime? LastSuccess, LastFailure, FailingSince; + public string? LastError; + } +} + +/// +/// The HTTP machinery for one upstream, pooled by . +/// +internal sealed class UpstreamTransport +{ + public UpstreamTransport(string key, HttpClient? http, NuGetClient? v3) + { + Key = key; + Http = http; + V3 = v3; + } + + public string Key { get; } + + public HttpClient? Http { get; } + + public NuGetClient? V3 { get; } + + /// + /// Bearer tokens the upstream's token service issued, by scope (a Docker upstream); they live as long as the transport, which + /// is rebuilt when the URL or the credentials change, so a token never outlives the settings it was obtained with. + /// + internal ConcurrentDictionary Tokens { get; } = new(); + + /// Set once the upstream has answered a request with a Basic challenge: the credentials are then sent to its host at once. + internal volatile bool BasicChallenged; +} + +/// A bearer token and when it stops being valid. +/// The token. +/// When to ask for another. +internal sealed record UpstreamToken(string Value, DateTime ExpiresUtc); diff --git a/src/BaGet.Core/Repositories/Remote/RemoteUpstreamClient.cs b/src/BaGet.Core/Repositories/Remote/RemoteUpstreamClient.cs new file mode 100644 index 000000000..b02043370 --- /dev/null +++ b/src/BaGet.Core/Repositories/Remote/RemoteUpstreamClient.cs @@ -0,0 +1,446 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Protocol; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// The upstream a repository fetches from, as resolved it. +/// +/// The key of the repository that owns the settings and the cache: the remote repository itself, or for the default repository's mirror the mirror repository (0 when it has none, the settings then coming from Mirror:*). +/// That repository's name. +/// The upstream's settings, password in clear (memory only). +public sealed record ResolvedUpstream(int Key, string Name, RemoteRepositorySettings Settings); + +/// +/// Decides which upstream, if any, serves a repository. The seam of D3 in the Artifactory plan: a remote repository +/// is its own upstream; the default repository uses the mirror remote repository while Mirror:Enabled +/// is set; when virtual repositories arrive, a virtual one resolves its members here. +/// +public interface IRemoteUpstreamSource +{ + /// The upstream of , or null when it has none (a local repository). + Task ResolveAsync(RepositoryInfo repository, CancellationToken cancellationToken); +} + +/// +/// over the repositories table and the Mirror:* options. +/// +public sealed class RemoteUpstreamSource : IRemoteUpstreamSource +{ + private sealed record MirrorRow(int Key); + + private readonly IContext _context; + private readonly RemoteSettingsCodec _codec; + private readonly RemoteRepositoryState _state; + private readonly IOptions _mirror; + + public RemoteUpstreamSource( + IContext context, + RemoteSettingsCodec codec, + RemoteRepositoryState state, + IOptions mirror) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _codec = codec ?? throw new ArgumentNullException(nameof(codec)); + _state = state ?? throw new ArgumentNullException(nameof(state)); + _mirror = mirror ?? throw new ArgumentNullException(nameof(mirror)); + } + + /// + public async Task ResolveAsync(RepositoryInfo repository, CancellationToken cancellationToken) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + + if (repository.Kind == RepositoryKind.Remote) + { + var settings = await LoadAsync(repository.Key, cancellationToken).ConfigureAwait(false); + + return settings == null ? null : new ResolvedUpstream(repository.Key, repository.Name, settings); + } + + if (!repository.IsDefault) return null; + + var mirror = _mirror.Value; + if (!mirror.Enabled || mirror.PackageSource == null) return null; + + var row = await _state.GetCachedAsync( + RemoteRepositoryState.MirrorLookupKey, + async () => await FindMirrorRowAsync(cancellationToken).ConfigureAwait(false)).ConfigureAwait(false); + var fromRow = row == null ? null : await LoadAsync(row.Key, cancellationToken).ConfigureAwait(false); + if (row == null || fromRow == null) + { + return new ResolvedUpstream(0, Repository.MirrorName, RemoteRepositorySettings.FromMirror(mirror)); + } + + // Mirror:* stays authoritative for where the upstream is; the repository holds the rest (credentials, cache + // periods, offline). It is restart-required configuration, so this only ever changes with a restart. + var settings2 = fromRow.Clone(); + settings2.Url = mirror.PackageSource.AbsoluteUri; + settings2.Protocol = mirror.Legacy ? RemoteProtocol.V2 : RemoteProtocol.V3; + settings2.DownloadTimeoutSeconds = mirror.PackageDownloadTimeoutSeconds; + + return new ResolvedUpstream(row.Key, Repository.MirrorName, settings2); + } + + private async Task FindMirrorRowAsync(CancellationToken cancellationToken) + { + if (_context is NullContext) return null; + + var key = await _context.Repositories!.AsNoTracking() + .Where(r => r.Name == Repository.MirrorName && r.Kind == RepositoryKind.Remote && r.Format == RepositoryFormat.NuGet) + .Select(r => (int?)r.Key) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + + return key == null ? null : new MirrorRow(key.Value); + } + + private async Task LoadAsync(int key, CancellationToken cancellationToken) + { + if (_context is NullContext) return null; + + return await _state.GetCachedAsync(key, async () => + { + var json = await _context.Repositories!.AsNoTracking() + .Where(r => r.Key == key && r.Kind == RepositoryKind.Remote) + .Select(r => r.Settings) + .FirstOrDefaultAsync(cancellationToken) + .ConfigureAwait(false); + + var settings = _codec.Deserialize(json); + + return settings != null && settings.Validate().Count == 0 ? settings : null; + }).ConfigureAwait(false); + } +} + +/// +/// An that is also told how the repository treats what it fetches. +/// +public interface IPassThroughUpstreamClient : IUpstreamClient +{ + /// + /// True when the repository does not keep what it fetches ( + /// off): the package service then answers from the upstream directly and streams downloads through. + /// + Task IsPassThroughAsync(CancellationToken cancellationToken); +} + +/// +/// The of the current repository (): resolves its +/// upstream, honours offline mode, reuses answers for the metadata period, remembers 404s for the negative period, and +/// serves an expired answer when the upstream cannot be reached. A repository without an upstream gets empty answers, +/// like . +/// +/// +/// A failure to reach the upstream is never cached as "not found" (only a 404 is), and is recorded in the repository's +/// . It is logged without the URL's query or any credential. +/// +public sealed class RemoteUpstreamClient : IPassThroughUpstreamClient +{ + private static readonly IReadOnlyList NoVersions = Array.Empty(); + private static readonly IReadOnlyList NoPackages = Array.Empty(); + + private readonly IRepositoryContext? _repository; + private readonly IRemoteUpstreamSource _source; + private readonly RemoteRepositoryState _state; + private readonly IRemoteHttpClientFactory _http; + private readonly ILoggerFactory _loggers; + private readonly ILogger _logger; + + public RemoteUpstreamClient( + IRepositoryContext? repository, + IRemoteUpstreamSource source, + RemoteRepositoryState state, + IRemoteHttpClientFactory http, + ILoggerFactory loggers) + { + _repository = repository; + _source = source ?? throw new ArgumentNullException(nameof(source)); + _state = state ?? throw new ArgumentNullException(nameof(state)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _loggers = loggers ?? throw new ArgumentNullException(nameof(loggers)); + _logger = loggers.CreateLogger(); + } + + private Task ResolveAsync(CancellationToken cancellationToken) + => _source.ResolveAsync(_repository?.Current ?? RepositoryInfo.Default, cancellationToken); + + /// + public async Task IsPassThroughAsync(CancellationToken cancellationToken) + { + var upstream = await ResolveAsync(cancellationToken).ConfigureAwait(false); + + return upstream != null && !upstream.Settings.StoreLocally; + } + + /// + public async Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) + { + var upstream = await ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return NoVersions; + + return await CachedAsync( + upstream, + "v:" + id.ToLowerInvariant(), + NoVersions, + ct => Inner(upstream, out var dispose).WithDispose(dispose, c => c.ListPackageVersionsAsync(id, ct)), + cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> ListPackagesAsync(string id, CancellationToken cancellationToken) + { + var upstream = await ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return NoPackages; + + return await CachedAsync( + upstream, + "p:" + id.ToLowerInvariant(), + NoPackages, + ct => Inner(upstream, out var dispose).WithDispose(dispose, c => c.ListPackagesAsync(id, ct)), + cancellationToken).ConfigureAwait(false); + } + + /// + public async Task DownloadPackageOrNullAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + var upstream = await ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return null; + + var key = upstream.Key; + var cacheKey = DownloadCacheKey(id, version); + if (DownloadGate(upstream, cacheKey) != Gate.Ask) return null; + + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + + try + { + var stream = await Inner(upstream, out var dispose) + .WithDispose(dispose, c => c.DownloadPackageOrNullAsync(id, version, cancellationToken)) + .ConfigureAwait(false); + _state.Succeeded(key); + + if (stream == null) + { + _state.Set(key, cacheKey, null, negative: true, TimeSpan.FromSeconds(upstream.Settings.NegativeTtlSeconds)); + } + + return stream; + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + Fail(upstream, e); + + return null; + } + } + + /// + /// Applies the gate a download applies (offline, remembered "not found"), then asks the version list. + public async Task ProbeAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + var upstream = await ResolveAsync(cancellationToken).ConfigureAwait(false); + if (upstream == null) return UpstreamProbe.Absent; + + switch (DownloadGate(upstream, DownloadCacheKey(id, version))) + { + case Gate.Offline: return UpstreamProbe.Offline; + case Gate.KnownAbsent: return UpstreamProbe.Absent; + } + + // The list answers "nothing" when the upstream fails and counts the failure, which is how a down upstream is + // told from one that simply does not have the package. + var failuresBefore = _state.Status(upstream.Key).Failures; + var versions = await ListPackageVersionsAsync(id, cancellationToken).ConfigureAwait(false); + if (versions.Contains(version)) return UpstreamProbe.Available; + + return _state.Status(upstream.Key).Failures > failuresBefore ? UpstreamProbe.Unavailable : UpstreamProbe.Absent; + } + + private enum Gate + { + Ask, + Offline, + KnownAbsent, + } + + private static string DownloadCacheKey(string? id, NuGetVersion version) + => "d:" + (id ?? string.Empty).ToLowerInvariant() + "/" + version.ToNormalizedString().ToLowerInvariant(); + + // Whether a download is asked of the upstream at all: never offline, not while a fresh 404 is remembered. Download and + // Probe share it so the preview cannot disagree with a real request. + private Gate DownloadGate(ResolvedUpstream upstream, string cacheKey) + { + if (upstream.Settings.Offline) return Gate.Offline; + + if (_state.TryGet(upstream.Key, cacheKey, out _, out var negative, out var fresh) && negative && fresh) + { + _state.Count(upstream.Key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return Gate.KnownAbsent; + } + + return Gate.Ask; + } + + // The metadata period, the negative period, offline mode and stale-on-error around one question. + private async Task> CachedAsync( + ResolvedUpstream upstream, + string cacheKey, + IReadOnlyList none, + Func>> ask, + CancellationToken cancellationToken) + { + var key = upstream.Key; + var settings = upstream.Settings; + var cached = _state.TryGet(key, cacheKey, out var value, out var negative, out var fresh); + + // Offline: whatever is remembered, however old; else nothing. The upstream is not contacted. + if (settings.Offline) + { + if (cached && !negative && value is IReadOnlyList remembered) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return remembered; + } + + return none; + } + + if (cached && fresh) + { + if (negative) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.NegativeHit); + + return none; + } + + if (value is IReadOnlyList hit) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Hit); + + return hit; + } + } + + _state.Count(key, RemoteRepositoryState.CacheEvent.Miss); + + try + { + var answer = await ask(cancellationToken).ConfigureAwait(false); + _state.Succeeded(key); + + if (answer.Count == 0) + { + _state.Set(key, cacheKey, null, negative: true, TimeSpan.FromSeconds(settings.NegativeTtlSeconds)); + } + else + { + _state.Set(key, cacheKey, answer, negative: false, TimeSpan.FromSeconds(settings.MetadataTtlSeconds)); + } + + return answer; + } + catch (Exception e) when (e is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + Fail(upstream, e); + + if (cached && !negative && value is IReadOnlyList stale) + { + _state.Count(key, RemoteRepositoryState.CacheEvent.Stale); + + return stale; + } + + return none; + } + } + + private void Fail(ResolvedUpstream upstream, Exception e) + { + var what = Describe(e); + _state.Failed(upstream.Key, what); + + // The exception itself is not logged: its message can carry the upstream's URL with a query string. + _logger.LogWarning( + "The upstream of repository {Repository} could not be reached: {Error}", + upstream.Name, + what); + } + + /// A description of a failure that is safe to show and log: no URL, no header, no credential. + internal static string Describe(Exception e) + { + var inner = e is AggregateException { InnerException: { } a } ? a : e; + var text = inner.GetType().Name; + + if (inner is System.Net.Http.HttpRequestException http) + { + if (http.StatusCode != null) return $"{text}: HTTP {(int)http.StatusCode} {http.StatusCode}"; + if (http.InnerException != null) text += " (" + http.InnerException.GetType().Name + ")"; + } + else if (inner is TaskCanceledException or TimeoutException) + { + return "The upstream timed out."; + } + + return text; + } + + // The client of the upstream for one call. V3 shares a pooled transport (its service index is cached); a V2 client + // owns a NuGet source cache, so it is disposed after the call. + private IUpstreamClient Inner(ResolvedUpstream upstream, out IDisposable? dispose) + { + var settings = upstream.Settings; + dispose = null; + + if (settings.Protocol == RemoteProtocol.V2) + { + var client = new V2UpstreamClient( + settings.UrlOrNull!, settings.Username, settings.Password, _loggers.CreateLogger(), propagateErrors: true); + dispose = client; + + return client; + } + + var transport = _state.GetTransport(upstream.Key, settings, () => + { + var http = _http.Create(settings); + + return new UpstreamTransport( + settings.TransportKey(), + http, + new NuGetClient(new NuGetClientFactory(http, settings.UrlOrNull!.AbsoluteUri))); + }); + + return new V3UpstreamClient(transport.V3!, _loggers.CreateLogger(), propagateErrors: true); + } +} + +internal static class UpstreamCallExtensions +{ + // Runs a call on a client and disposes it (a V2 client) afterwards. + public static async Task WithDispose(this IUpstreamClient client, IDisposable? dispose, Func> call) + { + try + { + return await call(client).ConfigureAwait(false); + } + finally + { + dispose?.Dispose(); + } + } +} diff --git a/src/BaGet.Core/Repositories/Repository.cs b/src/BaGet.Core/Repositories/Repository.cs new file mode 100644 index 000000000..00eda1436 --- /dev/null +++ b/src/BaGet.Core/Repositories/Repository.cs @@ -0,0 +1,99 @@ +using System; + +namespace BaGet.Core; + +/// +/// A named package repository. The unit every package, owner, catalog entry, validation and abuse report +/// belongs to, through its . +/// +/// +/// Format-specific metadata (a future npm or Maven table) hangs off in tables of its own, so +/// the common columns here stay format-neutral. The repository (key +/// ) is the one served at /; it is created at startup when missing and holds every +/// row that predates repositories. +/// +public class Repository +{ + /// + /// The name of the repository served at /. + /// + public const string DefaultName = "default"; + + /// + /// The key of the repository: the value migrations give every pre-existing row. + /// + public const int DefaultKey = 1; + + /// + /// The name of the remote repository created from the Mirror:* options when Mirror:Enabled is set; + /// the default repository fetches through it (see ). + /// + public const string MirrorName = "mirror"; + + public int Key { get; set; } + + /// + /// Unique, and valid per . It appears in URLs and storage paths, so it is + /// never renamed. + /// + public string? Name { get; set; } + + public RepositoryFormat Format { get; set; } + + public RepositoryKind Kind { get; set; } + + /// + /// The that owns the repository, if any. A Restrict foreign key to (nullable); + /// deleting the project clears it first. + /// + public int? ProjectKey { get; set; } + + /// + /// Format and kind specific settings as JSON: a remote's upstream (, read + /// and written by only, as it holds a protected password), later a virtual's + /// members. Opaque to the common code. + /// + public string? Settings { get; set; } + + /// + /// Whether requests without credentials may read the repository. + /// + public bool AnonymousRead { get; set; } = true; + + public DateTime Created { get; set; } + + /// + /// The immutable view of this row that carries. + /// + public RepositoryInfo ToInfo() => new(Key, Name ?? string.Empty, Format, Kind); +} + +/// +/// A group of repositories with its own administrators (Artifactory's projects). +/// +public class Project +{ + public int Key { get; set; } + + /// + /// Unique; lowercase letters, digits and hyphens (Artifactory's "project key"). + /// + public string? Name { get; set; } + + public string? DisplayName { get; set; } + + public DateTime Created { get; set; } +} + +/// +/// An entity that belongs to one . The context filters every query on these by the +/// current repository () and stamps new rows with it. RepositoryKey is a Restrict foreign key +/// to : the code that deletes a repository removes the rows first. +/// +public interface IRepositoryScoped +{ + /// + /// The owning . Left 0 on a new row, it is set to the current repository on save. + /// + int RepositoryKey { get; set; } +} diff --git a/src/BaGet.Core/Repositories/RepositoryAdministration.cs b/src/BaGet.Core/Repositories/RepositoryAdministration.cs new file mode 100644 index 000000000..00a65be8b --- /dev/null +++ b/src/BaGet.Core/Repositories/RepositoryAdministration.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// over the relational database. With a database that is not relational +/// () only the default repository is listed, without a package count, and nothing can be edited. +/// +/// +/// Repository-scoped tables are read with the query filter off (IgnoreQueryFilters) because the administrator +/// looks across repositories, not inside the current one. +/// +public class RepositoryAdministration : IRepositoryAdministration +{ + private readonly IContext _context; + private readonly IStorageService? _storage; + private readonly SystemTime? _time; + private readonly RemoteRepositoryState? _remoteState; + private readonly FormatRegistry _formats; + + /// The database. + /// The store whose repos/{name}/ folder is emptied when a repository is deleted. Null leaves storage alone. + /// The clock for audit entries and created targets; null uses the system's. + /// The remote repositories' in-memory state, emptied for a deleted one; null has none. + /// The format modules, which count a repository's artifacts and purge its rows; null knows NuGet only. + public RepositoryAdministration(IContext context, IStorageService? storage = null, SystemTime? time = null, RemoteRepositoryState? remoteState = null, FormatRegistry? formats = null) + { + _formats = formats ?? FormatRegistry.Default; + _time = time; + _remoteState = remoteState; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage; + } + + private DateTime Now => _time?.UtcNow ?? DateTime.UtcNow; + + private bool Relational => !(_context is NullContext); + + private static RepositorySummary DefaultSummary => new( + Repository.DefaultKey, Repository.DefaultName, RepositoryFormat.NuGet, RepositoryKind.Local, true, DateTime.UtcNow, 0); + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + if (!Relational) return new[] { DefaultSummary }; + + var rows = await _context.Repositories!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + var counts = new Dictionary(); + foreach (var module in _formats.Modules) + { + foreach (var pair in await module.CountArtifactsAsync(_context, cancellationToken).ConfigureAwait(false)) + { + counts[pair.Key] = (counts.TryGetValue(pair.Key, out var n) ? n : 0) + pair.Value; + } + } + + var all = rows.Select(r => Summarize(r, counts.TryGetValue(r.Key, out var n) ? n : 0)).ToList(); + if (!all.Any(r => r.IsDefault)) all.Add(DefaultSummary); + + return all.OrderBy(r => r.Name, StringComparer.Ordinal).ToList(); + } + + /// + public async Task FindAsync(string? name, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(name)) return null; + + return (await ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(r => r.Name == name); + } + + /// + public async Task SetAnonymousReadAsync(string name, bool anonymousRead, CancellationToken cancellationToken, string? actor = null) + { + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + row.AnonymousRead = anonymousRead; + + var created = false; + if (anonymousRead && !await EveryoneReadsAsync(row, cancellationToken).ConfigureAwait(false)) + { + await GrantEveryoneReadAsync(row, cancellationToken).ConfigureAwait(false); + created = true; + } + + AccessAdministration.Audit(_context, Now, actor, "repository.anonymous-read", name, new { anonymousRead, grantCreated = created }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + // Whether some target grants the Everyone group Read on every package of the repository. + private async Task EveryoneReadsAsync(Repository row, CancellationToken cancellationToken) + { + var everyone = await _context.Groups!.AsNoTracking() + .Where(g => g.IsBuiltIn && g.Name == BuiltInNames.Everyone) + .Select(g => (int?)g.Key).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (everyone == null) return false; + + var id = everyone.Value.ToString(); + var targets = await _context.PermissionGrants!.AsNoTracking() + .Where(g => g.PrincipalType == PrincipalType.Group && g.PrincipalId == id && (g.Actions & AccessAction.Read) != 0) + .Select(g => g.Target!) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return targets.Any(t => + (t.ProjectKey == null || t.ProjectKey == row.ProjectKey) + && GlobSet.Parse(t.RepositoryPatterns, emptyMeansAll: false).IsMatch(row.Name) + && GlobSet.Parse(t.IncludePatterns, emptyMeansAll: true).IsMatch("*") + && !GlobSet.Parse(t.ExcludePatterns, emptyMeansAll: false).IsMatch("*")); + } + + private async Task GrantEveryoneReadAsync(Repository row, CancellationToken cancellationToken) + { + var everyone = await _context.Groups!.AsNoTracking() + .Where(g => g.IsBuiltIn && g.Name == BuiltInNames.Everyone) + .Select(g => (int?)g.Key).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (everyone == null) return; + + var targetName = "Anonymous read " + row.Name; + var target = await _context.PermissionTargets!.FirstOrDefaultAsync(t => t.Name == targetName, cancellationToken).ConfigureAwait(false); + if (target == null) + { + target = new PermissionTarget + { + Name = targetName, + RepositoryPatterns = new[] { row.Name! }, + IncludePatterns = new[] { "*" }, + ExcludePatterns = Array.Empty(), + Created = Now, + }; + _context.PermissionTargets!.Add(target); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + var id = everyone.Value.ToString(); + var grant = await _context.PermissionGrants!.FirstOrDefaultAsync( + g => g.TargetKey == target.Key && g.PrincipalType == PrincipalType.Group && g.PrincipalId == id, cancellationToken).ConfigureAwait(false); + if (grant == null) + { + _context.PermissionGrants!.Add(new PermissionGrant { TargetKey = target.Key, PrincipalType = PrincipalType.Group, PrincipalId = id, Actions = AccessAction.Read }); + } + else + { + grant.Actions |= AccessAction.Read; + } + } + + /// + public async Task DeleteAsync(string name, CancellationToken cancellationToken) + { + if (name == Repository.DefaultName) throw new RepositoryProtectedException(); + + var row = await FindRowAsync(name, cancellationToken).ConfigureAwait(false); + var key = row.Key; + if (key == Repository.DefaultKey) throw new RepositoryProtectedException(); + + // A virtual repository that lists it would silently lose a member (and a deploy target): remove it there first. + var virtuals = (await _context.Repositories!.AsNoTracking().Where(r => r.Kind == RepositoryKind.Virtual).ToListAsync(cancellationToken).ConfigureAwait(false)) + .Where(v => VirtualSettingsCodec.Deserialize(v.Settings).Members.Contains(name)) + .Select(v => v.Name!) + .OrderBy(n => n, StringComparer.Ordinal) + .ToList(); + if (virtuals.Count > 0) throw new RepositoryReferencedException(name, virtuals); + + // Empty means no artifacts and no submission awaiting validation (a pushed package the client already got an + // accepted response for, staged but not indexed yet; deleting would lose it). What the format keeps besides + // (NuGet: the catalog, owners, finished validations, abuse reports, symbol records) is history of a repository that + // no longer exists once it is deleted, and goes with it. The format module knows both. + var module = _formats.Find(row.Format); + if (module != null) + { + var usage = await module.GetUsageAsync(_context, key, cancellationToken).ConfigureAwait(false); + if (usage.Artifacts > 0) throw new RepositoryNotEmptyException(name, remote: row.Kind == RepositoryKind.Remote); + if (usage.PendingWork) throw new RepositoryNotEmptyException(name, awaitingValidation: true); + + await module.StagePurgeAsync(_context, key, cancellationToken).ConfigureAwait(false); + } + + // Retention history of a repository that no longer exists: its policies, legal holds and download times. + _context.RetentionPolicies!.RemoveRange(await _context.RetentionPolicies!.Where(e => e.RepositoryKey == key).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.RetentionHolds!.RemoveRange(await _context.RetentionHolds!.IgnoreQueryFilters().Where(e => e.RepositoryKey == key).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.ArtifactUsages!.RemoveRange(await _context.ArtifactUsages!.IgnoreQueryFilters().Where(e => e.RepositoryKey == key).ToListAsync(cancellationToken).ConfigureAwait(false)); + // What vulnerability scans found in the repository and its scanning policy go with it (the artifacts are already gone). + _context.ScanResults!.RemoveRange(await _context.ScanResults!.IgnoreQueryFilters().Where(r => r.RepositoryKey == key).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.ScanPolicies!.RemoveRange(await _context.ScanPolicies!.Where(p => p.RepositoryKey == key).ToListAsync(cancellationToken).ConfigureAwait(false)); + + // Its replications go with it: configurations, their log and their ledger. + var replications = await _context.ReplicationConfigs!.Where(c => c.RepositoryKey == key).ToListAsync(cancellationToken).ConfigureAwait(false); + if (replications.Count > 0) + { + var replicationKeys = replications.Select(c => c.Key).ToList(); + _context.ReplicationRuns!.RemoveRange(await _context.ReplicationRuns!.Where(r => replicationKeys.Contains(r.ConfigKey)).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.ReplicationItems!.RemoveRange(await _context.ReplicationItems!.Where(i => replicationKeys.Contains(i.ConfigKey)).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.ReplicationConfigs!.RemoveRange(replications); + } + + // A key limited to this repository would otherwise be left with no limit, which means every repository: a key + // limited to several only loses this one, one limited to this alone has no use left and is deleted. + var limits = await _context.ApiKeyRepositories!.Where(e => e.RepositoryKey == key).ToListAsync(cancellationToken).ConfigureAwait(false); + if (limits.Count > 0) + { + var keys = limits.Select(l => l.ApiKeyKey).ToList(); + var others = await _context.ApiKeyRepositories! + .Where(e => keys.Contains(e.ApiKeyKey) && e.RepositoryKey != key) + .Select(e => e.ApiKeyKey) + .Distinct() + .ToListAsync(cancellationToken).ConfigureAwait(false); + var useless = keys.Except(others).ToList(); + + _context.ApiKeys!.RemoveRange(await _context.ApiKeys!.Where(k => useless.Contains(k.Key)).ToListAsync(cancellationToken).ConfigureAwait(false)); + _context.ApiKeyRepositories!.RemoveRange(limits); + } + + _context.Repositories!.Remove(row); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + _remoteState?.Remove(key); + + await PurgeStorageAsync(key, row.Name ?? name, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes every file under repos/{name}/ (symbols, catalog leaves, staged and quarantined uploads, leftovers of + /// hard-deleted packages): storage paths are keyed by name, so a repository created later under the same name would + /// otherwise inherit them. Runs after the database commit; a failure surfaces and a retry is not possible (the row is + /// gone), so the leftovers stay and the administrator is told. + /// + private async Task PurgeStorageAsync(int key, string name, CancellationToken cancellationToken) + { + // A store that cannot list (or no store) cannot be swept; paths are not recorded anywhere else. + if (!(_storage is IListableStorageService listable)) return; + + var prefix = RepositoryStorage.Prefix(new RepositoryInfo(key, name, RepositoryFormat.NuGet, RepositoryKind.Local)); + foreach (var path in await listable.ListAsync(prefix, cancellationToken).ConfigureAwait(false)) + { + await _storage!.DeleteAsync(path, cancellationToken).ConfigureAwait(false); + } + } + + private async Task FindRowAsync(string name, CancellationToken cancellationToken) + { + var row = Relational + ? await _context.Repositories!.FirstOrDefaultAsync(r => r.Name == name, cancellationToken).ConfigureAwait(false) + : null; + + return row ?? throw new KeyNotFoundException($"There is no repository named '{name}'."); + } + + private static RepositorySummary Summarize(Repository r, int packages) + => new(r.Key, r.Name ?? string.Empty, r.Format, r.Kind, r.AnonymousRead, r.Created, packages); +} diff --git a/src/BaGet.Core/Repositories/RepositoryFormat.cs b/src/BaGet.Core/Repositories/RepositoryFormat.cs new file mode 100644 index 000000000..2583e3c5e --- /dev/null +++ b/src/BaGet.Core/Repositories/RepositoryFormat.cs @@ -0,0 +1,54 @@ +namespace BaGet.Core; + +/// +/// The package format a serves. Stored as its name, so a value may be appended +/// but never renumbered or renamed. +/// +public enum RepositoryFormat +{ + /// + /// NuGet (V3 and V2 feeds, symbols). + /// + NuGet = 0, + + /// + /// npm (the registry API under npm/). A repository of this format needs the npm , which a + /// later phase registers; until then none can be created. + /// + Npm = 1, + + /// + /// Maven 2 (the repository layout under maven/): mvn deploy, mvn dependency:get, Gradle. Local + /// repositories only for now. + /// + Maven = 2, + + /// + /// Docker / OCI images (the OCI Distribution Spec v1.1 under /v2/{repository}/{image}/…): docker login, + /// push and pull, multi-arch indexes, referrers. Local repositories only for now; needs a store that streams + /// (). + /// + Docker = 3, +} + +/// +/// How a gets its content. Stored as its name. +/// +public enum RepositoryKind +{ + /// + /// Holds what is pushed to it. + /// + Local = 0, + + /// + /// Caches an upstream repository (). Read-only for clients: nothing can be + /// deployed to it, the server itself stores what it fetches. + /// + Remote = 1, + + /// + /// Presents several repositories as one. + /// + Virtual = 2, +} diff --git a/src/BaGet.Core/Repositories/RepositoryInfo.cs b/src/BaGet.Core/Repositories/RepositoryInfo.cs new file mode 100644 index 000000000..c053459a0 --- /dev/null +++ b/src/BaGet.Core/Repositories/RepositoryInfo.cs @@ -0,0 +1,29 @@ +namespace BaGet.Core; + +/// +/// What a request, job or command needs to know about the repository it works in: immutable, and small enough to +/// copy around. +/// +/// The . +/// The . +/// The package format served. +/// How the repository gets its content. +public sealed record RepositoryInfo(int Key, string Name, RepositoryFormat Format, RepositoryKind Kind) +{ + /// + /// The repository served at /. + /// + public static RepositoryInfo Default { get; } = + new(Repository.DefaultKey, Repository.DefaultName, RepositoryFormat.NuGet, RepositoryKind.Local); + + /// + /// Whether this is the repository. + /// + public bool IsDefault => Key == Repository.DefaultKey; + + /// + /// The path in front of this repository's routes, feeds and pages, without a leading slash: nothing for the + /// default repository (served at /), else r/{name}/. + /// + public string PathPrefix => IsDefault ? string.Empty : "r/" + System.Uri.EscapeDataString(Name) + "/"; +} diff --git a/src/BaGet.Core/Repositories/RepositoryNames.cs b/src/BaGet.Core/Repositories/RepositoryNames.cs new file mode 100644 index 000000000..db28b336f --- /dev/null +++ b/src/BaGet.Core/Repositories/RepositoryNames.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// The one definition of what a repository may be called. A name is a URL segment (/r/{name}/) and a +/// storage folder, so it is restricted to lowercase [a-z0-9-._], 1 to 64 characters, and may not +/// collide with a path BaGet itself serves. +/// +public static class RepositoryNames +{ + public const int MaxLength = 64; + + /// + /// Names that would shadow a route or static path. Compared case-insensitively. + /// + public static readonly IReadOnlyCollection Reserved = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "r", "api", "v2", "v3", "admin", "account", "packages", "profiles", "symbols", "catalog", + "upload", "health", "css", "js", "lib", "images", "favicon.ico", "_content", "_framework", + }; + + /// + /// Checks . + /// + /// The candidate name. + /// Why it is refused, or null. + /// Whether the name may be used. + public static bool IsValid(string? name, out string? error) + { + if (string.IsNullOrEmpty(name)) + { + error = "A repository name is required."; + return false; + } + + if (name.Length > MaxLength) + { + error = $"A repository name is at most {MaxLength} characters."; + return false; + } + + foreach (var c in name) + { + if (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && c != '-' && c != '.' && c != '_') + { + error = "A repository name uses only lowercase letters, digits, '-', '.' and '_'."; + return false; + } + } + + if (name[0] == '.' || name[name.Length - 1] == '.' || name.Contains("..")) + { + error = "A repository name cannot start or end with '.' or contain '..'."; + return false; + } + + if (((HashSet)Reserved).Contains(name)) + { + error = $"'{name}' is reserved."; + return false; + } + + error = null; + return true; + } + + /// + public static bool IsValid(string? name) => IsValid(name, out _); +} diff --git a/src/BaGet.Core/Repositories/RepositoryService.cs b/src/BaGet.Core/Repositories/RepositoryService.cs new file mode 100644 index 000000000..36e9eaa2c --- /dev/null +++ b/src/BaGet.Core/Repositories/RepositoryService.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// +/// over the relational database. When the database is not relational +/// (, as with Azure Table) or the search index is not repository-aware +/// (Search:Type = AzureSearch: one global index with package-id document keys) only the default +/// repository exists, others stored in the database are not served, and creating another is refused with a +/// message saying why. +/// +public class RepositoryService : IRepositoryService +{ + private readonly IContext _context; + private readonly IOptions? _search; + private readonly RemoteSettingsCodec _codec; + private readonly IOptionsSnapshot? _remoteOptions; + private readonly FormatRegistry _formats; + private readonly IStorageService? _storage; + + /// The database. + /// The search options (whether the index is repository-aware). + /// Writes a remote repository's settings; null stores them without being able to protect a password. + /// The Remote:* options (whether private upstream addresses are refused). + /// The format modules (which formats and kinds can be created); null knows NuGet only. + /// The configured store; a format that is refused when it cannot stream. Null skips that check. + public RepositoryService(IContext context, IOptions? search = null, RemoteSettingsCodec? codec = null, IOptionsSnapshot? remoteOptions = null, FormatRegistry? formats = null, IStorageService? storage = null) + { + _storage = storage; + _formats = formats ?? FormatRegistry.Default; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _search = search; + _codec = codec ?? new RemoteSettingsCodec(); + _remoteOptions = remoteOptions; + } + + /// + public bool SupportsMultipleRepositories + => !(_context is NullContext) + && !string.Equals(_search?.Value?.Type, "AzureSearch", StringComparison.OrdinalIgnoreCase); + + /// + public async Task FindAsync(string? name, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(name)) return null; + + if (SupportsMultipleRepositories) + { + var row = await _context.Repositories! + .AsNoTracking() + .FirstOrDefaultAsync(r => r.Name == name, cancellationToken) + .ConfigureAwait(false); + if (row != null) return row.ToInfo(); + } + + // A database that has not been through EnsureDefaultAsync yet still serves the default repository. + return name == Repository.DefaultName ? RepositoryInfo.Default : null; + } + + /// + public async Task FindAsync(int key, CancellationToken cancellationToken) + { + if (SupportsMultipleRepositories) + { + var row = await _context.Repositories! + .AsNoTracking() + .FirstOrDefaultAsync(r => r.Key == key, cancellationToken) + .ConfigureAwait(false); + if (row != null) return row.ToInfo(); + } + + return key == Repository.DefaultKey ? RepositoryInfo.Default : null; + } + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + var all = new List(); + if (SupportsMultipleRepositories) + { + var rows = await _context.Repositories!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + all.AddRange(rows.Select(r => r.ToInfo())); + } + + if (!all.Any(r => r.IsDefault)) all.Add(RepositoryInfo.Default); + + return all.OrderBy(r => r.Name, StringComparer.Ordinal).ToList(); + } + + /// + public Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + CancellationToken cancellationToken) + => CreateAsync(name, format, kind, remote: null, cancellationToken); + + /// + public Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + RemoteRepositorySettings? remote, + CancellationToken cancellationToken) + => CreateCoreAsync(name, format, kind, remote, anonymousRead: null, fields: null, cancellationToken); + + /// + public Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + RemoteRepositorySettings? remote, + bool anonymousRead, + CancellationToken cancellationToken) + => CreateCoreAsync(name, format, kind, remote, anonymousRead, fields: null, cancellationToken); + + /// + public Task CreateAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + IReadOnlyDictionary fields, + bool anonymousRead, + CancellationToken cancellationToken) + => CreateCoreAsync(name, format, kind, remote: null, anonymousRead, fields ?? throw new ArgumentNullException(nameof(fields)), cancellationToken); + + private async Task CreateCoreAsync( + string name, + RepositoryFormat format, + RepositoryKind kind, + RemoteRepositorySettings? remote, + bool? anonymousRead, + IReadOnlyDictionary? fields, + CancellationToken cancellationToken) + { + if (!RepositoryNames.IsValid(name, out var error)) throw new ArgumentException(error, nameof(name)); + + if (!SupportsMultipleRepositories) + { + throw new NotSupportedException( + "Only the 'default' repository is available with this configuration; use a relational database (SQLite, SQL Server, PostgreSQL or MySQL) and a search type other than AzureSearch (whose index is not repository-aware) to create more."); + } + + var module = _formats.Find(format) + ?? throw new NotSupportedException($"The {format} format is not available on this server."); + // A virtual repository holds no blobs of its own; local and remote ones of a streaming format need a store that streams. + if (module.RequiresStreamingStorage && kind != RepositoryKind.Virtual && _storage != null) + { + StreamingStorage.Require(_storage, $"{module.DisplayName} repositories"); + } + + if (!module.CreatableKinds.Contains(kind)) + { + throw new NotSupportedException( + kind == RepositoryKind.Virtual + ? "A virtual repository needs its members: create it with IVirtualRepositoryAdministration." + : $"Only {string.Join(" and ", module.CreatableKinds.Select(k => k.ToString().ToLowerInvariant()))} {module.DisplayName} repositories can be created here."); + } + + string? settings = null; + if (fields != null) + { + if (kind == RepositoryKind.Remote) throw new ArgumentException("A remote repository takes its upstream settings, not form fields.", nameof(fields)); + + settings = module.CreateSettings(fields); + } + + if (kind == RepositoryKind.Remote) + { + if (remote == null) throw new ArgumentException("A remote repository needs its upstream settings.", nameof(remote)); + + // The protocol is the format's: npm speaks only the npm registry protocol, NuGet V3 or V2. + remote = remote.ForFormat(format); + var problems = remote.Validate(_remoteOptions?.Value?.BlockPrivateAddresses == true); + if (problems.Count > 0) throw new ArgumentException(string.Join(" ", problems), nameof(remote)); + + settings = _codec.Serialize(remote); + } + else if (remote != null) + { + throw new ArgumentException("Only a remote repository has upstream settings.", nameof(remote)); + } + + // Migrations create the default row; restore it if it is missing (key 1 is what every existing row carries, so + // a new repository must never take it) and refuse when it cannot be restored. + await EnsureDefaultAsync(cancellationToken).ConfigureAwait(false); + + if (await _context.Repositories!.AnyAsync(r => r.Name == name, cancellationToken).ConfigureAwait(false)) + { + throw new RepositoryExistsException(name); + } + + var repository = new Repository + { + Name = name, + Format = format, + Kind = kind, + Settings = settings, + // A remote repository with credentials is not readable anonymously unless asked: it would hand whatever those + // credentials can fetch to anyone. + AnonymousRead = anonymousRead ?? !(remote?.HasCredentials ?? false), + Created = DateTime.UtcNow, + }; + + _context.Repositories!.Add(repository); + + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e)) + { + throw new RepositoryExistsException(name); + } + + return repository.ToInfo(); + } + + /// + public async Task EnsureDefaultAsync(CancellationToken cancellationToken) + { + if (!SupportsMultipleRepositories) return; + + if (await _context.Repositories!.AnyAsync(r => r.Key == Repository.DefaultKey, cancellationToken).ConfigureAwait(false)) + { + return; + } + + // The default row must have key 1, which rows that predate repositories already carry. Generated keys only + // start at 1 in a table that never held a row (SQLite and MySQL keep counting after a delete), so the key is + // given explicitly. + var anyRow = await _context.Repositories!.AnyAsync(cancellationToken).ConfigureAwait(false); + if (anyRow) + { + throw new InvalidOperationException( + $"The database has repositories but none with key {Repository.DefaultKey}; the '{Repository.DefaultName}' repository cannot be restored."); + } + + _context.Repositories!.Add(new Repository + { + Key = Repository.DefaultKey, + Name = Repository.DefaultName, + Format = RepositoryFormat.NuGet, + Kind = RepositoryKind.Local, + AnonymousRead = true, + Created = DateTime.UtcNow, + }); + + var entityType = (_context as DbContext)?.Model.FindEntityType(typeof(Repository)); + if (entityType != null) await _context.BeginKeyedInsertAsync(entityType, cancellationToken).ConfigureAwait(false); + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e)) + { + // Another node or a concurrent start created it. + } + finally + { + if (entityType != null) await _context.EndKeyedInsertAsync(entityType, CancellationToken.None).ConfigureAwait(false); + } + } +} diff --git a/src/BaGet.Core/Repositories/RepositoryStorage.cs b/src/BaGet.Core/Repositories/RepositoryStorage.cs new file mode 100644 index 000000000..68b3d5872 --- /dev/null +++ b/src/BaGet.Core/Repositories/RepositoryStorage.cs @@ -0,0 +1,54 @@ +using System; + +namespace BaGet.Core; + +/// +/// The one definition of where a repository keeps its files. The repository +/// keeps the layout that predates repositories (packages/…, symbols/…, catalog/…, +/// validation/…, staging/…), so existing stores need no migration; every other repository nests the +/// same layout under repos/{name}/. +/// +/// +/// The name becomes a folder, so a non-default name is re-validated here with +/// (defence in depth: the repository service already validates it) and never concatenated unchecked. +/// +public static class RepositoryStorage +{ + /// + /// The folder that holds every non-default repository. + /// + public const string ReposFolder = "repos"; + + /// + /// The prefix to put before a storage path: empty for the default repository, else repos/{name}/. + /// + /// A non-default repository whose name is not valid. + public static string Prefix(RepositoryInfo repository) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + if (repository.IsDefault) return string.Empty; + + if (!RepositoryNames.IsValid(repository.Name, out var error)) + { + throw new ArgumentException($"Repository name '{repository.Name}' cannot be used in a storage path: {error}", nameof(repository)); + } + + return $"{ReposFolder}/{repository.Name}/"; + } + + /// + /// Scopes a forward-slash storage (catalog/x.json) to . + /// + public static string Scope(RepositoryInfo repository, string path) => Prefix(repository) + path; + + /// + /// The folder segments to put before the segments of a path built with : + /// none for the default repository, else repos and the name. Keeps default paths byte-identical to before. + /// + public static string[] Segments(RepositoryInfo repository) + { + var prefix = Prefix(repository); + + return prefix.Length == 0 ? Array.Empty() : new[] { ReposFolder, repository.Name }; + } +} diff --git a/src/BaGet.Core/Repositories/Virtual/IRequestCaller.cs b/src/BaGet.Core/Repositories/Virtual/IRequestCaller.cs new file mode 100644 index 000000000..de005f41f --- /dev/null +++ b/src/BaGet.Core/Repositories/Virtual/IRequestCaller.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Who is asking, for code in Core that must filter what it shows by the caller's rights (a virtual repository reads +/// only the members the caller may read). The host's request pipeline calls with a resolver; the +/// credentials are read only when something asks. Scoped. Without a resolver the caller is anonymous. +/// +public interface IRequestCaller +{ + /// The caller's principal, or null for an anonymous one. + Task GetAsync(CancellationToken cancellationToken); + + /// Sets how the caller is found (once per request or job). + void Use(Func> resolver); +} + +/// The scoped ; the answer is kept for the scope. +public sealed class RequestCaller : IRequestCaller +{ + private Func>? _resolver; + private Task? _resolved; + + /// + public Task GetAsync(CancellationToken cancellationToken) + { + if (_resolver == null) return Task.FromResult(null); + + // Resolved once per scope (a request or job). + return _resolved ??= _resolver(cancellationToken); + } + + /// + public void Use(Func> resolver) + { + _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); + _resolved = null; + } +} diff --git a/src/BaGet.Core/Repositories/Virtual/IVirtualRepositories.cs b/src/BaGet.Core/Repositories/Virtual/IVirtualRepositories.cs new file mode 100644 index 000000000..ceeb8ed16 --- /dev/null +++ b/src/BaGet.Core/Repositories/Virtual/IVirtualRepositories.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// +/// Answers what a repository is made of, from the stored settings and without any +/// access check (see for what the caller may read). +/// +public interface IVirtualRepositories +{ + /// + /// The repositories that answer for , in resolution order: its members, with a + /// member that is itself virtual replaced in place by its own members. Each repository appears once (its first + /// place counts), a cycle is cut where it closes, and members that no longer exist or are of another format than the + /// virtual repository are skipped. The result holds local and remote repositories only. + /// + Task> EffectiveMembersAsync(RepositoryInfo virtualRepository, CancellationToken cancellationToken); + + /// + /// The local repository that receives what is pushed to : its deploy repository, + /// or, when that is virtual too, the one it deploys to. Null when none is set or the chain does not end in a local + /// repository. + /// + Task DeployTargetAsync(RepositoryInfo virtualRepository, CancellationToken cancellationToken); +} + +/// +/// over the repositories table. Scoped: the table is read once per instance (it is +/// a handful of rows), so a long-lived instance does not see a later change; take a new scope for that. +/// +public sealed class VirtualRepositories : IVirtualRepositories +{ + private const int MaxDepth = 16; + + private readonly IContext _context; + private Dictionary? _byName; + + public VirtualRepositories(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + public async Task> EffectiveMembersAsync(RepositoryInfo virtualRepository, CancellationToken cancellationToken) + { + if (virtualRepository == null) throw new ArgumentNullException(nameof(virtualRepository)); + + var rows = await LoadAsync(cancellationToken).ConfigureAwait(false); + var result = new List(); + var keys = new HashSet(); + Flatten(virtualRepository.Name, rows, new HashSet(StringComparer.Ordinal), result, keys, depth: 0); + + return result; + } + + /// + public async Task DeployTargetAsync(RepositoryInfo virtualRepository, CancellationToken cancellationToken) + { + if (virtualRepository == null) throw new ArgumentNullException(nameof(virtualRepository)); + + var rows = await LoadAsync(cancellationToken).ConfigureAwait(false); + + return ResolveDeploy(virtualRepository.Name, rows); + } + + /// The deploy target of the virtual repository in , or null. + internal static RepositoryInfo? ResolveDeploy(string name, IReadOnlyDictionary rows) + { + var visited = new HashSet(StringComparer.Ordinal); + var current = name; + for (var depth = 0; depth < MaxDepth; depth++) + { + if (!visited.Add(current) || !rows.TryGetValue(current, out var row) || row.Kind != RepositoryKind.Virtual) return null; + + var next = VirtualSettingsCodec.Deserialize(row.Settings).DeployRepository; + if (string.IsNullOrEmpty(next) || !rows.TryGetValue(next!, out var target)) return null; + if (target.Format != row.Format) return null; + if (target.Kind == RepositoryKind.Local) return target.ToInfo(); + if (target.Kind != RepositoryKind.Virtual) return null; + + current = next!; + } + + return null; + } + + // Depth-first, in member order. 'path' holds the virtual repositories being expanded, which is what detects a cycle. + internal static void Flatten( + string name, + IReadOnlyDictionary rows, + HashSet path, + List result, + HashSet keys, + int depth) + { + if (depth > MaxDepth || !path.Add(name)) return; + if (!rows.TryGetValue(name, out var row)) { path.Remove(name); return; } + + foreach (var memberName in VirtualSettingsCodec.Deserialize(row.Settings).Members) + { + // A virtual repository is of one format: its members are too. + if (!rows.TryGetValue(memberName, out var member) || member.Format != row.Format) continue; + + if (member.Kind == RepositoryKind.Virtual) + { + Flatten(memberName, rows, path, result, keys, depth + 1); + } + else if (keys.Add(member.Key)) + { + result.Add(member.ToInfo()); + } + } + + path.Remove(name); + } + + private async Task> LoadAsync(CancellationToken cancellationToken) + { + if (_byName != null) return _byName; + + var rows = _context.Repositories == null + ? new List() + : await _context.Repositories.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + + return _byName = rows + .Where(r => r.Name != null) + .ToDictionary(r => r.Name!, StringComparer.Ordinal); + } +} diff --git a/src/BaGet.Core/Repositories/Virtual/VirtualReadServices.cs b/src/BaGet.Core/Repositories/Virtual/VirtualReadServices.cs new file mode 100644 index 000000000..db7c480e6 --- /dev/null +++ b/src/BaGet.Core/Repositories/Virtual/VirtualReadServices.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Protocol.Models; +using Microsoft.Extensions.DependencyInjection; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// that answers for a virtual repository from its members and for any other repository +/// from . Versions are the union of the members' (each version from the first member that has +/// it, so the registration index and the version list of a package that lives in two members show every version); a +/// single version is answered by the first readable member that has it, asking a remote member's upstream when it must. +/// +public sealed class VirtualPackageService : IPackageService +{ + private readonly PackageService _inner; + private readonly VirtualRepositoryReader _reader; + + public VirtualPackageService(PackageService inner, VirtualRepositoryReader reader) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + } + + /// + public async Task> FindPackageVersionsAsync(string id, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.FindPackageVersionsAsync(id, cancellationToken).ConfigureAwait(false); + + var all = await _reader.AllAsync( + id, + sp => sp.GetRequiredService().FindPackageVersionsAsync(id, cancellationToken), + cancellationToken).ConfigureAwait(false); + + return all.SelectMany(r => r.Value).Distinct().ToList(); + } + + /// + public async Task> FindPackagesAsync(string id, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.FindPackagesAsync(id, cancellationToken).ConfigureAwait(false); + + var all = await _reader.AllAsync( + id, + sp => sp.GetRequiredService().FindPackagesAsync(id, cancellationToken), + cancellationToken).ConfigureAwait(false); + + return VirtualRepositoryReader.Union(all.Select(r => r.Value)); + } + + /// + public async Task FindPackageOrNullAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.FindPackageOrNullAsync(id, version, cancellationToken).ConfigureAwait(false); + + return await _reader.FirstAsync( + id, + sp => sp.GetRequiredService().FindPackageOrNullAsync(id, version, cancellationToken), + cancellationToken).ConfigureAwait(false); + } + + /// + public async Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.ExistsAsync(id, version, cancellationToken).ConfigureAwait(false); + + var found = await _reader.FirstAsync( + id, + async sp => await sp.GetRequiredService().ExistsAsync(id, version, cancellationToken).ConfigureAwait(false) ? true : null, + cancellationToken).ConfigureAwait(false); + + return found != null; + } + + /// + public async Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) + { + await _inner.AddDownloadAsync(packageId, version, cancellationToken).ConfigureAwait(false); + return; + } + + // The member that holds the version counts the download; nothing is fetched to find it. + foreach (var member in await _reader.ReadableMembersAsync(packageId, cancellationToken).ConfigureAwait(false)) + { + var held = await _reader.InMemberAsync( + member, + sp => sp.GetRequiredService().ExistsAsync(packageId, version, cancellationToken)).ConfigureAwait(false); + if (!held) continue; + + await _reader.InMemberAsync( + member, + async sp => + { + await sp.GetRequiredService().AddDownloadAsync(packageId, version, cancellationToken).ConfigureAwait(false); + return true; + }).ConfigureAwait(false); + + return; + } + } + + /// + public async Task OpenUncachedAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.OpenUncachedAsync(id, version, cancellationToken).ConfigureAwait(false); + + foreach (var member in await _reader.ReadableMembersAsync(id, cancellationToken).ConfigureAwait(false)) + { + var stream = await _reader.InMemberAsync( + member, + async sp => + { + var packages = sp.GetRequiredService(); + if (id == null || !await packages.ExistsAsync(id, version, cancellationToken).ConfigureAwait(false)) return (found: false, stream: (Stream?)null); + + return (found: true, stream: await packages.OpenUncachedAsync(id, version, cancellationToken).ConfigureAwait(false)); + }).ConfigureAwait(false); + + // The first member that has the version answers, even when it stores the package and so streams nothing. + if (stream.found) return stream.stream; + } + + return null; + } +} + +/// +/// for a virtual repository: downloads, nuspec, readme and icon come from the first +/// readable member that has the version (its own content service, so a remote member fetches and caches as it does when +/// read directly); the version list is the union of the members'. +/// +public sealed class VirtualPackageContentService : IPackageContentService +{ + private readonly DefaultPackageContentService _inner; + private readonly VirtualRepositoryReader _reader; + + public VirtualPackageContentService(DefaultPackageContentService inner, VirtualRepositoryReader reader) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + } + + /// + public async Task GetPackageVersionsOrNullAsync(string packageId, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.GetPackageVersionsOrNullAsync(packageId, cancellationToken).ConfigureAwait(false); + + var all = await _reader.AllAsync( + packageId, + sp => sp.GetRequiredService().FindPackageVersionsAsync(packageId, cancellationToken), + cancellationToken).ConfigureAwait(false); + + var versions = all.SelectMany(r => r.Value).Distinct().ToList(); + if (versions.Count == 0) return null; + + return new PackageVersionsResponse + { + Versions = versions.Select(v => v.ToNormalizedString().ToLowerInvariant()).ToList(), + }; + } + + /// + public Task GetPackageContentStreamOrNullAsync(string packageId, NuGetVersion packageVersion, CancellationToken cancellationToken) + => _reader.IsVirtual + ? _reader.FirstAsync(packageId, sp => sp.GetRequiredService().GetPackageContentStreamOrNullAsync(packageId, packageVersion, cancellationToken), cancellationToken) + : _inner.GetPackageContentStreamOrNullAsync(packageId, packageVersion, cancellationToken); + + /// + public Task GetPackageManifestStreamOrNullAsync(string packageId, NuGetVersion packageVersion, CancellationToken cancellationToken) + => _reader.IsVirtual + ? _reader.FirstAsync(packageId, sp => sp.GetRequiredService().GetPackageManifestStreamOrNullAsync(packageId, packageVersion, cancellationToken), cancellationToken) + : _inner.GetPackageManifestStreamOrNullAsync(packageId, packageVersion, cancellationToken); + + /// + public Task GetPackageReadmeStreamOrNullAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + => _reader.IsVirtual + ? _reader.FirstAsync(id, sp => sp.GetRequiredService().GetPackageReadmeStreamOrNullAsync(id, version, cancellationToken), cancellationToken) + : _inner.GetPackageReadmeStreamOrNullAsync(id, version, cancellationToken); + + /// + public Task GetPackageIconStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + => _reader.IsVirtual + ? _reader.FirstAsync(id, sp => sp.GetRequiredService().GetPackageIconStreamOrNullAsync(id, version, cancellationToken), cancellationToken) + : _inner.GetPackageIconStreamOrNullAsync(id, version, cancellationToken); +} + +/// +/// for a virtual repository: a PDB is served from the first readable member that +/// stores it (the request names a file and a key, not a package, so only the member-level Read applies). Saving and +/// deleting are never done through a virtual repository (a push is redirected to its deploy repository first). +/// +public sealed class VirtualSymbolStorageService : ISymbolStorageService +{ + private readonly SymbolStorageService _inner; + private readonly VirtualRepositoryReader _reader; + + public VirtualSymbolStorageService(SymbolStorageService inner, VirtualRepositoryReader reader) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + } + + /// + public Task SavePortablePdbContentAsync(string file, string key, Stream pdbStream, CancellationToken cancellationToken) + => _inner.SavePortablePdbContentAsync(file, key, pdbStream, cancellationToken); + + /// + public Task GetPortablePdbContentStreamOrNullAsync(string file, string key) + => _reader.IsVirtual + ? _reader.FirstAsync(null, sp => sp.GetRequiredService().GetPortablePdbContentStreamOrNullAsync(file, key), CancellationToken.None) + : _inner.GetPortablePdbContentStreamOrNullAsync(file, key); + + /// + public Task DeletePortablePdbContentAsync(string file, string key, CancellationToken cancellationToken) + => _inner.DeletePortablePdbContentAsync(file, key, cancellationToken); +} diff --git a/src/BaGet.Core/Repositories/Virtual/VirtualRepositoryAdministration.cs b/src/BaGet.Core/Repositories/Virtual/VirtualRepositoryAdministration.cs new file mode 100644 index 000000000..6848a1c82 --- /dev/null +++ b/src/BaGet.Core/Repositories/Virtual/VirtualRepositoryAdministration.cs @@ -0,0 +1,467 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// One member of a virtual repository as the administration page lists it. +/// The member's name, as stored. +/// The member repository, or null when no repository has that name any more. +public sealed record VirtualMemberDetail(string Name, RepositoryInfo? Repository) +{ + /// Whether a repository of that name exists. + public bool Exists => Repository != null; +} + +/// A virtual repository as the administration pages edit it. +/// The virtual repository. +/// Its direct members in resolution order. +/// The name of the member that receives deployments, if any. +/// The local repository a push really goes to (the deploy repository, or where a virtual deploy repository deploys), or null. +/// The local and remote repositories that answer, in order, nested virtual members expanded. +public sealed record VirtualRepositoryDetail( + RepositoryInfo Repository, + IReadOnlyList Members, + string? DeployRepository, + RepositoryInfo? DeployTarget, + IReadOnlyList EffectiveMembers); + +/// What asking one member about a package version found. +public enum ResolutionOutcome +{ + /// The member stores the version. + Stored, + + /// A remote member that does not store it yet but whose upstream has it (it would be fetched). + WouldFetch, + + /// The member does not have it. + NotFound, + + /// A remote member whose upstream could not be asked. + Unavailable, + + /// Not asked: an earlier member already answers (a member's upstream is not contacted then). + NotAsked, + + /// The member does not store it and its upstream is in offline mode, so a request would not ask it. + Offline, +} + +/// One member's part in . +/// The member asked. +/// What it found. +public sealed record ResolutionStep(RepositoryInfo Member, ResolutionOutcome Outcome); + +/// Where a package version would come from, member by member. +/// The package id asked about (group:artifact for Maven). +/// The version asked about, as written for the format (a NuGet or npm version in its normalized form; a Maven version as typed). +/// The effective members in resolution order and what each found. +/// The member that answers (the first that stores the version or whose upstream has it), or null when none. +public sealed record ResolutionPreview(string PackageId, string Version, IReadOnlyList Steps, RepositoryInfo? Answers); + +/// +/// Creates, edits and explains virtual repositories. What the administration pages use; writes go through the database +/// context, so the refuses them while it is closed. The access model is not consulted: +/// the pages are administrators' tools (read access to a virtual repository's members is judged per request, see +/// ). +/// +public interface IVirtualRepositoryAdministration +{ + /// A virtual repository by exact name, or null when there is none (or it is not virtual). + Task FindAsync(string? name, CancellationToken cancellationToken); + + /// + /// The repositories of the virtual repository's format that can be added to (every other + /// repository whose own members do not lead back to it), ordered by name. For a repository not created yet pass null and its + /// . + /// + Task> CandidatesAsync(string? name, CancellationToken cancellationToken, RepositoryFormat format = RepositoryFormat.NuGet); + + /// The virtual repositories that list directly, ordered by name. + Task> ReferencedByAsync(string memberName, CancellationToken cancellationToken); + + /// + /// Creates a virtual repository of (its members must be of that format: NuGet or npm). Audited. + /// + /// The name or the settings are invalid; the message lists the problems. + /// The name is taken. + /// The configuration holds the default repository only. + Task CreateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null, bool anonymousRead = true, RepositoryFormat format = RepositoryFormat.NuGet); + + /// + /// Replaces the members and the deploy repository. Refused (nothing changes) for an unknown, remote-only or + /// other-format member, for a deploy repository that is not a member or does not end in a local repository, and for a + /// change that would close a cycle between virtual repositories. Audited. + /// + /// No such virtual repository. + /// The settings are invalid; the message lists the problems. + Task UpdateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null); + + /// + /// Where would come from: each effective member is asked in + /// order whether it stores the version (a remote member that does not is asked whether its upstream has it, unless an + /// earlier member already answers). Stores nothing and fetches nothing. For an npm repository the package id is the package + /// name and the version is read as a full semantic version (its full string form). + /// + /// No such virtual repository. + Task PreviewAsync(string name, string packageId, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Like for a version written as text: a Maven version + /// (5.3.20.RELEASE, 1.0-SNAPSHOT) is not always a NuGet version, and the package id of a Maven repository is + /// group:artifact. A NuGet or npm repository still needs a version that parses. + /// + /// No such virtual repository. + /// The version or the package id is not valid for the repository's format. + Task PreviewAsync(string name, string packageId, string version, CancellationToken cancellationToken); +} + +/// +/// over the relational database. +/// +public sealed class VirtualRepositoryAdministration : IVirtualRepositoryAdministration +{ + private readonly IContext _context; + private readonly IRepositoryService _repositories; + private readonly IServiceScopeFactory _scopes; + private readonly MaintenanceGate? _gate; + private readonly SystemTime? _time; + private readonly FormatRegistry _formats; + + public VirtualRepositoryAdministration( + IContext context, + IRepositoryService repositories, + IServiceScopeFactory scopes, + MaintenanceGate? gate = null, + SystemTime? time = null, + FormatRegistry? formats = null) + { + _formats = formats ?? FormatRegistry.Default; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _gate = gate; + _time = time; + } + + private DateTime Now => _time?.UtcNow ?? DateTime.UtcNow; + + /// + public async Task FindAsync(string? name, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(name) || _context.Repositories == null) return null; + + var rows = await LoadAsync(cancellationToken).ConfigureAwait(false); + if (!rows.TryGetValue(name!, out var row) || row.Kind != RepositoryKind.Virtual) return null; + + var settings = VirtualSettingsCodec.Deserialize(row.Settings); + var effective = new List(); + VirtualRepositories.Flatten(name!, rows, new HashSet(StringComparer.Ordinal), effective, new HashSet(), depth: 0); + + return new VirtualRepositoryDetail( + row.ToInfo(), + settings.Members.Select(m => new VirtualMemberDetail(m, rows.TryGetValue(m, out var member) ? member.ToInfo() : null)).ToList(), + settings.DeployRepository, + VirtualRepositories.ResolveDeploy(name!, rows), + effective); + } + + /// + public async Task> CandidatesAsync(string? name, CancellationToken cancellationToken, RepositoryFormat format = RepositoryFormat.NuGet) + { + if (_context.Repositories == null) return Array.Empty(); + + var rows = await LoadAsync(cancellationToken).ConfigureAwait(false); + if (name != null && rows.TryGetValue(name, out var self)) format = self.Format; + + return rows.Values + .Where(r => r.Format == format && r.Name != name && !(name != null && r.Kind == RepositoryKind.Virtual && Reaches(r.Name!, name, rows))) + .OrderBy(r => r.Name, StringComparer.Ordinal) + .Select(r => r.ToInfo()) + .ToList(); + } + + /// + public async Task> ReferencedByAsync(string memberName, CancellationToken cancellationToken) + { + if (_context.Repositories == null) return Array.Empty(); + + var rows = await LoadAsync(cancellationToken).ConfigureAwait(false); + + return rows.Values + .Where(r => r.Kind == RepositoryKind.Virtual && VirtualSettingsCodec.Deserialize(r.Settings).Members.Contains(memberName)) + .Select(r => r.Name!) + .OrderBy(n => n, StringComparer.Ordinal) + .ToList(); + } + + /// + public async Task CreateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null, bool anonymousRead = true, RepositoryFormat format = RepositoryFormat.NuGet) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + if (!RepositoryNames.IsValid(name, out var error)) throw new ArgumentException(error, nameof(name)); + if (_formats.Find(format) is not { SupportsVirtual: true }) + { + throw new NotSupportedException($"A virtual {format} repository is not available on this server."); + } + + _gate?.ThrowIfClosed(); + + if (!_repositories.SupportsMultipleRepositories) + { + throw new NotSupportedException( + "Only the 'default' repository is available with this configuration; use a relational database (SQLite, SQL Server, PostgreSQL or MySQL) and a search type other than AzureSearch (whose index is not repository-aware) to create more."); + } + + await _repositories.EnsureDefaultAsync(cancellationToken).ConfigureAwait(false); + + var rows = await LoadAsync(cancellationToken).ConfigureAwait(false); + if (rows.ContainsKey(name)) throw new RepositoryExistsException(name); + + Validate(name, format, settings, rows); + + var row = new Repository + { + Name = name, + Format = format, + Kind = RepositoryKind.Virtual, + Settings = VirtualSettingsCodec.Serialize(settings), + AnonymousRead = anonymousRead, + Created = Now, + }; + _context.Repositories!.Add(row); + AccessAdministration.Audit(_context, Now, actor, "repository.virtual.create", name, Describe(settings)); + + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException e) when (_context.IsUniqueConstraintViolationException(e)) + { + throw new RepositoryExistsException(name); + } + + return row.ToInfo(); + } + + /// + public async Task UpdateAsync(string name, VirtualRepositorySettings settings, CancellationToken cancellationToken, string? actor = null) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + _gate?.ThrowIfClosed(); + + var row = _context.Repositories == null + ? null + : await _context.Repositories.FirstOrDefaultAsync(r => r.Name == name && r.Kind == RepositoryKind.Virtual, cancellationToken).ConfigureAwait(false); + if (row == null) throw new KeyNotFoundException($"There is no virtual repository named '{name}'."); + + var rows = await LoadAsync(cancellationToken).ConfigureAwait(false); + Validate(name, row.Format, settings, rows); + + row.Settings = VirtualSettingsCodec.Serialize(settings); + AccessAdministration.Audit(_context, Now, actor, "repository.virtual.update", name, Describe(settings)); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public Task PreviewAsync(string name, string packageId, NuGetVersion version, CancellationToken cancellationToken) + => PreviewAsync(name, packageId, version?.ToFullString() ?? throw new ArgumentNullException(nameof(version)), cancellationToken); + + /// + public async Task PreviewAsync(string name, string packageId, string version, CancellationToken cancellationToken) + { + if (version == null) throw new ArgumentNullException(nameof(version)); + + var detail = await FindAsync(name, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"There is no virtual repository named '{name}'."); + + // NuGet and npm versions are semantic versions; a Maven version is any version folder name; a Docker "version" is a tag or a digest. + NuGetVersion? parsed = null; + string shown = version; + string group = string.Empty, artifact = string.Empty; + if (detail.Repository.Format == RepositoryFormat.Docker) + { + packageId = packageId.Trim().ToLowerInvariant(); + if (!OciNames.IsValidImage(packageId)) throw new ArgumentException($"{packageId} is not an image name: lower-case letters, digits, '.', '_', '-' in components separated by '/'.", nameof(packageId)); + if (!(OciNames.IsValidTag(version) || OciNames.IsValidDigest(version))) throw new ArgumentException($"{version} is not a tag or a sha256 digest.", nameof(version)); + } + else if (detail.Repository.Format == RepositoryFormat.Maven) + { + if (!MavenNames.TryParseArtifactName(packageId, out group, out artifact)) throw new ArgumentException($"{packageId} is not an artifact: write it as group:artifact.", nameof(packageId)); + if (!MavenNames.IsValidVersion(version)) throw new ArgumentException($"{version} is not a valid version.", nameof(version)); + } + else + { + if (!NuGetVersion.TryParse(version, out parsed)) throw new ArgumentException($"{version} is not a valid version.", nameof(version)); + + shown = parsed.ToNormalizedString(); + } + + var steps = new List(); + RepositoryInfo? answers = null; + + foreach (var member in detail.EffectiveMembers) + { + // Once a member answers the later ones are not asked: a real request stops there, and probing an upstream + // is a request to it. + var outcome = ResolutionOutcome.NotAsked; + if (answers != null) + { + // Only the stored copy is looked at (cheap and local): it shows a member the answering one shadows. + using var scope = _scopes.CreateRepositoryScope(member); + if (await StoredAsync(scope.ServiceProvider, detail.Repository.Format, packageId, parsed, group, artifact, version, cancellationToken).ConfigureAwait(false)) + { + outcome = ResolutionOutcome.Stored; + } + } + else + { + // The member's own package service decides, as it does for a real request: its stored copy first, then + // its upstream (any member can have one: a remote repository, or the default repository's mirror). + using var scope = _scopes.CreateRepositoryScope(member); + try + { + outcome = detail.Repository.Format switch + { + RepositoryFormat.Npm => await scope.ServiceProvider.GetRequiredService() + .ProbeAsync(packageId.ToLowerInvariant(), parsed!.ToFullString(), cancellationToken).ConfigureAwait(false), + RepositoryFormat.Maven => await scope.ServiceProvider.GetRequiredService() + .ProbeAsync(group, artifact, version, cancellationToken).ConfigureAwait(false), + RepositoryFormat.Docker => await scope.ServiceProvider.GetRequiredService() + .ProbeAsync(packageId, version, cancellationToken).ConfigureAwait(false), + _ => await scope.ServiceProvider.GetRequiredService() + .ProbeAsync(packageId, parsed!, cancellationToken).ConfigureAwait(false), + }; + } + catch (Exception e) when (e is not OperationCanceledException) + { + outcome = ResolutionOutcome.Unavailable; + } + } + + if (answers == null && outcome is ResolutionOutcome.Stored or ResolutionOutcome.WouldFetch) answers = member; + steps.Add(new ResolutionStep(member, outcome)); + } + + return new ResolutionPreview(packageId, shown, steps, answers); + } + + // Whether the member's own storage holds the version (cheap and local). + private static async Task StoredAsync( + IServiceProvider services, + RepositoryFormat format, + string packageId, + NuGetVersion? parsed, + string group, + string artifact, + string version, + CancellationToken cancellationToken) + { + if (format == RepositoryFormat.Docker) + { + // A Docker member's stored copy only: the probe of a remote member would ask its upstream, which a shadowed member must not. + return await services.GetRequiredService().ProbeAsync(packageId, version, cancellationToken).ConfigureAwait(false) == ResolutionOutcome.Stored; + } + + if (format == RepositoryFormat.Maven) + { + // A Maven member's stored copy only: the probe of a remote member would ask its upstream, which a shadowed member must not. + return await services.GetRequiredService().HasVersionAsync(group, artifact, version, cancellationToken).ConfigureAwait(false); + } + + if (format != RepositoryFormat.Npm) + { + return await services.GetRequiredService().ExistsAsync(packageId, parsed!, cancellationToken).ConfigureAwait(false); + } + + // An npm member's stored copy only: the probe of a remote member would ask its upstream, which a shadowed member must not. + return await services.GetRequiredService() + .ProbeAsync(packageId.ToLowerInvariant(), parsed!.ToFullString(), cancellationToken).ConfigureAwait(false) == ResolutionOutcome.Stored; + } + + private static object Describe(VirtualRepositorySettings settings) + => new { members = settings.Members, deploy = settings.DeployRepository }; + + private async Task> LoadAsync(CancellationToken cancellationToken) + { + var rows = await _context.Repositories!.AsNoTracking().ToListAsync(cancellationToken).ConfigureAwait(false); + + return rows.Where(r => r.Name != null).ToDictionary(r => r.Name!, StringComparer.Ordinal); + } + + // Whether the virtual repository 'from' lists 'target' directly or through nested virtual members. + private static bool Reaches(string from, string target, IReadOnlyDictionary rows) + { + var seen = new HashSet(StringComparer.Ordinal); + var pending = new Stack(); + pending.Push(from); + while (pending.Count > 0) + { + var current = pending.Pop(); + if (!seen.Add(current) || !rows.TryGetValue(current, out var row) || row.Kind != RepositoryKind.Virtual) continue; + + foreach (var member in VirtualSettingsCodec.Deserialize(row.Settings).Members) + { + if (member == target) return true; + pending.Push(member); + } + } + + return false; + } + + // Throws ArgumentException listing every problem of 'settings' as the settings of the virtual repository 'name'. + private static void Validate(string name, RepositoryFormat format, VirtualRepositorySettings settings, Dictionary rows) + { + var problems = settings.ValidateShape().ToList(); + + foreach (var member in settings.Members) + { + if (member == name) + { + problems.Add("A virtual repository cannot contain itself."); + } + else if (!rows.TryGetValue(member, out var row)) + { + problems.Add($"There is no repository named '{member}'."); + } + else if (row.Format != format) + { + problems.Add($"'{member}' is not a {format} repository."); + } + else if (row.Kind == RepositoryKind.Virtual && Reaches(member, name, rows)) + { + problems.Add($"Adding '{member}' would make '{name}' contain itself through '{member}'."); + } + } + + if (problems.Count == 0 && !string.IsNullOrEmpty(settings.DeployRepository)) + { + // The deploy repository is judged in the graph with the new members in place of the stored ones. + var proposed = new Dictionary(rows, StringComparer.Ordinal) + { + [name] = new() + { + Key = rows.TryGetValue(name, out var existing) ? existing.Key : 0, + Name = name, + Format = format, + Kind = RepositoryKind.Virtual, + Settings = VirtualSettingsCodec.Serialize(settings), + }, + }; + + if (VirtualRepositories.ResolveDeploy(name, proposed) == null) + { + problems.Add($"The deploy repository '{settings.DeployRepository}' must be a local repository (or a virtual one that deploys to a local repository); a remote repository takes no deployments."); + } + } + + if (problems.Count > 0) throw new ArgumentException(string.Join(" ", problems), nameof(settings)); + } +} diff --git a/src/BaGet.Core/Repositories/Virtual/VirtualRepositoryReader.cs b/src/BaGet.Core/Repositories/Virtual/VirtualRepositoryReader.cs new file mode 100644 index 000000000..bace5ca34 --- /dev/null +++ b/src/BaGet.Core/Repositories/Virtual/VirtualRepositoryReader.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// One member's answer to a question asked of every member of a virtual repository. +/// The answer. +/// The member that answered. +/// What it answered. +public sealed record MemberResult(RepositoryInfo Member, T Value); + +/// +/// The engine behind reading a repository. It finds the members the caller may +/// read, in resolution order, and runs a question in each one's own DI scope (so the member's database filter, storage +/// path, upstream and access checks apply exactly as they do when the member is read directly). A member that fails +/// (its upstream is down) is logged and skipped, so the next member can answer; cancellation and a closed maintenance +/// gate are never swallowed. URLs in the answers still point into the virtual repository: they are generated from the +/// request, not from the member's scope. +/// +public sealed class VirtualRepositoryReader +{ + private readonly IRepositoryContext _repository; + private readonly IVirtualRepositories _virtuals; + private readonly IAccessEvaluator _evaluator; + private readonly IRequestCaller _caller; + private readonly IServiceScopeFactory _scopes; + private readonly ILogger _logger; + + public VirtualRepositoryReader( + IRepositoryContext repository, + IVirtualRepositories virtuals, + IAccessEvaluator evaluator, + IRequestCaller caller, + IServiceScopeFactory scopes, + ILogger logger) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator)); + _caller = caller ?? throw new ArgumentNullException(nameof(caller)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// Whether the request's repository is a virtual one (otherwise nothing here applies). + public bool IsVirtual => _repository.Current.Kind == RepositoryKind.Virtual; + + /// + /// The members of the request's virtual repository the caller may read, in resolution order. With + /// the Read grants' package patterns apply too. + /// + public async Task> ReadableMembersAsync(string? packageId, CancellationToken cancellationToken) + { + if (!IsVirtual) return new[] { _repository.Current }; + + var members = await _virtuals.EffectiveMembersAsync(_repository.Current, cancellationToken).ConfigureAwait(false); + var principal = await _caller.GetAsync(cancellationToken).ConfigureAwait(false); + var readable = new List(); + + foreach (var member in members) + { + if (await _evaluator.IsAllowedAsync(principal, member, packageId: null, AccessAction.Read, cancellationToken).ConfigureAwait(false) + && (packageId == null + || await _evaluator.IsAllowedAsync(principal, member, packageId, AccessAction.Read, cancellationToken).ConfigureAwait(false))) + { + readable.Add(member); + } + } + + return readable; + } + + /// + /// Whether the caller may read in (the repository, and the package when + /// given): what a merged listing asks per hit, since the members' own listings do not know the caller. + /// + public async Task CanReadInMemberAsync(RepositoryInfo member, string? packageId, CancellationToken cancellationToken) + { + var principal = await _caller.GetAsync(cancellationToken).ConfigureAwait(false); + + return await _evaluator.IsAllowedAsync(principal, member, packageId: null, AccessAction.Read, cancellationToken).ConfigureAwait(false) + && (packageId == null + || await _evaluator.IsAllowedAsync(principal, member, packageId, AccessAction.Read, cancellationToken).ConfigureAwait(false)); + } + + /// Runs in a scope pinned to . + public async Task InMemberAsync(RepositoryInfo member, Func> action) + { + using var scope = _scopes.CreateRepositoryScope(member); + + return await action(scope.ServiceProvider).ConfigureAwait(false); + } + + /// + /// Asks the readable members in order and returns the first answer that is not null; null when none has one. + /// + public async Task FirstAsync(string? packageId, Func> action, CancellationToken cancellationToken) + where T : class + { + foreach (var member in await ReadableMembersAsync(packageId, cancellationToken).ConfigureAwait(false)) + { + var answer = await TryAsync(member, action).ConfigureAwait(false); + if (answer != null) return answer; + } + + return null; + } + + /// Asks every readable member, in order; a member that fails contributes nothing. + public async Task>> AllAsync(string? packageId, Func> action, CancellationToken cancellationToken) + where T : class + { + var results = new List>(); + foreach (var member in await ReadableMembersAsync(packageId, cancellationToken).ConfigureAwait(false)) + { + var answer = await TryAsync(member, async sp => (T?)await action(sp).ConfigureAwait(false)).ConfigureAwait(false); + if (answer != null) results.Add(new MemberResult(member, answer)); + } + + return results; + } + + private async Task TryAsync(RepositoryInfo member, Func> action) where T : class + { + try + { + return await InMemberAsync(member, action).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + _logger.LogWarning(e, "Member {Member} of virtual repository {Virtual} failed; the next member answers instead", member.Name, _repository.Current.Name); + + return null; + } + } + + /// + /// The versions of a package stored in the readable members (no upstream is asked), each version once, from the + /// first member that has it. + /// + public async Task> FindPackagesAsync(string? id, bool includeUnlisted, CancellationToken cancellationToken) + { + var all = await AllAsync( + id, + sp => sp.GetRequiredService().FindAsync(id, includeUnlisted, cancellationToken), + cancellationToken).ConfigureAwait(false); + + return Union(all.Select(r => r.Value)); + } + + /// One version stored in the first readable member that has it (no upstream is asked). + public Task FindPackageAsync(string? id, NuGetVersion version, bool includeUnlisted, CancellationToken cancellationToken) + => FirstAsync( + id, + sp => sp.GetRequiredService().FindOrNullAsync(id, version, includeUnlisted, cancellationToken), + cancellationToken); + + /// The vulnerabilities recorded in the readable members, each advisory once. + public async Task> GetAllVulnerabilitiesAsync(CancellationToken cancellationToken) + { + var all = await AllAsync( + packageId: null, + sp => sp.GetRequiredService().GetAllVulnerabilitiesAsync(cancellationToken), + cancellationToken).ConfigureAwait(false); + + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var result = new List(); + foreach (var vulnerability in all.SelectMany(r => r.Value)) + { + var key = $"{vulnerability.Package?.Id}|{vulnerability.Package?.NormalizedVersionString}|{vulnerability.AdvisoryUrl}|{vulnerability.Severity}"; + if (seen.Add(key)) result.Add(vulnerability); + } + + return result; + } + + /// Package lists from several members merged by version: the earliest list wins a version. + internal static IReadOnlyList Union(IEnumerable> lists) + { + var byVersion = new Dictionary(); + foreach (var package in lists.SelectMany(l => l)) + { + byVersion.TryAdd(package.Version, package); + } + + return byVersion.Values.ToList(); + } +} diff --git a/src/BaGet.Core/Repositories/Virtual/VirtualRepositorySettings.cs b/src/BaGet.Core/Repositories/Virtual/VirtualRepositorySettings.cs new file mode 100644 index 000000000..60954591c --- /dev/null +++ b/src/BaGet.Core/Repositories/Virtual/VirtualRepositorySettings.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace BaGet.Core; + +/// +/// What a repository is made of: kept as JSON in . +/// Members are named (names never change), so a member is found again whatever its key. +/// +public sealed class VirtualRepositorySettings +{ + /// Most members one virtual repository may list (each one costs a lookup per request). + public const int MaxMembers = 50; + + /// + /// The member repositories in resolution order: the first one that has a package version answers for it. A member + /// may be a local, a remote or another virtual repository (flattened in place, cycles refused). + /// + [JsonPropertyName("members")] + public List Members { get; set; } = new(); + + /// + /// The member that receives what is pushed to the virtual repository (a local repository, or a virtual one that + /// itself resolves to a local one). Null: the virtual repository takes no uploads. + /// + [JsonPropertyName("deployRepository")] + public string? DeployRepository { get; set; } + + /// A copy that can be changed without affecting this one. + public VirtualRepositorySettings Clone() => new() { Members = Members.ToList(), DeployRepository = DeployRepository }; + + /// + /// The problems that need no database: the member names, duplicates, the member count and a deploy repository + /// that is not a member. + /// + public IReadOnlyList ValidateShape() + { + var problems = new List(); + var seen = new HashSet(StringComparer.Ordinal); + + if (Members.Count > MaxMembers) problems.Add($"A virtual repository has at most {MaxMembers} members."); + + foreach (var member in Members) + { + if (!RepositoryNames.IsValid(member, out _)) + { + problems.Add($"'{member}' is not a valid repository name."); + } + else if (!seen.Add(member)) + { + problems.Add($"'{member}' is listed twice."); + } + } + + if (!string.IsNullOrEmpty(DeployRepository) && !seen.Contains(DeployRepository!)) + { + problems.Add($"The deploy repository '{DeployRepository}' must be one of the members."); + } + + return problems; + } +} + +/// +/// Reads and writes a virtual repository's JSON. +/// +public static class VirtualSettingsCodec +{ + private static readonly JsonSerializerOptions Options = new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + /// The JSON stored for . + public static string Serialize(VirtualRepositorySettings settings) + => JsonSerializer.Serialize(settings ?? throw new ArgumentNullException(nameof(settings)), Options); + + /// The settings in ; an empty or unreadable value reads as no members. + public static VirtualRepositorySettings Deserialize(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return new VirtualRepositorySettings(); + + try + { + var settings = JsonSerializer.Deserialize(json!, Options) ?? new VirtualRepositorySettings(); + settings.Members ??= new List(); + settings.Members = settings.Members.Where(m => !string.IsNullOrEmpty(m)).ToList(); + + return settings; + } + catch (JsonException) + { + return new VirtualRepositorySettings(); + } + } +} diff --git a/src/BaGet.Core/Retention/ArtifactUsageRecorder.cs b/src/BaGet.Core/Retention/ArtifactUsageRecorder.cs new file mode 100644 index 000000000..dc395b675 --- /dev/null +++ b/src/BaGet.Core/Retention/ArtifactUsageRecorder.cs @@ -0,0 +1,222 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// Remembers when each version was last downloaded, for the retention rules "unused for N days" and the remote cache limit. A download +/// only touches an in-memory map (no database write on the download path); (the retention worker, every +/// minute, and the engine before it plans) writes the newest time of each version in batches. A restart loses at most the last minute, +/// and a closed keeps the entries until it opens. Names and versions are compared case-insensitively. +/// +public sealed class ArtifactUsageRecorder +{ + /// The most distinct versions remembered between two flushes; further new ones are dropped (known ones keep updating). + public const int MaxPending = 50_000; + + private const int Chunk = 400; + + private readonly ConcurrentDictionary<(int Repository, string Name, string Version), DateTime> _pending = new(); + private readonly SemaphoreSlim _flushing = new(1, 1); + private readonly SystemTime _time; + private readonly ILogger? _logger; + + public ArtifactUsageRecorder(SystemTime time, ILogger? logger = null) + { + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger; + } + + /// Versions waiting to be written. + public int Pending => _pending.Count; + + /// The key of a version in the map and in the database: lower case, so the engines' collations agree. + internal static string Normalize(string value) => value.ToLowerInvariant(); + + /// Notes that of repository was downloaded now. + public void Touch(int repositoryKey, string? name, string? version) + { + if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(version)) return; + if (name.Length > RetentionLimits.MaxNameLength || version.Length > RetentionLimits.MaxVersionLength) return; + + var key = (repositoryKey, Normalize(name), Normalize(version)); + var now = _time.UtcNow; + if (_pending.Count >= MaxPending && !_pending.ContainsKey(key)) return; + + _pending.AddOrUpdate(key, now, (_, old) => old > now ? old : now); + } + + /// + /// Writes the pending times. Entries that cannot be written (the gate is closed, the database is unreachable) stay for the next + /// flush. Never throws except for cancellation. + /// + /// How many versions were written. + public async Task FlushAsync(IServiceScopeFactory scopes, CancellationToken cancellationToken) + { + if (scopes == null) throw new ArgumentNullException(nameof(scopes)); + if (_pending.IsEmpty) return 0; + + await _flushing.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var snapshot = _pending.ToArray(); + if (snapshot.Length == 0) return 0; + + using var scope = scopes.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); + if (context is NullContext) + { + _pending.Clear(); + + return 0; + } + + var written = 0; + foreach (var group in snapshot.GroupBy(e => e.Key.Repository)) + { + foreach (var batch in group.Chunk(Chunk)) + { + try + { + await WriteAsync(context, group.Key, batch, cancellationToken).ConfigureAwait(false); + foreach (var entry in batch) ((ICollection>)_pending).Remove(entry); + written += batch.Length; + } + catch (OperationCanceledException) + { + throw; + } + catch (MaintenanceException) + { + return written; + } + catch (Exception e) + { + context = scope.ServiceProvider.GetRequiredService(); + + // A repository that was deleted meanwhile (RepositoryKey is a foreign key): its times belong to nothing, drop them. + if (!await RepositoryExistsAsync(context, group.Key, cancellationToken).ConfigureAwait(false)) + { + foreach (var entry in group) ((ICollection>)_pending).Remove(entry); + break; + } + + // A race with another node: keep the entries, try again. + _logger?.LogWarning(e, "Could not record download times for repository {Repository}", group.Key); + } + } + } + + return written; + } + finally + { + _flushing.Release(); + } + } + + // False only when the database says so; a failing lookup counts as "exists" (keep the entries). + private static async Task RepositoryExistsAsync(IContext context, int repositoryKey, CancellationToken cancellationToken) + { + try + { + return await context.Repositories!.AsNoTracking().AnyAsync(r => r.Key == repositoryKey, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return true; + } + } + + private static async Task WriteAsync(IContext context, int repositoryKey, KeyValuePair<(int Repository, string Name, string Version), DateTime>[] batch, CancellationToken cancellationToken) + { + var names = batch.Select(e => e.Key.Name).Distinct().ToList(); + var rows = await context.ArtifactUsages!.IgnoreQueryFilters() + .Where(u => u.RepositoryKey == repositoryKey && names.Contains(u.Name!)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + var existing = rows.ToDictionary(r => (r.Name!, r.Version!), StringTupleComparer.Instance); + + foreach (var entry in batch) + { + if (existing.TryGetValue((entry.Key.Name, entry.Key.Version), out var row)) + { + if (entry.Value > row.LastUsed) row.LastUsed = entry.Value; + } + else + { + context.ArtifactUsages!.Add(new ArtifactUsage { RepositoryKey = repositoryKey, Name = entry.Key.Name, Version = entry.Key.Version, LastUsed = entry.Value }); + } + } + + try + { + await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + // A failed save must not leave rejected rows tracked for the next batch. + if (context is Microsoft.EntityFrameworkCore.DbContext db) db.ChangeTracker.Clear(); + } + } + + private sealed class StringTupleComparer : IEqualityComparer<(string, string)> + { + public static readonly StringTupleComparer Instance = new(); + + public bool Equals((string, string) x, (string, string) y) + => string.Equals(x.Item1, y.Item1, StringComparison.OrdinalIgnoreCase) && string.Equals(x.Item2, y.Item2, StringComparison.OrdinalIgnoreCase); + + public int GetHashCode((string, string) value) + => HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(value.Item1), StringComparer.OrdinalIgnoreCase.GetHashCode(value.Item2)); + } +} + +/// The recorded download times of the repository of a context (its query filter applies), keyed by name and version. +public sealed class ArtifactUsageMap +{ + private readonly Dictionary<(string, string), DateTime> _times; + + private ArtifactUsageMap(Dictionary<(string, string), DateTime> times) + { + _times = times; + } + + /// The map of every version of the context's repository. + public static async Task LoadAsync(IContext context, CancellationToken cancellationToken) + { + var rows = await context.ArtifactUsages!.AsNoTracking().Select(u => new { u.Name, u.Version, u.LastUsed }).ToListAsync(cancellationToken).ConfigureAwait(false); + var times = new Dictionary<(string, string), DateTime>(); + foreach (var row in rows) + { + var key = (ArtifactUsageRecorder.Normalize(row.Name!), ArtifactUsageRecorder.Normalize(row.Version!)); + var value = DateTime.SpecifyKind(row.LastUsed, DateTimeKind.Utc); + if (!times.TryGetValue(key, out var old) || value > old) times[key] = value; + } + + return new ArtifactUsageMap(times); + } + + /// The last download of the version, or null. + public DateTime? Get(string name, string version) + => _times.TryGetValue((ArtifactUsageRecorder.Normalize(name), ArtifactUsageRecorder.Normalize(version)), out var time) ? time : null; + + /// The later of the two (a Docker tag and the digest it points at). + public DateTime? Latest(string name, string version, string otherVersion) + { + var a = Get(name, version); + var b = Get(name, otherVersion); + + return a == null ? b : b == null ? a : (a > b ? a : b); + } +} diff --git a/src/BaGet.Core/Retention/RetentionAdministration.cs b/src/BaGet.Core/Retention/RetentionAdministration.cs new file mode 100644 index 000000000..9568a445b --- /dev/null +++ b/src/BaGet.Core/Retention/RetentionAdministration.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// A refusal the administrator can fix (invalid input, unknown repository); the message is shown on the page. +public sealed class RetentionException : AccessModelException +{ + public RetentionException(string message) + : base(message) + { + } +} + +/// What the administrator types to create or change a policy. 0 creates. +public sealed record RetentionPolicyInput( + int Key, + string? Name, + string? Repository, + string? Project, + bool Enabled, + string? NamePatterns, + int? KeepLast, + int? OlderThanDays, + int? UnusedDays, + bool PrereleaseOnly, + long? CacheLimitBytes, + int? UntaggedAfterDays, + bool CollectGarbage, + int? ScheduleHours); + +/// A policy with the name of what it applies to. +/// The policy. +/// The repository name, when it applies to one. +/// The project name, when it applies to a project. +/// How many repositories it currently applies to. +public sealed record RetentionPolicyView(RetentionPolicy Policy, string? Repository, string? Project, int Targets); + +/// A legal hold with its repository's name. +public sealed record RetentionHoldView(int Key, int RepositoryKey, string Repository, string Name, string Version, string? Reason, string? CreatedBy, DateTime Created); + +/// +/// Manages retention policies and legal holds. Every change calls and is audited +/// (, in the same save as the change). Authorization is the caller's (the administrator pages). +/// +public interface IRetentionAdministration +{ + /// Every policy, by name. + Task> ListPoliciesAsync(CancellationToken cancellationToken); + + /// One policy, or null. + Task GetPolicyAsync(int key, CancellationToken cancellationToken); + + /// Creates ( 0) or changes a policy. + /// The input is not valid. + Task SavePolicyAsync(RetentionPolicyInput input, string? actor, CancellationToken cancellationToken); + + /// Deletes a policy (what it already deleted stays deleted). + Task DeletePolicyAsync(int key, string? actor, CancellationToken cancellationToken); + + /// The legal holds of one repository, or of all when is null. + Task> ListHoldsAsync(string? repository, CancellationToken cancellationToken); + + /// + /// Places a hold on an artifact ( empty: every version) of a repository. The name and version are put in + /// the format's canonical form. Placing one that exists changes nothing. + /// + /// The repository is unknown or virtual, or the name or version is not valid for its format. + Task AddHoldAsync(string repository, string name, string? version, string? reason, string? actor, CancellationToken cancellationToken); + + /// Lifts a hold. + Task RemoveHoldAsync(int holdKey, string? actor, CancellationToken cancellationToken); +} + +/// over the relational database. +public sealed class RetentionAdministration : IRetentionAdministration +{ + private readonly IContext _context; + private readonly IServiceProvider _services; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + + public RetentionAdministration(IContext context, IServiceProvider services, SystemTime time, MaintenanceGate gate) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + } + + private IContext Db => _context is NullContext ? throw new RetentionException("Retention needs a relational database.") : _context; + + /// + public async Task> ListPoliciesAsync(CancellationToken cancellationToken) + { + var policies = await Db.RetentionPolicies!.AsNoTracking().OrderBy(p => p.Name).ToListAsync(cancellationToken).ConfigureAwait(false); + + return await ViewsAsync(policies, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task GetPolicyAsync(int key, CancellationToken cancellationToken) + { + var policy = await Db.RetentionPolicies!.AsNoTracking().FirstOrDefaultAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false); + + return policy == null ? null : (await ViewsAsync(new[] { policy }, cancellationToken).ConfigureAwait(false)).Single(); + } + + private async Task> ViewsAsync(IReadOnlyList policies, CancellationToken cancellationToken) + { + var repositories = await Db.Repositories!.AsNoTracking().Select(r => new { r.Key, r.Name, r.ProjectKey, r.Kind }).ToListAsync(cancellationToken).ConfigureAwait(false); + var projects = await Db.Projects!.AsNoTracking().ToDictionaryAsync(p => p.Key, p => p.Name!, cancellationToken).ConfigureAwait(false); + + return policies.Select(p => + { + var targets = repositories.Count(r => r.Kind != RepositoryKind.Virtual + && (p.RepositoryKey != null ? r.Key == p.RepositoryKey : p.ProjectKey != null && r.ProjectKey == p.ProjectKey)); + + return new RetentionPolicyView( + p, + p.RepositoryKey is int rk ? repositories.FirstOrDefault(r => r.Key == rk)?.Name : null, + p.ProjectKey is int pk ? (projects.TryGetValue(pk, out var name) ? name : null) : null, + targets); + }).ToList(); + } + + /// + public async Task SavePolicyAsync(RetentionPolicyInput input, string? actor, CancellationToken cancellationToken) + { + if (input == null) throw new ArgumentNullException(nameof(input)); + var db = Db; + _gate.ThrowIfClosed(); + + var name = input.Name?.Trim(); + if (!AccessNames.IsValid(name, out var nameError)) throw new RetentionException(nameError ?? "The name is not valid."); + + var hasRepository = !string.IsNullOrWhiteSpace(input.Repository); + var hasProject = !string.IsNullOrWhiteSpace(input.Project); + if (hasRepository == hasProject) throw new RetentionException("Choose either one repository or one project."); + + Check(input.KeepLast, 1, 1_000_000, "Keep the newest"); + Check(input.OlderThanDays, 1, 36_500, "Older than (days)"); + Check(input.UnusedDays, 1, 36_500, "Unused for (days)"); + Check(input.UntaggedAfterDays, 0, 36_500, "Untagged for (days)"); + Check(input.ScheduleHours, 1, 8_760, "Repeat every (hours)"); + if (input.CacheLimitBytes is long cache && cache < 1) throw new RetentionException("The cache limit must be at least 1 byte."); + + var patterns = AccessPatterns.Split(input.NamePatterns); + var patternText = patterns.Length == 0 ? null : string.Join("\n", patterns); + if (patternText != null && patternText.Length > RetentionLimits.MaxPatternsLength) throw new RetentionException("The name patterns are too long."); + + if (input.KeepLast == null && input.OlderThanDays == null && input.UnusedDays == null && input.CacheLimitBytes == null + && input.UntaggedAfterDays == null && !input.CollectGarbage) + { + throw new RetentionException("Choose at least one rule."); + } + + int? repositoryKey = null; + int? projectKey = null; + if (hasRepository) + { + var repository = await db.Repositories!.AsNoTracking().FirstOrDefaultAsync(r => r.Name == input.Repository!.Trim(), cancellationToken).ConfigureAwait(false) + ?? throw new RetentionException($"There is no repository '{input.Repository!.Trim()}'."); + if (repository.Kind == RepositoryKind.Virtual) throw new RetentionException("A virtual repository stores nothing, so retention does not apply to it."); + + // A rule that can never apply to the one repository is a mistake worth refusing (a project mixes formats, so it is only noted in reports). + if ((input.UntaggedAfterDays != null || input.CollectGarbage) && repository.Format != RepositoryFormat.Docker) + { + throw new RetentionException("Untagged manifests and the garbage collection apply to Docker repositories only."); + } + + if (input.CacheLimitBytes != null && repository.Kind != RepositoryKind.Remote) throw new RetentionException("The cache limit applies to remote repositories only."); + + repositoryKey = repository.Key; + } + else + { + var project = await db.Projects!.AsNoTracking().FirstOrDefaultAsync(p => p.Name == input.Project!.Trim(), cancellationToken).ConfigureAwait(false) + ?? throw new RetentionException($"There is no project '{input.Project!.Trim()}'."); + projectKey = project.Key; + } + + // Compared in memory, case-insensitively, whatever the engine's collation. + var names = await db.RetentionPolicies!.AsNoTracking().Select(p => new { p.Key, p.Name }).ToListAsync(cancellationToken).ConfigureAwait(false); + if (names.Any(p => p.Key != input.Key && string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))) throw new RetentionException($"There is already a policy named '{name}'."); + + var now = _time.UtcNow; + RetentionPolicy row; + string action; + if (input.Key == 0) + { + row = new RetentionPolicy { Created = now, UnusedSince = now }; + db.RetentionPolicies!.Add(row); + action = "retention.policy.create"; + } + else + { + row = await db.RetentionPolicies!.FirstOrDefaultAsync(p => p.Key == input.Key, cancellationToken).ConfigureAwait(false) + ?? throw new RetentionException("The policy no longer exists."); + action = "retention.policy.update"; + } + + // A changed schedule counts from now, so enabling a stale policy does not run it at once for the time it was off. + var restartSchedule = input.Key == 0 || row.ScheduleHours != input.ScheduleHours || (!row.Enabled && input.Enabled); + + // The unused rule judges only time it watched: restart that clock when the rule is switched on or changed, or when the + // scope it looks at (repository, project, name patterns) changes, since downloads of a newly covered version were not recorded. + if (input.Key != 0 && (row.UnusedDays != input.UnusedDays || row.RepositoryKey != repositoryKey || row.ProjectKey != projectKey + || !string.Equals(row.NamePatterns ?? string.Empty, patternText ?? string.Empty, StringComparison.Ordinal))) + { + row.UnusedSince = now; + } + + row.Name = name; + row.RepositoryKey = repositoryKey; + row.ProjectKey = projectKey; + row.Enabled = input.Enabled; + row.NamePatterns = patternText; + row.KeepLast = input.KeepLast; + row.OlderThanDays = input.OlderThanDays; + row.UnusedDays = input.UnusedDays; + row.PrereleaseOnly = input.PrereleaseOnly; + row.CacheLimitBytes = input.CacheLimitBytes; + row.UntaggedAfterDays = input.UntaggedAfterDays; + row.CollectGarbage = input.CollectGarbage; + row.ScheduleHours = input.ScheduleHours; + row.Modified = now; + if (restartSchedule && row.ScheduleHours != null) row.ScheduleStart = now; + + AccessAdministration.Audit(db, now, actor, action, name, new + { + repository = input.Repository?.Trim(), + project = input.Project?.Trim(), + input.Enabled, + input.KeepLast, + input.OlderThanDays, + input.UnusedDays, + input.PrereleaseOnly, + input.CacheLimitBytes, + input.UntaggedAfterDays, + input.CollectGarbage, + input.ScheduleHours, + }); + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return row; + } + + private static void Check(int? value, int min, int max, string field) + { + if (value is int v && (v < min || v > max)) throw new RetentionException($"{field} must be between {min} and {max}."); + } + + /// + public async Task DeletePolicyAsync(int key, string? actor, CancellationToken cancellationToken) + { + var db = Db; + _gate.ThrowIfClosed(); + + var row = await db.RetentionPolicies!.FirstOrDefaultAsync(p => p.Key == key, cancellationToken).ConfigureAwait(false); + if (row == null) return false; + + db.RetentionPolicies!.Remove(row); + AccessAdministration.Audit(db, _time.UtcNow, actor, "retention.policy.delete", row.Name); + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return true; + } + + /// + public async Task> ListHoldsAsync(string? repository, CancellationToken cancellationToken) + { + var db = Db; + var query = from h in db.RetentionHolds!.IgnoreQueryFilters().AsNoTracking() + join r in db.Repositories!.AsNoTracking() on h.RepositoryKey equals r.Key + select new { h, r.Name }; + if (!string.IsNullOrWhiteSpace(repository)) + { + var name = repository.Trim(); + query = query.Where(x => x.Name == name); + } + + var rows = await query.OrderBy(x => x.Name).ThenBy(x => x.h.Name).ThenBy(x => x.h.Version).ToListAsync(cancellationToken).ConfigureAwait(false); + + return rows.Select(x => new RetentionHoldView(x.h.Key, x.h.RepositoryKey, x.Name!, x.h.Name!, x.h.Version ?? string.Empty, x.h.Reason, x.h.CreatedBy, x.h.Created)).ToList(); + } + + /// + public async Task AddHoldAsync(string repository, string name, string? version, string? reason, string? actor, CancellationToken cancellationToken) + { + var db = Db; + _gate.ThrowIfClosed(); + + var row = await db.Repositories!.AsNoTracking().FirstOrDefaultAsync(r => r.Name == (repository ?? string.Empty).Trim(), cancellationToken).ConfigureAwait(false) + ?? throw new RetentionException($"There is no repository '{repository}'."); + if (row.Kind == RepositoryKind.Virtual) throw new RetentionException("A virtual repository stores nothing, so there is nothing to hold."); + + var hooks = _services.GetFormatService(row.Format) + ?? throw new RetentionException($"The {row.Format} format has no retention support."); + var canonical = hooks.Canonical(name ?? string.Empty, version) + ?? throw new RetentionException($"'{name}' {(string.IsNullOrWhiteSpace(version) ? string.Empty : version)} is not a valid {row.Format} name or version."); + if (canonical.Name.Length > RetentionLimits.MaxNameLength) throw new RetentionException("The name is too long."); + if (canonical.Version.Length > RetentionLimits.MaxVersionLength) throw new RetentionException("The version is too long."); + + var reasonText = string.IsNullOrWhiteSpace(reason) ? null : reason.Trim(); + if (reasonText != null && reasonText.Length > RetentionLimits.MaxReasonLength) throw new RetentionException("The reason is too long."); + + // Names compare case-insensitively whatever the engine's collation, so look for a twin in memory. + var sameName = await db.RetentionHolds!.IgnoreQueryFilters().Where(h => h.RepositoryKey == row.Key).ToListAsync(cancellationToken).ConfigureAwait(false); + var twin = sameName.FirstOrDefault(h => string.Equals(h.Name, canonical.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(h.Version, canonical.Version, StringComparison.OrdinalIgnoreCase)); + if (twin != null) return twin; + + var now = _time.UtcNow; + var hold = new RetentionHold { RepositoryKey = row.Key, Name = canonical.Name, Version = canonical.Version, Reason = reasonText, CreatedBy = actor, Created = now }; + db.RetentionHolds!.Add(hold); + AccessAdministration.Audit(db, now, actor, "retention.hold.add", row.Name, new { name = canonical.Name, version = canonical.Version, reason = reasonText }); + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return hold; + } + + /// + public async Task RemoveHoldAsync(int holdKey, string? actor, CancellationToken cancellationToken) + { + var db = Db; + _gate.ThrowIfClosed(); + + var hold = await db.RetentionHolds!.IgnoreQueryFilters().FirstOrDefaultAsync(h => h.Key == holdKey, cancellationToken).ConfigureAwait(false); + if (hold == null) return false; + + var repository = await db.Repositories!.AsNoTracking().Where(r => r.Key == hold.RepositoryKey).Select(r => r.Name).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + db.RetentionHolds!.Remove(hold); + AccessAdministration.Audit(db, _time.UtcNow, actor, "retention.hold.remove", repository, new { name = hold.Name, version = hold.Version }); + await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return true; + } +} diff --git a/src/BaGet.Core/Retention/RetentionEngine.cs b/src/BaGet.Core/Retention/RetentionEngine.cs new file mode 100644 index 000000000..8247bf7a6 --- /dev/null +++ b/src/BaGet.Core/Retention/RetentionEngine.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// Runs a over its repositories. One code path computes the report and deletes: the dry run stops after +/// planning, the real run deletes exactly the planned versions (re-checking the legal holds just before each deletion, so a hold +/// placed meanwhile is honoured). Each repository is processed in its own scope pinned to it, through the format's +/// . +/// +public sealed class RetentionEngine +{ + private readonly IContext _context; + private readonly IServiceScopeFactory _scopes; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly IAdminAudit _audit; + private readonly ILogger _logger; + private readonly ArtifactUsageRecorder? _usage; + + public RetentionEngine( + IContext context, + IServiceScopeFactory scopes, + SystemTime time, + MaintenanceGate gate, + IAdminAudit audit, + ILogger logger, + ArtifactUsageRecorder? usage = null) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _audit = audit ?? throw new ArgumentNullException(nameof(audit)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _usage = usage; + } + + /// + /// The repositories applies to: its repository, or every repository of its project. Virtual repositories + /// store nothing and are left out. + /// + public async Task> TargetsAsync(RetentionPolicy policy, CancellationToken cancellationToken) + { + if (policy == null) throw new ArgumentNullException(nameof(policy)); + + var query = _context.Repositories!.AsNoTracking().Where(r => r.Kind != RepositoryKind.Virtual); + query = policy.RepositoryKey is int repository + ? query.Where(r => r.Key == repository) + : policy.ProjectKey is int project ? query.Where(r => r.ProjectKey == project) : query.Where(r => false); + + return (await query.OrderBy(r => r.Name).ToListAsync(cancellationToken).ConfigureAwait(false)).Select(r => r.ToInfo()).ToList(); + } + + /// + /// Plans the policy and, unless , deletes what it selected. + /// + /// The policy. + /// Whether to only report. + /// Who asked (the user name, or scheduler), for the audit trail. + /// A token to cancel the run. + /// There is no such policy, or a real run of a disabled one. + /// A real run while the server is read-only, or one the gate closed on; the deletions already made are audited first. + public async Task RunAsync(int policyKey, bool dryRun, string? actor, CancellationToken cancellationToken) + { + if (_context is NullContext) throw new InvalidOperationException("Retention needs a relational database."); + + var policy = await _context.RetentionPolicies!.AsNoTracking().FirstOrDefaultAsync(p => p.Key == policyKey, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException("There is no such retention policy."); + if (!dryRun) + { + if (!policy.Enabled) throw new InvalidOperationException($"Retention policy '{policy.Name}' is disabled."); + + _gate.ThrowIfClosed(); + } + + var started = _time.UtcNow; + var report = new RetentionReport { PolicyKey = policy.Key, PolicyName = policy.Name ?? string.Empty, DryRun = dryRun, Started = started }; + + // Downloads recorded in memory so far count for the "unused" rules. + if (_usage != null) await _usage.FlushAsync(_scopes, cancellationToken).ConfigureAwait(false); + + try + { + foreach (var repository in await TargetsAsync(policy, cancellationToken).ConfigureAwait(false)) + { + var part = new RetentionRepositoryReport { Repository = repository.Name, Format = repository.Format }; + report.Repositories.Add(part); + try + { + await RunRepositoryAsync(policy, repository, dryRun, part, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + _logger.LogError(e, "Retention policy {Policy} failed on repository {Repository}", policy.Name, repository.Name); + part.Error = $"{e.GetType().Name}: {e.Message}"; + } + } + } + catch (MaintenanceException) when (!dryRun) + { + // The gate closed mid-run: what was already deleted must not go unaudited. The bookkeeping row may be unwritable now + // (RecordRunAsync tolerates that); the refusal still propagates. + report.Finished = _time.UtcNow; + _audit.Record(actor, "retention.run", $"policy {policy.Name}", "Interrupted by the read-only gate. " + report.Summary); + await RecordRunAsync(policy, started, report, actor, cancellationToken).ConfigureAwait(false); + + throw; + } + + report.Finished = _time.UtcNow; + _audit.Record(actor, dryRun ? "retention.dry-run" : "retention.run", $"policy {policy.Name}", report.Summary); + if (!dryRun) await RecordRunAsync(policy, started, report, actor, cancellationToken).ConfigureAwait(false); + + return report; + } + + private async Task RunRepositoryAsync(RetentionPolicy policy, RepositoryInfo repository, bool dryRun, RetentionRepositoryReport part, CancellationToken cancellationToken) + { + using var scope = _scopes.CreateRepositoryScope(repository); + var services = scope.ServiceProvider; + var context = services.GetRequiredService(); + var hooks = services.GetFormatService(repository.Format); + if (hooks == null) + { + part.Notes.Add($"The {repository.Format} format has no retention hooks; nothing was examined."); + + return; + } + + var versions = await hooks.ListVersionsAsync(cancellationToken).ConfigureAwait(false); + var unreferenced = policy.UntaggedAfterDays == null || repository.Format != RepositoryFormat.Docker + ? Array.Empty() + : await hooks.ListUnreferencedAsync(cancellationToken).ConfigureAwait(false); + + // The cache limit needs sizes; the listing leaves the costly ones out. + if (policy.CacheLimitBytes != null && repository.Kind == RepositoryKind.Remote) + { + var sized = new List(versions.Count); + foreach (var version in versions) + { + sized.Add(version.Size != null ? version : version with { Size = await hooks.GetSizeAsync(version.Name, version.Version, cancellationToken).ConfigureAwait(false) }); + } + + versions = sized; + } + + var holds = await LoadHoldsAsync(context, cancellationToken).ConfigureAwait(false); + var now = _time.UtcNow; + var decision = RetentionEvaluator.Evaluate(policy, repository, versions, unreferenced, holds, now); + + part.Examined = decision.Examined; + part.Notes.AddRange(decision.Notes); + part.Selected = decision.Selected.Count; + part.Held = decision.Held.Count; + + foreach (var held in decision.Held) part.Add(Item(repository, held, RetentionOutcome.Held, null)); + + foreach (var item in decision.Selected) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (dryRun) + { + part.Bytes += item.Size ?? 0; + part.Add(Item(repository, item, RetentionOutcome.Planned, null)); + continue; + } + + // A hold placed since the plan was made is honoured. + var current = await LoadHoldsAsync(context, cancellationToken).ConfigureAwait(false); + if (current.IsHeld(item.Name, item.Version)) + { + part.Held++; + part.Selected--; + part.Add(Item(repository, item, RetentionOutcome.Held, null)); + continue; + } + + try + { + await hooks.DeleteVersionAsync(item.Name, item.Version, cancellationToken).ConfigureAwait(false); + part.Deleted++; + part.Bytes += item.Size ?? 0; + part.Add(Item(repository, item, RetentionOutcome.Deleted, null)); + await ForgetUsageAsync(context, item, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + _logger.LogWarning(e, "Retention could not delete {Name} {Version} from {Repository}", item.Name, item.Version, repository.Name); + part.Failed++; + part.Add(Item(repository, item, RetentionOutcome.Failed, $"{e.GetType().Name}: {e.Message}")); + } + } + + if (policy.CollectGarbage) + { + if (repository.Format != RepositoryFormat.Docker) + { + part.Notes.Add("The garbage collection applies to Docker repositories only; it was ignored."); + } + else if (!StreamingStorage.IsSupported(services.GetRequiredService())) + { + part.Notes.Add("The configured storage cannot hold Docker blobs, so there is nothing to collect."); + } + else + { + part.GarbageCollection = await services.GetRequiredService().RunAsync(dryRun, cancellationToken).ConfigureAwait(false); + } + } + } + + private static RetentionReportItem Item(RepositoryInfo repository, RetentionSelection s, RetentionOutcome outcome, string? error) + => new(repository.Name, s.Name, s.Version, s.Published, s.LastDownloaded, s.Size, string.Join(", ", s.Rules.Select(Describe)), outcome, error); + + /// The rule in words, for reports. + public static string Describe(RetentionRule rule) => rule switch + { + RetentionRule.KeepLast => "beyond the newest versions kept", + RetentionRule.OlderThan => "older than the age limit", + RetentionRule.Unused => "not downloaded recently", + RetentionRule.CacheLimit => "evicted from the cache (least recently used)", + RetentionRule.Untagged => "untagged manifest", + _ => rule.ToString(), + }; + + private static async Task LoadHoldsAsync(IContext context, CancellationToken cancellationToken) + { + var rows = await context.RetentionHolds!.AsNoTracking().Select(h => new { h.Name, h.Version }).ToListAsync(cancellationToken).ConfigureAwait(false); + + return new RetentionEvaluator.HoldSet(rows.Select(r => (r.Name!, r.Version ?? string.Empty))); + } + + // The download time of a version that is gone is of no use; a failure here must not undo the deletion. + private async Task ForgetUsageAsync(IContext context, RetentionSelection item, CancellationToken cancellationToken) + { + try + { + var name = ArtifactUsageRecorder.Normalize(item.Name); + var version = ArtifactUsageRecorder.Normalize(item.Version); + var rows = await context.ArtifactUsages!.Where(u => u.Name == name && u.Version == version).ToListAsync(cancellationToken).ConfigureAwait(false); + if (rows.Count == 0) return; + + context.ArtifactUsages!.RemoveRange(rows); + await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + _logger.LogDebug(e, "Could not drop the download time of {Name} {Version}", item.Name, item.Version); + } + } + + private async Task RecordRunAsync(RetentionPolicy policy, DateTime started, RetentionReport report, string? actor, CancellationToken cancellationToken) + { + try + { + var row = await _context.RetentionPolicies!.FirstOrDefaultAsync(p => p.Key == policy.Key, cancellationToken).ConfigureAwait(false); + if (row == null) return; + + row.LastRun = started; + var summary = report.Summary; + row.LastResult = summary.Length <= RetentionLimits.MaxResultLength ? summary : summary.Substring(0, RetentionLimits.MaxResultLength - 3) + "..."; + AccessAdministration.Audit(_context, _time.UtcNow, actor, "retention.run", policy.Name, new + { + repositories = report.Repositories.Select(r => r.Repository).ToArray(), + deleted = report.Deleted, + held = report.Held, + failed = report.Failed, + bytes = report.Bytes, + }); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + // The deletions are done; a gate that closed since only costs the bookkeeping, and the next run records itself. + _logger.LogWarning(e, "Could not record the run of retention policy {Policy}", policy.Name); + } + } +} diff --git a/src/BaGet.Core/Retention/RetentionEntities.cs b/src/BaGet.Core/Retention/RetentionEntities.cs new file mode 100644 index 000000000..dd0dd5dd2 --- /dev/null +++ b/src/BaGet.Core/Retention/RetentionEntities.cs @@ -0,0 +1,140 @@ +using System; + +namespace BaGet.Core; + +/// Column limits of the retention tables; the longest Maven group:artifact (200 + 1 + 128) fits a name. +public static class RetentionLimits +{ + public const int MaxNameLength = 340; + public const int MaxVersionLength = 128; + public const int MaxReasonLength = 512; + public const int MaxPatternsLength = 1024; + public const int MaxResultLength = 1024; +} + +/// +/// A retention policy: which stored versions of one repository (or of every repository of a project) are deleted, and when. +/// A version is deleted when any enabled rule selects it and no covers it. Not repository-scoped: +/// the administrator lists policies across repositories. RepositoryKey and ProjectKey are optional Restrict foreign keys; +/// deleting a repository or a project deletes its policies first. +/// +public class RetentionPolicy +{ + public int Key { get; set; } + + /// Unique, rules. + public string? Name { get; set; } + + /// The the policy applies to, or null when it applies to a project. + public int? RepositoryKey { get; set; } + + /// The : the policy applies to every repository of the project. Exactly one of the two keys is set. + public int? ProjectKey { get; set; } + + /// A disabled policy is never run by the schedule and refuses a manual run (a dry run still reports). + public bool Enabled { get; set; } + + /// + /// Globs (, one per line) naming the artifacts the policy looks at (package ids, npm names, Maven + /// group:artifact, image names); empty means every artifact. + /// + public string? NamePatterns { get; set; } + + /// Keep this many newest versions of each artifact (by publish time); older ones are selected. Null: rule off. + public int? KeepLast { get; set; } + + /// Select versions published more than this many days ago. Null: rule off. + public int? OlderThanDays { get; set; } + + /// Select versions not downloaded for this many days (the publish time counts when never downloaded). Null: rule off. + public int? UnusedDays { get; set; } + + /// The age and count rules look at prerelease versions (NuGet pre-release, npm prerelease, Maven snapshot) only. + public bool PrereleaseOnly { get; set; } + + /// + /// Remote repositories only: when what the repository cached is larger than this many bytes, the least recently used versions are + /// selected until it fits. Null: rule off. + /// + public long? CacheLimitBytes { get; set; } + + /// + /// Docker only: select manifests no tag, index or referrer relationship points at that were pushed more than this many days ago. + /// Null: rule off. + /// + public int? UntaggedAfterDays { get; set; } + + /// Docker only: run the garbage collection () after the rules, to free the blobs. + public bool CollectGarbage { get; set; } + + /// Run every this many hours (a real run, by the background worker). Null: only when an administrator starts it. + public int? ScheduleHours { get; set; } + + /// When the schedule was set or the policy enabled; the first scheduled run is due this long after it. + public DateTime? ScheduleStart { get; set; } + + /// When the last real run started (the schedule counts from the later of this and ). + public DateTime? LastRun { get; set; } + + /// One line about the last real run. + public string? LastResult { get; set; } + + public DateTime Created { get; set; } + + /// + /// Since when the unused rule has been watching the policy's scope (set when the rule is enabled or changed, or the repository, + /// project or name patterns change; null on rows that predate it, which fall back to ). A version never + /// downloaded counts as unused from the later of its publication and this time: downloads are recorded only while watched. + /// + public DateTime? UnusedSince { get; set; } + + public DateTime Modified { get; set; } +} + +/// +/// A legal hold: an artifact ( empty) or one version of it that no retention policy deletes, however old or +/// unused. Repository-scoped. The name and version are in the form the format's hooks list them +/// (). Retention is all a hold governs: a user who may delete a version still can. +/// +public class RetentionHold : IRepositoryScoped +{ + public int Key { get; set; } + + /// The owning repository; see . + public int RepositoryKey { get; set; } + + /// The artifact name as the format lists it. + public string? Name { get; set; } + + /// The version, or the empty string for every version of the artifact (the column is never null so the unique index works). + public string? Version { get; set; } + + /// Why (a case number, a ticket). + public string? Reason { get; set; } + + /// The administrator who placed it. + public string? CreatedBy { get; set; } + + public DateTime Created { get; set; } +} + +/// +/// When a version was last downloaded, for the "unused" and cache rules; formats other than NuGet keep no download count. Written in +/// batches by . Repository-scoped. +/// +public class ArtifactUsage : IRepositoryScoped +{ + public int Key { get; set; } + + /// The owning repository; see . + public int RepositoryKey { get; set; } + + /// The artifact name as the format lists it. + public string? Name { get; set; } + + /// The version (a Docker tag or manifest digest for images). + public string? Version { get; set; } + + /// The last download (UTC). + public DateTime LastUsed { get; set; } +} diff --git a/src/BaGet.Core/Retention/RetentionEvaluator.cs b/src/BaGet.Core/Retention/RetentionEvaluator.cs new file mode 100644 index 000000000..201622471 --- /dev/null +++ b/src/BaGet.Core/Retention/RetentionEvaluator.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Core; + +/// The rules of a , as the reasons a version is selected. +public enum RetentionRule +{ + /// Older than the newest versions of its artifact. + KeepLast, + + /// Published longer ago than . + OlderThan, + + /// Not downloaded for . + Unused, + + /// Evicted to bring a remote cache under . + CacheLimit, + + /// An untagged Docker manifest older than . + Untagged, +} + +/// A version a policy selected. +/// The artifact. +/// The version (a digest for an untagged manifest). +/// When it was stored. +/// The last download, when known. +/// Bytes it frees, when known. +/// Every rule that selected it. +/// Whether it is an untagged manifest (listed by ). +public sealed record RetentionSelection(string Name, string Version, DateTime Published, DateTime? LastDownloaded, long? Size, IReadOnlyList Rules, bool Unreferenced); + +/// What decided for one repository. +/// Versions looked at (after the name patterns). +/// Versions to delete, in a stable order (artifact, then oldest first). +/// Versions a rule selected that a legal hold protects: they are not deleted. +/// Rules that do not apply to this repository, in words. +public sealed record RetentionDecision(int Examined, IReadOnlyList Selected, IReadOnlyList Held, IReadOnlyList Notes); + +/// +/// The retention rules as a pure function of a policy, the versions a repository stores, the legal holds and the clock: the dry run +/// and the real run both call it, so a report is exactly what a run deletes (a version held or deleted in between aside). +/// +public static class RetentionEvaluator +{ + /// The legal holds of a repository, matched case-insensitively. A hold with an empty version covers every version of the artifact. + public sealed class HoldSet + { + private readonly HashSet _artifacts; + private readonly HashSet<(string, string)> _versions; + + /// No holds. + public static HoldSet Empty { get; } = new(Array.Empty<(string, string)>()); + + /// (name, version) pairs; the version is empty for a whole artifact. + public HoldSet(IEnumerable<(string Name, string Version)> holds) + { + var all = holds.ToList(); + _artifacts = new HashSet(all.Where(h => h.Version.Length == 0).Select(h => h.Name), StringComparer.OrdinalIgnoreCase); + _versions = new HashSet<(string, string)>(all.Where(h => h.Version.Length > 0), PairComparer.Instance); + } + + /// Whether the version (or its whole artifact) is under a legal hold. + public bool IsHeld(string name, string version) => _artifacts.Contains(name) || _versions.Contains((name, version)); + + private sealed class PairComparer : IEqualityComparer<(string, string)> + { + public static readonly PairComparer Instance = new(); + + public bool Equals((string, string) x, (string, string) y) + => string.Equals(x.Item1, y.Item1, StringComparison.OrdinalIgnoreCase) && string.Equals(x.Item2, y.Item2, StringComparison.OrdinalIgnoreCase); + + public int GetHashCode((string, string) value) + => HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(value.Item1), StringComparer.OrdinalIgnoreCase.GetHashCode(value.Item2)); + } + } + + /// Applies to the versions of . + /// The policy. + /// The repository the versions are in (its kind decides whether the cache limit applies). + /// Every version the format lists. + /// Things nothing points at (untagged Docker manifests). + /// The legal holds. + /// The current time (UTC). + public static RetentionDecision Evaluate( + RetentionPolicy policy, + RepositoryInfo repository, + IReadOnlyList versions, + IReadOnlyList unreferenced, + HoldSet holds, + DateTime now) + { + if (policy == null) throw new ArgumentNullException(nameof(policy)); + if (repository == null) throw new ArgumentNullException(nameof(repository)); + + var notes = new List(); + var patterns = AccessPatterns.Split(policy.NamePatterns); + bool Matches(string name) => patterns.Length == 0 || AccessPatterns.IsMatch(patterns, name); + + var considered = versions.Where(v => Matches(v.Name)).ToList(); + var candidates = policy.PrereleaseOnly ? considered.Where(v => v.Prerelease).ToList() : considered; + + var rules = new Dictionary<(string, string), List>(PairKeyComparer.Instance); + void Select(FormatVersion v, RetentionRule rule) + { + if (!rules.TryGetValue((v.Name, v.Version), out var list)) rules[(v.Name, v.Version)] = list = new List(); + if (!list.Contains(rule)) list.Add(rule); + } + + if (policy.KeepLast is int keep && keep >= 0) + { + foreach (var artifact in candidates.GroupBy(v => v.Name, StringComparer.OrdinalIgnoreCase)) + { + // Newest first; the version text breaks a tie so the same data always gives the same answer. + foreach (var old in artifact.OrderByDescending(v => v.Published).ThenByDescending(v => v.Version, StringComparer.Ordinal).Skip(keep)) Select(old, RetentionRule.KeepLast); + } + } + + if (policy.OlderThanDays is int age) + { + var cutoff = now - TimeSpan.FromDays(age); + foreach (var v in candidates.Where(v => v.Published < cutoff)) Select(v, RetentionRule.OlderThan); + } + + if (policy.UnusedDays is int unused) + { + var cutoff = now - TimeSpan.FromDays(unused); + + // A version with no recorded download counts from its publication, but never from before the policy watched its scope (UnusedSince, else Created): downloads + // are recorded only since usage tracking began (an upgraded install has no history), so "unused for N days" cannot be + // judged for a period the policy did not watch. + foreach (var v in candidates.Where(v => (v.LastDownloaded ?? Latest(v.Published, policy.UnusedSince ?? policy.Created)) < cutoff)) Select(v, RetentionRule.Unused); + } + + if (policy.CacheLimitBytes is long limit) + { + if (repository.Kind != RepositoryKind.Remote) + { + notes.Add("The cache limit applies to remote repositories only; it was ignored."); + } + else + { + // Evict the least recently used versions that no other rule and no hold already takes, until what is left fits. + var total = considered.Sum(v => v.Size ?? 0); + var freed = considered.Where(v => rules.ContainsKey((v.Name, v.Version)) && !holds.IsHeld(v.Name, v.Version)).Sum(v => v.Size ?? 0); + if (total - freed > limit) + { + foreach (var v in considered + .Where(v => !rules.ContainsKey((v.Name, v.Version)) && !holds.IsHeld(v.Name, v.Version)) + .OrderBy(v => v.LastDownloaded ?? v.Published) + .ThenBy(v => v.Name, StringComparer.Ordinal) + .ThenBy(v => v.Version, StringComparer.Ordinal)) + { + if (total - freed <= limit) break; + + Select(v, RetentionRule.CacheLimit); + freed += v.Size ?? 0; + } + } + } + } + + var selected = new List(); + var held = new List(); + foreach (var v in considered) + { + if (!rules.TryGetValue((v.Name, v.Version), out var list)) continue; + + var item = new RetentionSelection(v.Name, v.Version, v.Published, v.LastDownloaded, v.Size, list, Unreferenced: false); + (holds.IsHeld(v.Name, v.Version) ? held : selected).Add(item); + } + + if (policy.UntaggedAfterDays is int untagged) + { + if (repository.Format != RepositoryFormat.Docker) + { + notes.Add("The untagged-manifest rule applies to Docker repositories only; it was ignored."); + } + else + { + var cutoff = now - TimeSpan.FromDays(untagged); + foreach (var v in unreferenced.Where(v => Matches(v.Name) && v.Published < cutoff)) + { + var item = new RetentionSelection(v.Name, v.Version, v.Published, v.LastDownloaded, v.Size, new[] { RetentionRule.Untagged }, Unreferenced: true); + (holds.IsHeld(v.Name, v.Version) ? held : selected).Add(item); + } + } + } + + static IOrderedEnumerable Order(IEnumerable items) + => items.OrderBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Published).ThenBy(i => i.Version, StringComparer.Ordinal); + + return new RetentionDecision(considered.Count, Order(selected).ToList(), Order(held).ToList(), notes); + } + + private static DateTime Latest(DateTime a, DateTime b) => a > b ? a : b; + + private sealed class PairKeyComparer : IEqualityComparer<(string, string)> + { + public static readonly PairKeyComparer Instance = new(); + + public bool Equals((string, string) x, (string, string) y) + => string.Equals(x.Item1, y.Item1, StringComparison.Ordinal) && string.Equals(x.Item2, y.Item2, StringComparison.Ordinal); + + public int GetHashCode((string, string) value) => HashCode.Combine(value.Item1, value.Item2); + } +} diff --git a/src/BaGet.Core/Retention/RetentionJobs.cs b/src/BaGet.Core/Retention/RetentionJobs.cs new file mode 100644 index 000000000..5ea08b2e0 --- /dev/null +++ b/src/BaGet.Core/Retention/RetentionJobs.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +public enum RetentionJobState +{ + Running, + Succeeded, + Failed, +} + +/// The last run of a policy since the server started (in memory). +public sealed class RetentionJobStatus +{ + public int PolicyKey { get; init; } + + public bool DryRun { get; init; } + + public RetentionJobState State { get; internal set; } + + /// The administrator, or scheduler. + public string? Actor { get; init; } + + public DateTime Started { get; init; } + + public DateTime? Finished { get; internal set; } + + /// The report, once the run finished (also when some versions failed). + public RetentionReport? Report { get; internal set; } + + /// Why the run failed as a whole, or null. + public string? Error { get; internal set; } +} + +/// +/// Runs retention policies in the background, one run per policy at a time, and keeps the last report of each in memory (a dry +/// run's report is the page's answer). A real run is refused while the is closed; every run is audited +/// by . +/// +public sealed class RetentionJobs +{ + private readonly IServiceScopeFactory _scopes; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + private readonly IHostApplicationLifetime? _lifetime; + private readonly IJobLease? _lease; + private readonly ConcurrentDictionary _status = new(); + private readonly ConcurrentDictionary _running = new(); + private readonly object _lock = new(); + + public RetentionJobs(IServiceScopeFactory scopes, SystemTime time, MaintenanceGate gate, ILogger logger, IHostApplicationLifetime? lifetime = null, IJobLease? lease = null) + { + _lease = lease; + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _lifetime = lifetime; + } + + /// The last run of the policy, or null if none since the server started. + public RetentionJobStatus? Get(int policyKey) => _status.TryGetValue(policyKey, out var status) ? status : null; + + /// Starts a run of the policy in the background. + /// The policy. + /// Whether to only report. + /// Who started it. + /// Why it was not started. + /// A real run while the server is read-only. + public bool TryStart(int policyKey, bool dryRun, string? actor, out string? refusal) + { + if (!dryRun) _gate.ThrowIfClosed(); + + // One run per policy in the whole cluster (a dry run changes nothing and takes no lease). + IAsyncDisposable? held = null; + if (!dryRun) + { + held = _lease.Acquire($"retention:policy:{policyKey}"); + if (held == null) + { + refusal = "This policy is already running (on another node)."; + + return false; + } + } + + var status = new RetentionJobStatus { PolicyKey = policyKey, DryRun = dryRun, State = RetentionJobState.Running, Actor = actor, Started = _time.UtcNow }; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + lock (_lock) + { + if (_running.ContainsKey(policyKey)) + { + held?.Release(); + refusal = "This policy is already running."; + + return false; + } + + _status[policyKey] = status; + _running[policyKey] = completion.Task; + } + + var stopping = _lifetime?.ApplicationStopping ?? CancellationToken.None; + _ = Task.Run(async () => + { + try + { + using var scope = _scopes.CreateScope(); + var report = await scope.ServiceProvider.GetRequiredService().RunAsync(policyKey, dryRun, actor, stopping).ConfigureAwait(false); + status.Report = report; + Finish(status, RetentionJobState.Succeeded, null); + } + catch (Exception e) + { + _logger.LogError(e, "Retention policy {Policy} failed", policyKey); + Finish(status, RetentionJobState.Failed, $"{e.GetType().Name}: {e.Message}"); + } + finally + { + _running.TryRemove(policyKey, out _); + if (held != null) + { + try { await held.DisposeAsync().ConfigureAwait(false); } catch (Exception) { /* the lease expires by itself */ } + } + + completion.SetResult(true); + } + }); + + refusal = null; + + return true; + } + + /// Completes when the current run of the policy ends (immediately when none). + public Task WaitAsync(int policyKey) => _running.TryGetValue(policyKey, out var task) ? task : Task.CompletedTask; + + private void Finish(RetentionJobStatus status, RetentionJobState state, string? error) + { + status.Error = error; + status.Finished = _time.UtcNow; + status.State = state; + } +} + +/// +/// Starts the policies whose schedule is due ( after the later of the last run and the +/// time the schedule was set), and writes the download times collected. Idle while the server is +/// read-only for maintenance (the due policies run on the next pass after it reopens) and with a database that cannot hold policies. +/// +public sealed class RetentionWorker : BackgroundService +{ + /// How often the worker looks. + internal static readonly TimeSpan Interval = TimeSpan.FromMinutes(1); + + private readonly IServiceScopeFactory _scopes; + private readonly RetentionJobs _jobs; + private readonly ArtifactUsageRecorder _usage; + private readonly MaintenanceGate _gate; + private readonly SystemTime _time; + private readonly ILogger _logger; + private readonly IJobLease? _lease; + + public RetentionWorker(IServiceScopeFactory scopes, RetentionJobs jobs, ArtifactUsageRecorder usage, MaintenanceGate gate, SystemTime time, ILogger logger, IJobLease? lease = null) + { + _lease = lease; + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _jobs = jobs ?? throw new ArgumentNullException(nameof(jobs)); + _usage = usage ?? throw new ArgumentNullException(nameof(usage)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + // The wait comes first: the database may still be migrating when the host starts. + try + { + await Task.Delay(Interval, stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + + try + { + await RunDueAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception e) + { + _logger.LogError(e, "Retention pass failed; it is retried on the next one"); + } + } + } + + /// One pass: flush the download times, then run every due policy (one after the other) and wait for them. + /// The keys of the policies started. + public async Task> RunDueAsync(CancellationToken cancellationToken) + { + await _usage.FlushAsync(_scopes, cancellationToken).ConfigureAwait(false); + if (_gate.IsClosed) return Array.Empty(); + + // One scheduling pass in the whole cluster: the node holding this lease starts the due policies and waits for them. + await using var pass = await _lease.AcquireAsync("retention:schedule", cancellationToken).ConfigureAwait(false); + if (pass == null) return Array.Empty(); + + List due; + using (var scope = _scopes.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + if (context is NullContext) return Array.Empty(); + + var now = _time.UtcNow; + var candidates = await context.RetentionPolicies!.AsNoTracking().Where(p => p.Enabled && p.ScheduleHours != null).ToListAsync(cancellationToken).ConfigureAwait(false); + due = candidates.Where(p => IsDue(p, now)).OrderBy(p => p.Key).ToList(); + } + + var started = new List(); + foreach (var policy in due) + { + try + { + if (!_jobs.TryStart(policy.Key, dryRun: false, "scheduler", out _)) continue; + } + catch (MaintenanceException) + { + break; + } + + started.Add(policy.Key); + await _jobs.WaitAsync(policy.Key).ConfigureAwait(false); + } + + return started; + } + + /// Whether the schedule of is due at . + public static bool IsDue(RetentionPolicy policy, DateTime now) + { + if (!policy.Enabled || policy.ScheduleHours is not int hours) return false; + + var basis = new[] { policy.LastRun, policy.ScheduleStart, policy.Created }.Where(d => d != null).Select(d => d!.Value).DefaultIfEmpty(DateTime.MinValue).Max(); + + return basis.AddHours(hours) <= now; + } +} diff --git a/src/BaGet.Core/Retention/RetentionReport.cs b/src/BaGet.Core/Retention/RetentionReport.cs new file mode 100644 index 000000000..cd7e5307d --- /dev/null +++ b/src/BaGet.Core/Retention/RetentionReport.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Core; + +/// What happened (or, in a dry run, would happen) to one selected version. +public enum RetentionOutcome +{ + /// Dry run: the run would delete it. + Planned, + + /// Deleted. + Deleted, + + /// A rule selected it and a legal hold protects it: kept. + Held, + + /// Deleting it failed (); the next run tries again. + Failed, +} + +/// One version in a report. +public sealed record RetentionReportItem( + string Repository, + string Name, + string Version, + DateTime Published, + DateTime? LastDownloaded, + long? Size, + string Rules, + RetentionOutcome Outcome, + string? Error); + +/// The part of a that concerns one repository. +public sealed class RetentionRepositoryReport +{ + /// The most items listed per repository (the counts are exact). + public const int MaxItems = 1000; + + public string Repository { get; init; } = string.Empty; + + public RepositoryFormat Format { get; init; } + + /// Versions looked at (matching the policy's name patterns). + public int Examined { get; set; } + + /// Versions selected by a rule and not held (dry run: to be deleted). + public int Selected { get; set; } + + /// Versions deleted (always 0 in a dry run). + public int Deleted { get; set; } + + /// Versions a rule selected that a legal hold kept. + public int Held { get; set; } + + /// Versions whose deletion failed. + public int Failed { get; set; } + + /// Bytes of the deleted versions (dry run: of the selected ones), as far as known. + public long Bytes { get; set; } + + public List Items { get; } = new(); + + public bool ItemsTruncated { get; set; } + + /// Rules that did not apply, and similar remarks. + public List Notes { get; } = new(); + + /// For Docker, the garbage collection that followed (a dry run: what it would remove, as of before this run's deletions). + public OciGcReport? GarbageCollection { get; set; } + + /// Why the repository could not be processed, or null. + public string? Error { get; set; } + + internal void Add(RetentionReportItem item) + { + if (Items.Count < MaxItems) Items.Add(item); + else ItemsTruncated = true; + } +} + +/// The result of running (or dry-running) a policy over its repositories. +public sealed class RetentionReport +{ + public int PolicyKey { get; init; } + + public string PolicyName { get; init; } = string.Empty; + + /// Whether nothing was changed. + public bool DryRun { get; init; } + + public DateTime Started { get; init; } + + public DateTime? Finished { get; set; } + + public List Repositories { get; } = new(); + + public int Selected => Repositories.Sum(r => r.Selected); + + public int Deleted => Repositories.Sum(r => r.Deleted); + + public int Held => Repositories.Sum(r => r.Held); + + public int Failed => Repositories.Sum(r => r.Failed); + + public long Bytes => Repositories.Sum(r => r.Bytes); + + /// One line for the policy page, the job status and the audit log. + public string Summary + { + get + { + var text = DryRun + ? $"Dry run, nothing deleted. Would delete {Selected} version(s) ({FormatBytes(Bytes)}), {Held} kept by legal hold" + : $"Deleted {Deleted} version(s) ({FormatBytes(Bytes)}), {Held} kept by legal hold, {Failed} failed"; + text += $", across {Repositories.Count} repositor{(Repositories.Count == 1 ? "y" : "ies")}."; + var errors = Repositories.Where(r => r.Error != null).Select(r => $"{r.Repository}: {r.Error}").ToList(); + if (errors.Count > 0) text += " Errors: " + string.Join("; ", errors) + "."; + + return text; + } + } + + /// Bytes in KiB/MiB/GiB for the pages. + public static string FormatBytes(long bytes) + { + string[] units = { "B", "KiB", "MiB", "GiB", "TiB" }; + double value = bytes; + var unit = 0; + while (value >= 1024 && unit < units.Length - 1) + { + value /= 1024; + unit++; + } + + return unit == 0 ? $"{bytes} B" : $"{value:0.#} {units[unit]}"; + } +} diff --git a/src/BaGet.Core/Scanning/IScanService.cs b/src/BaGet.Core/Scanning/IScanService.cs new file mode 100644 index 000000000..c22dcc1bd --- /dev/null +++ b/src/BaGet.Core/Scanning/IScanService.cs @@ -0,0 +1,85 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// Whether the repository of the request can be scanned now, and by what. +/// Whether a scan can run. +/// What scans the repository's artifacts (OSV.dev, OSV offline copy, Trivy), or null. +/// Why it cannot, or null. Safe to show. +public sealed record ScanEngineStatus(bool Available, string? Engine, string? Reason); + +/// What a pass over a repository did. +/// Artifacts scanned. +/// Artifacts left alone because their last scan is recent enough. +/// Artifacts whose scan failed (the source was unreachable…). +/// Of the scanned, those with at least one finding. +/// Results dropped because the artifact is gone. +public sealed record ScanRepositoryReport(int Scanned, int Skipped, int Failed, int WithFindings, int Removed) +{ + /// A one-line description for the Operations page. + public override string ToString() + => $"Scanned {Scanned} artifact(s): {WithFindings} with findings, {Failed} failed, {Skipped} up to date, {Removed} stale result(s) removed."; +} + +/// The repository dashboard numbers. +/// The scanner status. +/// Artifacts stored in the repository. +/// Artifacts with no successful scan. +/// Of those, the ones whose last attempt failed. +/// Artifacts scanned without findings. +/// Artifacts by their highest finding: index 0 low … 3 critical. +public sealed record ScanSummary(ScanEngineStatus Engine, int Artifacts, int Unscanned, int Failed, int Clean, IReadOnlyList BySeverity); + +/// +/// Scans the artifacts of the repository of the request and keeps the results. Scoped; works in +/// , so a caller outside a request uses a repository scope. Authorizes nothing (callers decide). +/// +public interface IScanService +{ + /// Whether and how the repository can be scanned now. + ScanEngineStatus GetEngineStatus(); + + /// + /// Whether the repository stores the version (a remote repository does not until the first download fetched it, so there is + /// nothing to scan before). + /// + Task IsStoredAsync(string name, string version, CancellationToken cancellationToken); + + /// The stored result of a version with its findings (worst first), or null when it was never scanned. + Task FindAsync(string name, string version, CancellationToken cancellationToken); + + /// + /// Forgets the stored result of a version whose artifact was just stored again (a re-publish after a delete, a Maven redeploy or + /// a new snapshot build): the old verdict is about other bytes. No-op without a result. + /// + Task ForgetAsync(string name, string version, CancellationToken cancellationToken); + + /// + /// Scans one version now and stores the result (and, for NuGet, the vulnerability resource's entries). A failed scan is stored + /// as such () and returned. + /// + /// The result, or null when the version does not exist (a stored result of it is removed). + /// Scanning is off or the repository cannot be scanned. + /// The database is read-only. + Task ScanAsync(string name, string version, CancellationToken cancellationToken); + + /// + /// Scans every version of the repository (: only those not scanned within + /// ) and drops results of versions that no longer exist. + /// + Task ScanRepositoryAsync(bool onlyStale, CancellationToken cancellationToken); + + /// The numbers of the repository dashboard. + Task SummarizeAsync(CancellationToken cancellationToken); + + /// Scanned versions with a finding of at least , worst first (no findings loaded). + Task> ListAsync(int minSeverity, int skip, int take, CancellationToken cancellationToken); + + /// + /// The advisories that apply to (OSV formats), without storing anything: what a deploy check asks. + /// + /// The source cannot be reached. + Task> CheckAsync(IReadOnlyList components, CancellationToken cancellationToken); +} diff --git a/src/BaGet.Core/Scanning/OsvAdvisory.cs b/src/BaGet.Core/Scanning/OsvAdvisory.cs new file mode 100644 index 000000000..015c3ba65 --- /dev/null +++ b/src/BaGet.Core/Scanning/OsvAdvisory.cs @@ -0,0 +1,379 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// One vulnerability record in the OSV schema (https://ossf.github.io/osv-schema/), reduced to what scanning uses: the id, a +/// summary, a severity, a link, and the packages and versions it affects. Parsed from an OSV.dev answer or from a file of an +/// offline copy; the same matching decides whether it applies to a component. +/// +public sealed class OsvAdvisory +{ + private OsvAdvisory(string id, string? summary, int severity, string url, IReadOnlyList affected) + { + Id = id; + Summary = summary; + Severity = severity; + Url = url; + Affected = affected; + } + + /// The identifier (GHSA-…, CVE-…, PYSEC-…). + public string Id { get; } + + /// One line describing it, or null. + public string? Summary { get; } + + /// 0 low … 3 critical; when the record carries none. + public int Severity { get; } + + /// An absolute http(s) link to the advisory (its OSV page when the record names no better). + public string Url { get; } + + /// The package entries of the record. + public IReadOnlyList Affected { get; } + + /// Whether the record withdraws itself (it is then ignored). + public bool Withdrawn { get; private set; } + + /// Reads one record; null when it has no id. + public static OsvAdvisory? Parse(JsonElement record) + { + if (record.ValueKind != JsonValueKind.Object) return null; + var id = Text(record, "id"); + if (string.IsNullOrWhiteSpace(id)) return null; + + var summary = Text(record, "summary"); + if (string.IsNullOrWhiteSpace(summary)) + { + var details = Text(record, "details"); + if (!string.IsNullOrWhiteSpace(details)) + { + var line = details.Split('\n')[0].Trim(); + summary = line.Length > 300 ? line.Substring(0, 300) : line; + } + } + else if (summary.Length > 500) + { + summary = summary.Substring(0, 500); + } + + var advisory = new OsvAdvisory(id, string.IsNullOrWhiteSpace(summary) ? null : summary, ReadSeverity(record), ReadUrl(record, id), ReadAffected(record)) + { + Withdrawn = record.TryGetProperty("withdrawn", out var withdrawn) && withdrawn.ValueKind == JsonValueKind.String, + }; + return advisory; + } + + /// + /// Whether the record applies to , and the first version that fixes it when the record says. + /// + public bool Affects(ScanComponent component, out string? fixedVersion) + { + fixedVersion = null; + if (Withdrawn) return false; + + var affects = false; + foreach (var entry in Affected) + { + if (!string.Equals(entry.Ecosystem, component.Ecosystem, StringComparison.OrdinalIgnoreCase) + || !string.Equals(entry.Name, component.Name, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (entry.Versions.Any(v => string.Equals(v, component.Version, StringComparison.OrdinalIgnoreCase))) + { + affects = true; + } + + foreach (var range in entry.Ranges) + { + if (range.IsAffected(component.Ecosystem, component.Version, out var fix)) + { + affects = true; + if (fix != null && (fixedVersion == null || OsvVersions.Compare(component.Ecosystem, fix, fixedVersion) < 0)) fixedVersion = fix; + } + } + } + + return affects; + } + + private static string? Text(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + + private static int ReadSeverity(JsonElement record) + { + // GitHub advisories (the bulk of npm, Maven and NuGet records) name the level in database_specific.severity. + if (record.TryGetProperty("database_specific", out var database) && database.ValueKind == JsonValueKind.Object + && ScanSeverities.TryParseName(Text(database, "severity"), out var named)) + { + return named; + } + + if (record.TryGetProperty("severity", out var severities) && severities.ValueKind == JsonValueKind.Array) + { + foreach (var entry in severities.EnumerateArray()) + { + var score = ScanSeverities.CvssV3BaseScore(Text(entry, "score")); + if (score != null) return ScanSeverities.FromScore(score.Value); + } + } + + if (record.TryGetProperty("affected", out var affected) && affected.ValueKind == JsonValueKind.Array) + { + foreach (var entry in affected.EnumerateArray()) + { + if (entry.TryGetProperty("ecosystem_specific", out var specific) && specific.ValueKind == JsonValueKind.Object + && ScanSeverities.TryParseName(Text(specific, "severity"), out var legacy)) + { + return legacy; + } + } + } + + return ScanSeverities.Unrated; + } + + private static string ReadUrl(JsonElement record, string id) + { + string? web = null; + if (record.TryGetProperty("references", out var references) && references.ValueKind == JsonValueKind.Array) + { + foreach (var reference in references.EnumerateArray()) + { + var url = Text(reference, "url"); + if (!IsHttp(url)) continue; + var type = Text(reference, "type"); + if (string.Equals(type, "ADVISORY", StringComparison.OrdinalIgnoreCase)) return url!; + if (web == null && string.Equals(type, "WEB", StringComparison.OrdinalIgnoreCase)) web = url; + } + } + + return web ?? "https://osv.dev/vulnerability/" + Uri.EscapeDataString(id); + } + + private static bool IsHttp(string? url) + => Uri.TryCreate(url, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp) && url!.Length <= 900; + + private static IReadOnlyList ReadAffected(JsonElement record) + { + var result = new List(); + if (!record.TryGetProperty("affected", out var affected) || affected.ValueKind != JsonValueKind.Array) return result; + + foreach (var entry in affected.EnumerateArray()) + { + if (!entry.TryGetProperty("package", out var package) || package.ValueKind != JsonValueKind.Object) continue; + var ecosystem = Text(package, "ecosystem"); + var name = Text(package, "name"); + if (ecosystem == null || name == null) continue; + + var versions = new List(); + if (entry.TryGetProperty("versions", out var list) && list.ValueKind == JsonValueKind.Array) + { + versions.AddRange(list.EnumerateArray().Where(v => v.ValueKind == JsonValueKind.String).Select(v => v.GetString()!)); + } + + var ranges = new List(); + if (entry.TryGetProperty("ranges", out var rangeList) && rangeList.ValueKind == JsonValueKind.Array) + { + foreach (var range in rangeList.EnumerateArray()) + { + var type = Text(range, "type"); + if (type != "SEMVER" && type != "ECOSYSTEM") continue; + if (!range.TryGetProperty("events", out var events) || events.ValueKind != JsonValueKind.Array) continue; + + var parsed = new List(); + foreach (var e in events.EnumerateArray()) + { + if (e.TryGetProperty("introduced", out var introduced) && introduced.ValueKind == JsonValueKind.String) + parsed.Add(new OsvEvent(OsvEventKind.Introduced, introduced.GetString()!)); + else if (e.TryGetProperty("fixed", out var fix) && fix.ValueKind == JsonValueKind.String) + parsed.Add(new OsvEvent(OsvEventKind.Fixed, fix.GetString()!)); + else if (e.TryGetProperty("last_affected", out var last) && last.ValueKind == JsonValueKind.String) + parsed.Add(new OsvEvent(OsvEventKind.LastAffected, last.GetString()!)); + } + + ranges.Add(new OsvRange(parsed)); + } + } + + result.Add(new OsvAffected(ecosystem, name, versions, ranges)); + } + + return result; + } +} + +/// One affected entry of an OSV record: a package and the versions it covers. +public sealed record OsvAffected(string Ecosystem, string Name, IReadOnlyList Versions, IReadOnlyList Ranges); + +/// What an says about its version. +public enum OsvEventKind +{ + /// Versions from here on are affected (0 = from the start). + Introduced, + + /// Versions from here on are not affected. + Fixed, + + /// Versions after this one are not affected; this one is. + LastAffected, +} + +/// One event of a range. +public sealed record OsvEvent(OsvEventKind Kind, string Version); + +/// A SEMVER or ECOSYSTEM range of an OSV record: ordered events that switch "affected" on and off. +public sealed class OsvRange +{ + private readonly IReadOnlyList _events; + + public OsvRange(IReadOnlyList events) + { + _events = events; + } + + /// The events as written. + public IReadOnlyList Events => _events; + + /// + /// Whether is inside the range (OSV's evaluation: walk the events in version order, every + /// introduced at or below the version switches it on, a fixed at or below switches it off, a + /// last_affected below it switches it off), and the fixed version that ends the affected stretch. + /// + public bool IsAffected(string ecosystem, string version, out string? fixedVersion) + { + fixedVersion = null; + var affected = false; + var ordered = _events + .OrderBy(e => e.Version == "0" ? 0 : 1) + .ThenBy(e => e.Version, Comparer.Create((a, b) => a == "0" ? (b == "0" ? 0 : -1) : b == "0" ? 1 : OsvVersions.Compare(ecosystem, a, b))) + .ThenBy(e => e.Kind == OsvEventKind.Introduced ? 0 : 1); + + foreach (var e in ordered) + { + var cmp = e.Version == "0" ? -1 : OsvVersions.Compare(ecosystem, e.Version, version); + switch (e.Kind) + { + case OsvEventKind.Introduced: + if (cmp <= 0) affected = true; + break; + case OsvEventKind.Fixed: + if (cmp <= 0) affected = false; + else if (affected) fixedVersion ??= e.Version; + break; + case OsvEventKind.LastAffected: + if (cmp < 0) affected = false; + break; + } + } + + if (!affected) fixedVersion = null; + return affected; + } +} + +/// Version order for the OSV ecosystems BaGet scans (NuGet, npm, Maven). +public static class OsvVersions +{ + /// + /// Compares two versions: semantic versions as such (NuGet and npm versions parse as ), anything else + /// (most Maven versions) by its numeric and textual parts, with alpha < beta < milestone < rc < snapshot < + /// release < sp < any other qualifier (lexically) as in Maven. + /// + public static int Compare(string ecosystem, string left, string right) + { + if (string.Equals(ecosystem, "Maven", StringComparison.OrdinalIgnoreCase)) return CompareLoose(left, right); + if (NuGetVersion.TryParse(left, out var a) && NuGetVersion.TryParse(right, out var b)) return a.CompareTo(b); + return CompareLoose(left, right); + } + + private static int CompareLoose(string left, string right) + { + var a = Tokenize(left); + var b = Tokenize(right); + for (var i = 0; i < Math.Max(a.Count, b.Count); i++) + { + var x = i < a.Count ? a[i] : null; + var y = i < b.Count ? b[i] : null; + var cmp = CompareToken(x, y); + if (cmp != 0) return cmp; + } + + return 0; + } + + private static List Tokenize(string version) + { + var tokens = new List(); + var current = new System.Text.StringBuilder(); + bool? digits = null; + foreach (var ch in version) + { + if (ch == '.' || ch == '-' || ch == '_' || ch == '+') + { + Flush(); + continue; + } + + var isDigit = char.IsAsciiDigit(ch); + if (digits != null && digits != isDigit) Flush(); + digits = isDigit; + current.Append(char.ToLowerInvariant(ch)); + } + + Flush(); + return tokens; + + void Flush() + { + if (current.Length > 0) tokens.Add(current.ToString()); + current.Clear(); + digits = null; + } + } + + private static int CompareToken(string? x, string? y) + { + var xn = x != null && x.All(char.IsAsciiDigit); + var yn = y != null && y.All(char.IsAsciiDigit); + if ((x == null || xn) && (y == null || yn)) + { + return Number(x).CompareTo(Number(y)); + } + + // A number beats a qualifier of the same position (1.0.1 > 1.0-rc), a missing token ranks as the release itself. + var byRank = Rank(x).CompareTo(Rank(y)); + + // Maven puts an unknown qualifier (jre, android...) after the release and orders two of them lexically. + return byRank != 0 || Rank(x) != UnknownRank ? byRank : string.CompareOrdinal(x, y); + } + + private const int UnknownRank = 120; + + private static System.Numerics.BigInteger Number(string? value) + => string.IsNullOrEmpty(value) ? System.Numerics.BigInteger.Zero : System.Numerics.BigInteger.Parse(value); + + private static int Rank(string? token) + { + if (token == null || token.Length == 0) return 100; + if (token.All(char.IsAsciiDigit)) return 200; + return token switch + { + "alpha" or "a" => 10, + "beta" or "b" => 20, + "milestone" or "m" => 30, + "rc" or "cr" => 40, + "snapshot" => 50, + "ga" or "final" or "release" => 100, + "sp" => 110, + _ => UnknownRank, + }; + } +} diff --git a/src/BaGet.Core/Scanning/OsvVulnerabilitySource.cs b/src/BaGet.Core/Scanning/OsvVulnerabilitySource.cs new file mode 100644 index 000000000..318bf3c79 --- /dev/null +++ b/src/BaGet.Core/Scanning/OsvVulnerabilitySource.cs @@ -0,0 +1,439 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// One advisory that applies to a component. +/// The advisory id. +/// One line, or null. +/// 0 low … 3 critical. +/// An absolute http(s) link to the advisory. +/// The first fixed version, when the source says. +public sealed record VulnerabilityHit(string Id, string? Summary, int Severity, string Url, string? FixedVersion); + +/// Answers which advisories apply to which components (OSV, online or from an offline copy). +public interface IVulnerabilitySource +{ + /// The name recorded as . + string Name { get; } + + /// The advisories per component; a component without any maps to an empty list. + /// The source cannot be reached or read. + Task>> QueryAsync( + IReadOnlyCollection components, + CancellationToken cancellationToken); +} + +/// Scanning cannot run: it is off, the source is down or misconfigured. The message is safe to show. +public sealed class ScanUnavailableException : Exception +{ + public ScanUnavailableException(string message) + : base(message) + { } + + public ScanUnavailableException(string message, Exception inner) + : base(message, inner) + { } +} + +/// +/// What OSV scanning remembers between requests (singleton): the HTTP client, answers per component and advisory (so a repository +/// of a thousand packages sharing dependencies asks once), and the index of an offline copy. +/// +public sealed class OsvState : IDisposable +{ + private readonly HttpClient _http = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(5) }) { Timeout = Timeout.InfiniteTimeSpan }; + + internal HttpClient Http => _http; + + internal ConcurrentDictionary Hits)> Answers { get; } = new(); + + internal ConcurrentDictionary Advisories { get; } = new(StringComparer.Ordinal); + + internal SemaphoreSlim OfflineLock { get; } = new(1, 1); + + internal OsvOfflineIndex? Offline { get; set; } + + internal long OfflineCheckedAt { get; set; } + + /// Forgets every remembered answer (a test, or after the offline copy was replaced). + public void Clear() + { + Answers.Clear(); + Advisories.Clear(); + Offline = null; + OfflineCheckedAt = 0; + } + + public void Dispose() => _http.Dispose(); +} + +/// +/// The index of an offline OSV copy: the records of NuGet, npm and Maven packages by ecosystem and lower-cased name. +/// +internal sealed class OsvOfflineIndex +{ + private readonly Dictionary<(string Ecosystem, string Name), List> _byPackage = new(); + + public OsvOfflineIndex(string path, string stamp) + { + Path = path; + Stamp = stamp; + } + + public string Path { get; } + + public string Stamp { get; } + + public int Records { get; private set; } + + public IReadOnlyList For(ScanComponent component) + => _byPackage.TryGetValue((component.Ecosystem.ToLowerInvariant(), component.Name.ToLowerInvariant()), out var list) ? list : Array.Empty(); + + public void Add(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Array) + { + foreach (var item in element.EnumerateArray()) Add(item); + return; + } + + var advisory = OsvAdvisory.Parse(element); + if (advisory == null) return; + Records++; + foreach (var key in advisory.Affected.Select(a => (a.Ecosystem.ToLowerInvariant(), a.Name.ToLowerInvariant())).Distinct()) + { + if (!_byPackage.TryGetValue(key, out var list)) _byPackage[key] = list = new List(); + list.Add(advisory); + } + } + + /// The stamp of a path: its (and, for a directory, every file's) last write time and size. + public static string StampOf(string path) + { + if (Directory.Exists(path)) + { + long ticks = 0; + var count = 0; + foreach (var file in Directory.EnumerateFiles(path, "*.json", SearchOption.AllDirectories)) + { + var info = new FileInfo(file); + ticks = unchecked(ticks + info.LastWriteTimeUtc.Ticks + info.Length); + count++; + } + + return count + ":" + ticks; + } + + if (File.Exists(path)) + { + var info = new FileInfo(path); + return info.LastWriteTimeUtc.Ticks + ":" + info.Length; + } + + return "missing"; + } + + public static OsvOfflineIndex Load(string path) + { + var index = new OsvOfflineIndex(path, StampOf(path)); + if (Directory.Exists(path)) + { + foreach (var file in Directory.EnumerateFiles(path, "*.json", SearchOption.AllDirectories)) + { + using var stream = File.OpenRead(file); + index.AddStream(stream); + } + } + else if (File.Exists(path)) + { + using var archive = ZipFile.OpenRead(path); + foreach (var entry in archive.Entries.Where(e => e.FullName.EndsWith(".json", StringComparison.OrdinalIgnoreCase))) + { + using var stream = entry.Open(); + index.AddStream(stream); + } + } + else + { + throw new ScanUnavailableException("The offline vulnerability data '" + path + "' does not exist."); + } + + return index; + } + + private void AddStream(Stream stream) + { + try + { + using var document = JsonDocument.Parse(stream); + Add(document.RootElement); + } + catch (JsonException) + { + // A file that is not an OSV record (an index, a partial download) is skipped; the rest still counts. + } + } +} + +/// +/// OSV as the vulnerability source: the online API (POST /v1/querybatch for the ids that apply to each component, then +/// GET /v1/vulns/{id} for the records) or, when is set, an offline copy of the +/// data. Answers are remembered for . Data provided by OSV.dev; each record keeps the +/// licence of its source (the GitHub Advisory Database is CC-BY 4.0), which the advisory link leads to. +/// +public sealed class OsvVulnerabilitySource : IVulnerabilitySource +{ + private const int BatchSize = 500; + private const int MaxPages = 10; + + private readonly IOptionsSnapshot _options; + private readonly OsvState _state; + + public OsvVulnerabilitySource(IOptionsSnapshot options, OsvState state) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _state = state ?? throw new ArgumentNullException(nameof(state)); + } + + /// + public string Name => "osv"; + + /// + public async Task>> QueryAsync( + IReadOnlyCollection components, + CancellationToken cancellationToken) + { + var options = _options.Value; + var result = new Dictionary>(); + var distinct = components.Distinct().ToList(); + + if (!string.IsNullOrWhiteSpace(options.OsvOfflinePath)) + { + var index = await LoadOfflineAsync(options.OsvOfflinePath!, cancellationToken).ConfigureAwait(false); + foreach (var component in distinct) + { + result[component] = index.For(component) + .Select(a => a.Affects(component, out var fix) ? new VulnerabilityHit(a.Id, a.Summary, a.Severity, a.Url, fix) : null) + .Where(h => h != null) + .Select(h => h!) + .OrderByDescending(h => h.Severity) + .ThenBy(h => h.Id, StringComparer.Ordinal) + .ToList(); + } + + return result; + } + + var now = Environment.TickCount64; + var lifetime = (long)Math.Max(0, options.OsvCacheLifetime.TotalMilliseconds); + var todo = new List(); + foreach (var component in distinct) + { + if (_state.Answers.TryGetValue(component, out var cached) && cached.Expires > now) result[component] = cached.Hits; + else todo.Add(component); + } + + if (todo.Count == 0) return result; + + var ids = new Dictionary>(); + for (var offset = 0; offset < todo.Count; offset += BatchSize) + { + var chunk = todo.Skip(offset).Take(BatchSize).ToList(); + await QueryIdsAsync(options, chunk, ids, cancellationToken).ConfigureAwait(false); + } + + var needed = ids.Values.SelectMany(v => v).Distinct(StringComparer.Ordinal).Where(id => !_state.Advisories.ContainsKey(id)).ToList(); + using (var gate = new SemaphoreSlim(8)) + { + await Task.WhenAll(needed.Select(async id => + { + await gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + _state.Advisories[id] = await FetchAdvisoryAsync(options, id, cancellationToken).ConfigureAwait(false); + } + finally + { + gate.Release(); + } + })).ConfigureAwait(false); + } + + foreach (var component in todo) + { + var hits = new List(); + if (ids.TryGetValue(component, out var found)) + { + foreach (var id in found.Distinct(StringComparer.Ordinal)) + { + var advisory = _state.Advisories[id]; + if (advisory.Withdrawn) continue; + advisory.Affects(component, out var fix); + hits.Add(new VulnerabilityHit(advisory.Id, advisory.Summary, advisory.Severity, advisory.Url, fix)); + } + } + + IReadOnlyList ordered = hits.OrderByDescending(h => h.Severity).ThenBy(h => h.Id, StringComparer.Ordinal).ToList(); + result[component] = ordered; + _state.Answers[component] = (now + lifetime, ordered); + } + + return result; + } + + private async Task LoadOfflineAsync(string path, CancellationToken cancellationToken) + { + await _state.OfflineLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var now = Environment.TickCount64; + var current = _state.Offline; + if (current != null && current.Path == path && now - _state.OfflineCheckedAt < 30_000) return current; + + var stamp = OsvOfflineIndex.StampOf(path); + if (current == null || current.Path != path || current.Stamp != stamp) + { + try + { + current = await Task.Run(() => OsvOfflineIndex.Load(path), cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is InvalidDataException) + { + throw new ScanUnavailableException("The offline vulnerability data '" + path + "' cannot be read: " + e.Message, e); + } + + _state.Offline = current; + } + + _state.OfflineCheckedAt = now; + return current; + } + finally + { + _state.OfflineLock.Release(); + } + } + + private async Task QueryIdsAsync(ScanningOptions options, List chunk, Dictionary> ids, CancellationToken cancellationToken) + { + var pending = chunk.Select(c => (Component: c, Token: (string?)null)).ToList(); + for (var page = 0; page < MaxPages && pending.Count > 0; page++) + { + var body = new StringBuilder("{\"queries\":["); + for (var i = 0; i < pending.Count; i++) + { + if (i > 0) body.Append(','); + var (component, token) = pending[i]; + body.Append("{\"package\":{\"name\":").Append(JsonSerializer.Serialize(component.Name)) + .Append(",\"ecosystem\":").Append(JsonSerializer.Serialize(component.Ecosystem)) + .Append("},\"version\":").Append(JsonSerializer.Serialize(component.Version)); + if (token != null) body.Append(",\"page_token\":").Append(JsonSerializer.Serialize(token)); + body.Append('}'); + } + + body.Append("]}"); + + using var document = await SendAsync(options, HttpMethod.Post, "/v1/querybatch", body.ToString(), cancellationToken).ConfigureAwait(false); + if (!document.RootElement.TryGetProperty("results", out var results) || results.ValueKind != JsonValueKind.Array) + { + throw new ScanUnavailableException("OSV answered with an unexpected document."); + } + + var next = new List<(ScanComponent Component, string? Token)>(); + var j = 0; + foreach (var entry in results.EnumerateArray()) + { + if (j >= pending.Count) break; + var component = pending[j++].Component; + if (!ids.TryGetValue(component, out var list)) ids[component] = list = new List(); + + if (entry.ValueKind == JsonValueKind.Object && entry.TryGetProperty("vulns", out var vulns) && vulns.ValueKind == JsonValueKind.Array) + { + foreach (var vuln in vulns.EnumerateArray()) + { + if (vuln.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String) list.Add(id.GetString()!); + } + } + + if (entry.ValueKind == JsonValueKind.Object && entry.TryGetProperty("next_page_token", out var tokenValue) + && tokenValue.ValueKind == JsonValueKind.String && !string.IsNullOrEmpty(tokenValue.GetString())) + { + next.Add((component, tokenValue.GetString())); + } + } + + if (j < pending.Count) throw new ScanUnavailableException("OSV answered for fewer packages than asked."); + pending = next; + } + } + + private async Task FetchAdvisoryAsync(ScanningOptions options, string id, CancellationToken cancellationToken) + { + try + { + using var document = await SendAsync(options, HttpMethod.Get, "/v1/vulns/" + Uri.EscapeDataString(id), null, cancellationToken).ConfigureAwait(false); + var advisory = OsvAdvisory.Parse(document.RootElement); + if (advisory != null) return advisory; + } + catch (ScanUnavailableException e) when (e.Message.Contains("answered 404")) + { + // The record vanished between the two calls; the id alone is still worth reporting. + } + + using var minimal = JsonDocument.Parse("{\"id\":" + JsonSerializer.Serialize(id) + "}"); + return OsvAdvisory.Parse(minimal.RootElement)!; + } + + private async Task SendAsync(ScanningOptions options, HttpMethod method, string path, string? body, CancellationToken cancellationToken) + { + if (!Uri.TryCreate(options.OsvUrl?.TrimEnd('/') + path, UriKind.Absolute, out var uri) + || (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp)) + { + throw new ScanUnavailableException("Scanning:OsvUrl is not an absolute http(s) URL."); + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(options.OsvTimeout > TimeSpan.Zero ? options.OsvTimeout : TimeSpan.FromSeconds(30)); + try + { + using var request = new HttpRequestMessage(method, uri); + if (body != null) request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + using var response = await _state.Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + throw new ScanUnavailableException("OSV answered " + (int)response.StatusCode + " (" + response.StatusCode + ") for " + uri.AbsolutePath + "."); + } + + await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token).ConfigureAwait(false); + return await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new ScanUnavailableException("OSV did not answer in time."); + } + catch (HttpRequestException e) + { + throw new ScanUnavailableException("OSV cannot be reached: " + e.Message, e); + } + catch (JsonException e) + { + throw new ScanUnavailableException("OSV answered with a document that is not JSON.", e); + } + catch (System.IO.IOException e) + { + // A connection dropped while the body was read (HttpIOException is an IOException): the source is unavailable. + throw new ScanUnavailableException("OSV cannot be reached: " + e.Message, e); + } + } +} diff --git a/src/BaGet.Core/Scanning/ScanEntities.cs b/src/BaGet.Core/Scanning/ScanEntities.cs new file mode 100644 index 000000000..3ea265355 --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanEntities.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Core; + +/// +/// What the last scans of one artifact version found, in one repository (table ScanResults). The artifact is named the way +/// its format names it: NuGet package id (as stored), npm package name, Maven group:artifact, Docker image name; the +/// version is the package version, npm version, Maven version or the Docker manifest digest. A row exists once a scan was +/// attempted; there is no foreign key to the artifact (it may be deleted, and each format keeps its own tables), so stale rows are +/// dropped by the next sweep. +/// +public class ScanResult : IRepositoryScoped +{ + public int Key { get; set; } + + /// The owning repository; see . + public int RepositoryKey { get; set; } + + /// The artifact name (see the class remarks). At most ScanLimits.NameLength characters. + public string? Name { get; set; } + + /// The artifact version. At most ScanLimits.VersionLength characters. + public string? Version { get; set; } + + /// The scanner that produced the findings: osv or trivy. + public string? Scanner { get; set; } + + /// When the last scan succeeded (UTC); null when none ever did (the artifact counts as unscanned). + public DateTime? ScannedAt { get; set; } + + /// When a scan was last attempted (UTC). + public DateTime Attempted { get; set; } + + /// The scrubbed reason the last attempt failed, or null. The findings of the last success stay while this is set. + public string? Error { get; set; } + + /// The highest severity among (0 low … 3 critical), or -1 when there are none. + public int Highest { get; set; } = -1; + + /// How many findings the last success recorded. + public int FindingCount { get; set; } + + public List? Findings { get; set; } +} + +/// One vulnerability a scan found in an artifact or one of its components. +public class ScanFinding +{ + public int Key { get; set; } + + /// The . Required; deleting the result deletes its findings. + public int ResultKey { get; set; } + + /// The advisory id (GHSA-…, CVE-…), as the source names it. + public string? VulnerabilityId { get; set; } + + /// The component that is vulnerable: the artifact itself or one of its dependencies (package, OS package…). + public string? Component { get; set; } + + /// The version of . + public string? ComponentVersion { get; set; } + + /// 0 low, 1 moderate, 2 high, 3 critical (the numbering of NuGet's vulnerability resource). + public int Severity { get; set; } + + /// A one-line description from the source, or null. + public string? Summary { get; set; } + + /// Where the advisory is described (an absolute http(s) URL). + public string? AdvisoryUrl { get; set; } + + /// The first version that fixes it, when the source says. + public string? FixedVersion { get; set; } +} + +/// +/// What a repository (or a project's repositories) does about findings: a threshold severity per action, or none (null) for +/// the action. A repository's own policy wins over its project's. Exactly one of and +/// is set. +/// +public class ScanPolicy +{ + public int Key { get; set; } + + /// The repository this policy is for, or null for a project policy. + public int? RepositoryKey { get; set; } + + /// The project this policy is for, or null for a repository policy. + public int? ProjectKey { get; set; } + + /// Findings at or above this severity (0..3) are shown as a warning. Null: no warning. + public int? WarnSeverity { get; set; } + + /// A version with a finding at or above this severity cannot be downloaded (403 with the reason). Null: never. + public int? BlockDownloadSeverity { get; set; } + + /// A deploy whose artifact or declared dependencies have a finding at or above this severity is refused (403). Null: never. + public int? BlockDeploySeverity { get; set; } + + /// Whether a version that has not been scanned (yet, or at all) cannot be downloaded. + public bool BlockUnscanned { get; set; } + + /// When the policy was last saved (UTC). + public DateTime Modified { get; set; } + + /// The administrator who saved it, or null. + public string? ModifiedBy { get; set; } +} diff --git a/src/BaGet.Core/Scanning/ScanGate.cs b/src/BaGet.Core/Scanning/ScanGate.cs new file mode 100644 index 000000000..3d6c1dc43 --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanGate.cs @@ -0,0 +1,411 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// What a policy refused. +public enum ScanBlockedOperation +{ + /// A download of a version with findings (or not scanned). + Download, + + /// A deploy of an artifact with findings. + Deploy, +} + +/// +/// The scanning policy of a repository refuses an operation. Answered as 403 with as the +/// reason on every format's routes and pages (ScanBlockedFilter). +/// +public sealed class ScanBlockedException : Exception +{ + public ScanBlockedException(ScanBlockedOperation operation, string reason) + : base(reason) + { + Operation = operation; + } + + /// What was refused. + public ScanBlockedOperation Operation { get; } +} + +/// The state of one version as the pages show it. +public enum ScanState +{ + /// Scanning is off or not possible for the repository (see ). + Unavailable, + + /// No successful scan yet. + NotScanned, + + /// Scanned, nothing found. + Clean, + + /// Scanned, at least one finding. + Findings, +} + +/// What the pages know about a version: its result and what the policy does with it. +/// The state. +/// The stored result with its findings, or null. +/// The policy in force. +/// Whether the policy asks for a warning. +/// Why downloads are refused, or null when they are not. +/// Why the version cannot be scanned or has not been, when that is known. +public sealed record ScanAssessment(ScanState State, ScanResult? Result, EffectiveScanPolicy Policy, bool Warn, string? BlockReason, string? Note); + +/// +/// Applies the scanning policy of the repository of the request. Scoped. A format's routes and pages call +/// before they hand an artifact out and before they store one; +/// both are free (one cached lookup) when no policy asks for anything. +/// +public interface IScanGate +{ + /// Whether scanning is on and possible here (a cheap test; callers skip reading an artifact for scanning when false). + bool Enabled { get; } + + /// Whether the policy in force refuses deploys at some severity (callers read the artifact's components only then). + Task BlocksDeploysAsync(CancellationToken cancellationToken); + + /// + /// Whether a pull of the image is the scanning engine's own (Trivy pulls the image it scans through this registry): the caller is + /// (exempt from entirely, so rescans of images + /// with findings still work), or, when no user is configured and so the scanner cannot be told from any other client, a scan of + /// that very image is running and the image has no successful scan yet. The second case only lets an unscanned image be + /// scanned; it never lifts the severity block of an image already known to be vulnerable. + /// + Task IsScannerPullAsync(string name, string version, string? callerName, CancellationToken cancellationToken); + + /// Throws when the policy refuses to hand out the version. + Task CheckDownloadAsync(string name, string version, CancellationToken cancellationToken); + + /// + /// Throws when the policy refuses to store an artifact made of + /// (itself and its declared dependencies). A source that cannot answer lets the deploy through + /// (logged): a security tool that is down must not stop every push. + /// + Task CheckDeployAsync(IReadOnlyList components, CancellationToken cancellationToken); + + /// + /// For artifacts that cannot be inspected before they are stored (container images): scans the stored version now and throws + /// when its findings reach the policy's deploy threshold, so the caller can remove it again. + /// Without a deploy threshold, or without a scanner for the format, it only queues a scan. + /// + Task CheckStoredAsync(string name, string version, CancellationToken cancellationToken); + + /// The state and the policy's verdict for a version, for the pages. + Task AssessAsync(string name, string version, CancellationToken cancellationToken); + + /// Queues a scan of a version that was just stored (no-op when scanning is off). + void RequestScan(string name, string version); + + /// + /// What every store path calls once an artifact is stored: forgets the result of an earlier artifact of the same name and + /// version (it describes other bytes, and would count as a scan for "block unscanned") and then . + /// A failure to forget is logged, never thrown: the artifact is already stored. false (a file the + /// scanner does not read, e.g. a Maven classifier jar) keeps the result and only queues a scan. + /// + Task RegisterStoredAsync(string name, string version, CancellationToken cancellationToken, bool contentChanged = true); +} + +/// The scoped . +public sealed class ScanGate : IScanGate +{ + private readonly IScanService _scans; + private readonly IScanPolicyService _policies; + private readonly IRepositoryContext _repository; + private readonly IServiceScopeFactory _scopes; + private readonly IOptionsSnapshot _options; + private readonly ScanQueue _queue; + private readonly IContext _context; + private readonly IVirtualRepositories _virtuals; + private readonly ILogger _logger; + private readonly ClusterRuntime? _cluster; + private readonly VirtualRepositoryReader? _reader; + private readonly IOciRequestAccess? _ociAccess; + + public ScanGate( + IScanService scans, + IScanPolicyService policies, + IRepositoryContext repository, + IServiceScopeFactory scopes, + IOptionsSnapshot options, + ScanQueue queue, + IContext context, + IVirtualRepositories virtuals, + ILogger logger, + ClusterRuntime? cluster = null, + VirtualRepositoryReader? reader = null, + IOciRequestAccess? ociAccess = null) + { + _ociAccess = ociAccess; + _cluster = cluster; + _reader = reader; + _scans = scans ?? throw new ArgumentNullException(nameof(scans)); + _policies = policies ?? throw new ArgumentNullException(nameof(policies)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private bool Active => _options.Value.Enabled && _context is not NullContext; + + /// + public bool Enabled => Active; + + /// + public async Task BlocksDeploysAsync(CancellationToken cancellationToken) + => Active && (await _policies.GetEffectiveAsync(_repository.Current.Key, cancellationToken).ConfigureAwait(false)).Values.BlockDeploySeverity != null; + + /// + public async Task IsScannerPullAsync(string name, string version, string? callerName, CancellationToken cancellationToken) + { + if (!Active) return false; + + var user = _options.Value.TrivyRegistryUser; + if (!string.IsNullOrWhiteSpace(user)) + { + return callerName != null && string.Equals(callerName, user.Trim(), StringComparison.OrdinalIgnoreCase); + } + + if (!await ScanInFlight.ContainsAsync(_repository.Current.Key, name, version, _cluster?.Store, cancellationToken).ConfigureAwait(false)) return false; + + // Any client could be the one pulling during the scan, so only the unscanned case (the "block unscanned" check) is lifted. + var result = await _scans.FindAsync(name, version, cancellationToken).ConfigureAwait(false); + return result?.ScannedAt == null; + } + + /// + public async Task CheckDownloadAsync(string name, string version, CancellationToken cancellationToken) + { + if (!Active) return; + + var repository = _repository.Current; + if (repository.Kind == RepositoryKind.Virtual) + { + // The member that holds the version answers; one with no result for it is unscanned and says nothing. Only the members + // the caller can read count, as on the content path (which serves the first of them): judging a member the caller cannot + // read would let another member's copy through on its verdict. + // A Docker pull is judged like the registry judges it (IOciRequestAccess: the registry token's grants or the key), since + // the caller of the reader cannot see a registry token and would look anonymous. + IReadOnlyList members; + if (repository.Format == RepositoryFormat.Docker && _ociAccess != null) + { + var all = await _virtuals.EffectiveMembersAsync(repository, cancellationToken).ConfigureAwait(false); + var allowed = new List(); + foreach (var candidate in all) + { + if (await _ociAccess.CanPullAsync(candidate, name, cancellationToken).ConfigureAwait(false)) allowed.Add(candidate); + } + + members = allowed; + } + else + { + members = _reader != null + ? await _reader.ReadableMembersAsync(name, cancellationToken).ConfigureAwait(false) + : await _virtuals.EffectiveMembersAsync(repository, cancellationToken).ConfigureAwait(false); + } + + foreach (var member in members) + { + using var scope = _scopes.CreateRepositoryScope(member); + var memberGate = (ScanGate)scope.ServiceProvider.GetRequiredService(); + if (await memberGate.CheckDownloadCoreAsync(name, version, requireResult: true, cancellationToken).ConfigureAwait(false)) return; + } + + return; + } + + await CheckDownloadCoreAsync(name, version, requireResult: false, cancellationToken).ConfigureAwait(false); + } + + /// True when this repository had a result for the version (virtual lookups stop at the first that does). + private async Task CheckDownloadCoreAsync(string name, string version, bool requireResult, CancellationToken cancellationToken) + { + var repository = _repository.Current; + var policy = await _policies.GetEffectiveAsync(repository.Key, cancellationToken).ConfigureAwait(false); + var values = policy.Values; + var result = await _scans.FindAsync(name, version, cancellationToken).ConfigureAwait(false); + + // A virtual lookup stops at the member that holds the version: one with a result, or one that stores it without having + // scanned it (its own "block unscanned" then applies). + var stored = result != null; + async Task HoldsAsync() + { + if (!stored) stored = await _scans.IsStoredAsync(name, version, cancellationToken).ConfigureAwait(false); + return stored; + } + + if (values.BlockDownloadSeverity == null && !values.BlockUnscanned) + { + return requireResult && await HoldsAsync().ConfigureAwait(false); + } + + if (result?.ScannedAt == null) + { + if (requireResult && !await HoldsAsync().ConfigureAwait(false)) return false; + Enqueue(name, version); + + // Without an engine nothing can ever be scanned, so refusing would be for good (the pages say nothing is blocked then). + // What a remote repository has not fetched yet cannot be scanned, and it is fetched by this very download: refusing it + // would keep it from ever being scanned. It is scanned as soon as it is stored. + if (values.BlockUnscanned && _scans.GetEngineStatus().Available && await HoldsAsync().ConfigureAwait(false)) + { + throw new ScanBlockedException(ScanBlockedOperation.Download, + $"Download of {name} {version} refused by the scanning policy of {Describe(policy, repository)}: it has not been scanned yet. Try again shortly."); + } + + return stored; + } + + var reason = DownloadReason(name, version, result, policy, repository); + if (reason != null) throw new ScanBlockedException(ScanBlockedOperation.Download, reason); + return true; + } + + /// + public async Task CheckDeployAsync(IReadOnlyList components, CancellationToken cancellationToken) + { + if (!Active || components.Count == 0) return; + + var repository = _repository.Current; + var policy = await _policies.GetEffectiveAsync(repository.Key, cancellationToken).ConfigureAwait(false); + var threshold = policy.Values.BlockDeploySeverity; + if (threshold == null) return; + + IReadOnlyList hits; + try + { + hits = await _scans.CheckAsync(components, cancellationToken).ConfigureAwait(false); + } + catch (ScanUnavailableException e) + { + _logger.LogWarning("Deploy to {Repository} not checked against the scanning policy: {Reason}", repository.Name, e.Message); + return; + } + + var blocking = hits.Where(h => h.Severity >= threshold.Value).OrderByDescending(h => h.Severity).ThenBy(h => h.Id, StringComparer.Ordinal).ToList(); + if (blocking.Count == 0) return; + + throw new ScanBlockedException(ScanBlockedOperation.Deploy, + $"Deploy refused by the scanning policy of {Describe(policy, repository)} (blocks {ScanSeverities.Name(threshold.Value)} and above): {Summarize(blocking)}."); + } + + /// + public async Task CheckStoredAsync(string name, string version, CancellationToken cancellationToken) + { + if (!Active) return; + + var repository = _repository.Current; + var policy = await _policies.GetEffectiveAsync(repository.Key, cancellationToken).ConfigureAwait(false); + var threshold = policy.Values.BlockDeploySeverity; + if (threshold == null || !_scans.GetEngineStatus().Available) + { + RequestScan(name, version); + return; + } + + + var result = await _scans.ScanAsync(name, version, cancellationToken).ConfigureAwait(false); + if (result?.ScannedAt == null || result.Highest < threshold.Value) return; + + var blocking = (result.Findings ?? new List()) + .Where(f => f.Severity >= threshold.Value) + .OrderByDescending(f => f.Severity) + .ThenBy(f => f.VulnerabilityId, StringComparer.Ordinal) + .Select(f => new ScanHit(f.VulnerabilityId!, f.Component!, f.ComponentVersion!, f.Severity, f.Summary, f.AdvisoryUrl ?? string.Empty, f.FixedVersion)) + .ToList(); + throw new ScanBlockedException(ScanBlockedOperation.Deploy, + $"Deploy refused by the scanning policy of {Describe(policy, repository)} (blocks {ScanSeverities.Name(threshold.Value)} and above): {Summarize(blocking)}."); + } + + /// + public async Task AssessAsync(string name, string version, CancellationToken cancellationToken) + { + var repository = _repository.Current; + var status = _scans.GetEngineStatus(); + var policy = _context is NullContext ? EffectiveScanPolicy.None : await _policies.GetEffectiveAsync(repository.Key, cancellationToken).ConfigureAwait(false); + var result = _context is NullContext ? null : await _scans.FindAsync(name, version, cancellationToken).ConfigureAwait(false); + + if (result?.ScannedAt == null) + { + var note = result?.Error != null ? "The last scan failed: " + result.Error : status.Available ? null : status.Reason; + string? block = null; + if (Active && status.Available && policy.Values.BlockUnscanned) + { + block = $"Not scanned yet; the policy of {Describe(policy, repository)} refuses downloads of unscanned versions."; + } + + return new ScanAssessment(status.Available || result?.Error != null ? ScanState.NotScanned : ScanState.Unavailable, result, policy, false, block, note); + } + + var warn = policy.Values.WarnSeverity != null && result.Highest >= policy.Values.WarnSeverity.Value; + var reason = Active ? DownloadReason(name, version, result, policy, repository) : null; + return new ScanAssessment(result.FindingCount > 0 ? ScanState.Findings : ScanState.Clean, result, policy, warn, reason, result.Error != null ? "The last rescan failed: " + result.Error : null); + } + + /// + public void RequestScan(string name, string version) + { + if (Active && _options.Value.ScanOnDeploy) Enqueue(name, version); + } + + /// + public async Task RegisterStoredAsync(string name, string version, CancellationToken cancellationToken, bool contentChanged = true) + { + if (Active && contentChanged) + { + try + { + await _scans.ForgetAsync(name, version, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException) + { + _logger.LogWarning(e, "The earlier scan result of {Name} {Version} could not be forgotten", name, version); + } + } + + RequestScan(name, version); + } + + private void Enqueue(string name, string version) + { + if (Active) _queue.Enqueue(_repository.Current, name, version); + } + + private static string? DownloadReason(string name, string version, ScanResult result, EffectiveScanPolicy policy, RepositoryInfo repository) + { + var threshold = policy.Values.BlockDownloadSeverity; + if (threshold == null || result.Highest < threshold.Value) return null; + + var blocking = (result.Findings ?? new List()) + .Where(f => f.Severity >= threshold.Value) + .OrderByDescending(f => f.Severity) + .ThenBy(f => f.VulnerabilityId, StringComparer.Ordinal) + .Select(f => new ScanHit(f.VulnerabilityId!, f.Component!, f.ComponentVersion!, f.Severity, f.Summary, f.AdvisoryUrl ?? string.Empty, f.FixedVersion)) + .ToList(); + var detail = blocking.Count > 0 ? Summarize(blocking) : $"its highest finding is {ScanSeverities.Name(result.Highest)}"; + return $"Download of {name} {version} refused by the scanning policy of {Describe(policy, repository)} (blocks {ScanSeverities.Name(threshold.Value)} and above): {detail}."; + } + + private static string Describe(EffectiveScanPolicy policy, RepositoryInfo repository) + => policy.From == ScanPolicyScope.Project ? $"repository '{repository.Name}' (project '{policy.Name}')" : $"repository '{repository.Name}'"; + + private static string Summarize(IReadOnlyList hits) + { + var shown = hits.Take(3).Select(h => $"{h.Component} {h.ComponentVersion}: {ScanSeverities.Name(h.Severity)} {h.Id}").ToList(); + var more = hits.Count > shown.Count ? $" and {hits.Count - shown.Count} more" : string.Empty; + return string.Join("; ", shown) + more; + } +} diff --git a/src/BaGet.Core/Scanning/ScanInFlight.cs b/src/BaGet.Core/Scanning/ScanInFlight.cs new file mode 100644 index 000000000..e97ed1477 --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanInFlight.cs @@ -0,0 +1,72 @@ +using System.Collections.Concurrent; + +namespace BaGet.Core; + +/// +/// The container images being scanned right now, process-wide: the scanner pulls the image through this registry, and that pull must +/// not be refused as "unscanned" (see ). +/// In memory per process; in a cluster (Ha:Enabled) each image is also marked in the shared store, so the node that receives the +/// scanner's pull sees a scan another node started (set to avoid depending on it). +/// +internal static class ScanInFlight +{ + private static readonly ConcurrentDictionary<(int, string, string), int> Running = new(); + + /// How long a shared mark lasts if its node dies mid-scan. + private static readonly System.TimeSpan SharedTtl = System.TimeSpan.FromMinutes(30); + + private static string SharedKey(int repositoryKey, string name, string version) => $"scan-inflight:{repositoryKey}:{name}:{version}"; + + public static bool Contains(int repositoryKey, string name, string version) => Running.ContainsKey((repositoryKey, name, version)); + + /// Whether the image is being scanned here or, with a shared store, on any node. + public static async System.Threading.Tasks.Task ContainsAsync(int repositoryKey, string name, string version, IClusterStore? shared, System.Threading.CancellationToken cancellationToken) + { + if (Contains(repositoryKey, name, version)) return true; + + return shared != null && await shared.GetAsync(SharedKey(repositoryKey, name, version), cancellationToken).ConfigureAwait(false) != null; + } + + /// Marks the image as being scanned until the returned handle is disposed. + public static System.IDisposable Begin(int repositoryKey, string name, string version, IClusterStore? shared = null) + { + var key = (repositoryKey, name, version); + Running.AddOrUpdate(key, 1, (_, n) => n + 1); + if (shared != null) + { + try { shared.Set(SharedKey(repositoryKey, name, version), "1", SharedTtl); } + catch (System.Exception) { /* the local mark still covers a pull that reaches this node */ } + } + + return new Handle(key, shared); + } + + private sealed class Handle : System.IDisposable + { + private readonly (int, string, string) _key; + private readonly IClusterStore? _shared; + private int _done; + + public Handle((int, string, string) key, IClusterStore? shared) + { + _key = key; + _shared = shared; + } + + public void Dispose() + { + if (System.Threading.Interlocked.Exchange(ref _done, 1) != 0) return; + + if (_shared != null) + { + try { _shared.Delete(SharedKey(_key.Item1, _key.Item2, _key.Item3)); } + catch (System.Exception) { /* expires by itself */ } + } + + while (Running.TryGetValue(_key, out var n)) + { + if (n <= 1 ? Running.TryRemove(new System.Collections.Generic.KeyValuePair<(int, string, string), int>(_key, n)) : Running.TryUpdate(_key, n - 1, n)) break; + } + } + } +} diff --git a/src/BaGet.Core/Scanning/ScanLimits.cs b/src/BaGet.Core/Scanning/ScanLimits.cs new file mode 100644 index 000000000..d60607b9a --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanLimits.cs @@ -0,0 +1,13 @@ +namespace BaGet.Core; + +/// Column lengths of the scanning tables (shared by the model and the code that truncates to them). +public static class ScanLimits +{ + public const int NameLength = 400; + public const int VersionLength = 200; + public const int IdLength = 200; + public const int SummaryLength = 1000; + public const int UrlLength = 1000; + public const int ErrorLength = 1000; + public const int ScannerLength = 32; +} diff --git a/src/BaGet.Core/Scanning/ScanPolicyService.cs b/src/BaGet.Core/Scanning/ScanPolicyService.cs new file mode 100644 index 000000000..49bb400f3 --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanPolicyService.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +/// What a policy is attached to. +public enum ScanPolicyScope +{ + /// One repository. + Repository, + + /// Every repository of a project that has no policy of its own. + Project, +} + +/// The thresholds of a policy; null disables the action. +/// Show a warning from this severity (0 low … 3 critical). +/// Refuse downloads from this severity. +/// Refuse deploys from this severity. +/// Refuse downloads of versions that were not scanned. +public sealed record ScanPolicyValues(int? WarnSeverity, int? BlockDownloadSeverity, int? BlockDeploySeverity, bool BlockUnscanned) +{ + /// Whether nothing is enabled. + public bool IsEmpty => WarnSeverity == null && BlockDownloadSeverity == null && BlockDeploySeverity == null && !BlockUnscanned; + + /// The first problem with the thresholds, or null. + public string? Validate() + { + foreach (var (label, value) in new[] { ("warn", WarnSeverity), ("block download", BlockDownloadSeverity), ("block deploy", BlockDeploySeverity) }) + { + if (value != null && (value < 0 || value > PackageVulnerabilityRules.MaxSeverity)) + { + return $"The {label} severity must be between 0 (low) and {PackageVulnerabilityRules.MaxSeverity} (critical)."; + } + } + + return null; + } +} + +/// The policy in force for a repository: its own, else its project's, else none. +/// The thresholds; when no policy applies. +/// Where it comes from, or null when none applies. +/// The repository or project name it is stored for, or null. +public sealed record EffectiveScanPolicy(ScanPolicyValues Values, ScanPolicyScope? From, string? Name) +{ + /// No policy. + public static EffectiveScanPolicy None { get; } = new(new ScanPolicyValues(null, null, null, false), null, null); +} + +/// Reads and edits the scanning policies. Scoped; authorizes nothing. +public interface IScanPolicyService +{ + /// The policy in force for the repository (remembered for a few seconds). + Task GetEffectiveAsync(int repositoryKey, CancellationToken cancellationToken); + + /// The policy stored for a repository or project, or null. + Task GetAsync(ScanPolicyScope scope, int key, CancellationToken cancellationToken); + + /// Saves the policy of a repository or project; empty values delete it. Audited; refused while the database is read-only. + /// A threshold is outside 0..3, or the repository or project does not exist. + Task SaveAsync(ScanPolicyScope scope, int key, ScanPolicyValues values, string? actor, CancellationToken cancellationToken); +} + +/// Remembers effective policies for a few seconds, so a download costs no query when a policy is in force or not. +public sealed class ScanPolicyCache +{ + private static readonly long Lifetime = 5_000; + private readonly ConcurrentDictionary _entries = new(); + + internal bool TryGet(int repositoryKey, out EffectiveScanPolicy policy) + { + if (_entries.TryGetValue(repositoryKey, out var entry) && entry.Expires > Environment.TickCount64) + { + policy = entry.Policy; + return true; + } + + policy = EffectiveScanPolicy.None; + return false; + } + + internal void Set(int repositoryKey, EffectiveScanPolicy policy) => _entries[repositoryKey] = (Environment.TickCount64 + Lifetime, policy); + + /// Forgets everything (after a policy was saved on this node). + public void Clear() => _entries.Clear(); +} + +/// The scoped . +public sealed class ScanPolicyService : IScanPolicyService +{ + private readonly IContext _context; + private readonly ScanPolicyCache _cache; + private readonly MaintenanceGate _gate; + private readonly SystemTime _time; + private readonly IAdminAudit _audit; + + public ScanPolicyService(IContext context, ScanPolicyCache cache, MaintenanceGate gate, SystemTime time, IAdminAudit audit) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _cache = cache ?? throw new ArgumentNullException(nameof(cache)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _audit = audit ?? throw new ArgumentNullException(nameof(audit)); + } + + /// + public async Task GetEffectiveAsync(int repositoryKey, CancellationToken cancellationToken) + { + if (_context is NullContext) return EffectiveScanPolicy.None; + if (_cache.TryGet(repositoryKey, out var cached)) return cached; + + var repository = await _context.Repositories!.AsNoTracking().FirstOrDefaultAsync(r => r.Key == repositoryKey, cancellationToken).ConfigureAwait(false); + var effective = EffectiveScanPolicy.None; + if (repository != null) + { + var own = await _context.ScanPolicies!.AsNoTracking().FirstOrDefaultAsync(p => p.RepositoryKey == repositoryKey, cancellationToken).ConfigureAwait(false); + if (own != null) + { + effective = new EffectiveScanPolicy(ToValues(own), ScanPolicyScope.Repository, repository.Name); + } + else if (repository.ProjectKey != null) + { + var projectKey = repository.ProjectKey.Value; + var project = await _context.ScanPolicies!.AsNoTracking().FirstOrDefaultAsync(p => p.ProjectKey == projectKey, cancellationToken).ConfigureAwait(false); + if (project != null) + { + var projectName = await _context.Projects!.AsNoTracking().Where(p => p.Key == projectKey).Select(p => p.Name).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + effective = new EffectiveScanPolicy(ToValues(project), ScanPolicyScope.Project, projectName); + } + } + } + + _cache.Set(repositoryKey, effective); + return effective; + } + + /// + public async Task GetAsync(ScanPolicyScope scope, int key, CancellationToken cancellationToken) + { + if (_context is NullContext) return null; + return scope == ScanPolicyScope.Repository + ? await _context.ScanPolicies!.AsNoTracking().FirstOrDefaultAsync(p => p.RepositoryKey == key, cancellationToken).ConfigureAwait(false) + : await _context.ScanPolicies!.AsNoTracking().FirstOrDefaultAsync(p => p.ProjectKey == key, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task SaveAsync(ScanPolicyScope scope, int key, ScanPolicyValues values, string? actor, CancellationToken cancellationToken) + { + if (values == null) throw new ArgumentNullException(nameof(values)); + _gate.ThrowIfClosed(); + var error = values.Validate(); + if (error != null) throw new ArgumentException(error, nameof(values)); + + string subject; + if (scope == ScanPolicyScope.Repository) + { + var name = await _context.Repositories!.AsNoTracking().Where(r => r.Key == key).Select(r => r.Name).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (name == null) throw new ArgumentException("The repository does not exist.", nameof(key)); + subject = "repository " + name; + } + else + { + var name = await _context.Projects!.AsNoTracking().Where(p => p.Key == key).Select(p => p.Name).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (name == null) throw new ArgumentException("The project does not exist.", nameof(key)); + subject = "project " + name; + } + + var row = scope == ScanPolicyScope.Repository + ? await _context.ScanPolicies!.FirstOrDefaultAsync(p => p.RepositoryKey == key, cancellationToken).ConfigureAwait(false) + : await _context.ScanPolicies!.FirstOrDefaultAsync(p => p.ProjectKey == key, cancellationToken).ConfigureAwait(false); + + if (values.IsEmpty) + { + if (row != null) + { + _context.ScanPolicies!.Remove(row); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + _cache.Clear(); + _audit.Record(actor, "scan-policy.delete", subject); + return; + } + + if (row == null) + { + row = new ScanPolicy(); + if (scope == ScanPolicyScope.Repository) row.RepositoryKey = key; + else row.ProjectKey = key; + _context.ScanPolicies!.Add(row); + } + + row.WarnSeverity = values.WarnSeverity; + row.BlockDownloadSeverity = values.BlockDownloadSeverity; + row.BlockDeploySeverity = values.BlockDeploySeverity; + row.BlockUnscanned = values.BlockUnscanned; + row.Modified = _time.UtcNow; + row.ModifiedBy = actor == null ? null : (actor.Length > AbstractContext.MaxAccountNameLength ? actor.Substring(0, AbstractContext.MaxAccountNameLength) : actor); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + _cache.Clear(); + _audit.Record(actor, "scan-policy.save", subject, + $"warn={Show(values.WarnSeverity)}, block download={Show(values.BlockDownloadSeverity)}, block deploy={Show(values.BlockDeploySeverity)}, block unscanned={values.BlockUnscanned}"); + } + + private static string Show(int? severity) => severity == null ? "off" : ScanSeverities.Name(severity.Value); + + private static ScanPolicyValues ToValues(ScanPolicy policy) + => new(policy.WarnSeverity, policy.BlockDownloadSeverity, policy.BlockDeploySeverity, policy.BlockUnscanned); +} diff --git a/src/BaGet.Core/Scanning/ScanService.cs b/src/BaGet.Core/Scanning/ScanService.cs new file mode 100644 index 000000000..f44c03f1c --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanService.cs @@ -0,0 +1,480 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// The scoped . +public sealed class ScanService : IScanService +{ + /// The most findings kept for one version (worst first); a big image can have thousands. + public const int MaxFindingsPerResult = 1000; + + private readonly IContext _context; + private readonly IRepositoryContext _repository; + private readonly IServiceProvider _services; + private readonly IOptionsSnapshot _options; + private readonly IVulnerabilitySource _source; + private readonly ITrivyRunner _trivy; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ILogger _logger; + private readonly ClusterRuntime? _cluster; + + public ScanService( + IContext context, + IRepositoryContext repository, + IServiceProvider services, + IOptionsSnapshot options, + IVulnerabilitySource source, + ITrivyRunner trivy, + SystemTime time, + MaintenanceGate gate, + ILogger logger, + ClusterRuntime? cluster = null) + { + _cluster = cluster; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _source = source ?? throw new ArgumentNullException(nameof(source)); + _trivy = trivy ?? throw new ArgumentNullException(nameof(trivy)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private ScanningOptions Options => _options.Value; + + private RepositoryInfo Repository => _repository.Current; + + /// + public ScanEngineStatus GetEngineStatus() + { + if (!Options.Enabled) return new ScanEngineStatus(false, null, "Scanning is turned off (Scanning:Enabled)."); + if (_context is NullContext) return new ScanEngineStatus(false, null, "Scanning needs a relational database; this installation keeps packages in Azure Table Storage."); + if (Repository.Kind == RepositoryKind.Virtual) return new ScanEngineStatus(false, null, "A virtual repository holds no artifacts; scan its member repositories."); + + var scanner = _services.GetFormatService(Repository.Format); + if (scanner == null) return new ScanEngineStatus(false, null, "This format cannot be scanned."); + + if (scanner.Engine == ScanEngine.Image) + { + return _trivy.IsConfigured(Options) + ? new ScanEngineStatus(true, "Trivy", null) + : new ScanEngineStatus(false, null, "Trivy is not configured (Scanning:TrivyPath and Scanning:TrivyRegistryHost): container images are not scanned."); + } + + return new ScanEngineStatus(true, string.IsNullOrWhiteSpace(Options.OsvOfflinePath) ? "OSV.dev" : "OSV (offline copy)", null); + } + + /// + public async Task IsStoredAsync(string name, string version, CancellationToken cancellationToken) + { + var scanner = _services.GetFormatService(Repository.Format); + if (scanner == null || _context is NullContext) return false; + + return scanner.Engine == ScanEngine.Osv + ? (await scanner.ListComponentsAsync(name, version, cancellationToken).ConfigureAwait(false)).Count > 0 + : await scanner.GetImageReferenceAsync(name, version, cancellationToken).ConfigureAwait(false) != null; + } + + /// + public async Task FindAsync(string name, string version, CancellationToken cancellationToken) + { + if (_context is NullContext) return null; + var key = Normalize(name, version); + if (key == null) return null; + + var result = await _context.ScanResults! + .AsNoTracking() + .Include(r => r.Findings) + .AsSplitQuery() + .FirstOrDefaultAsync(r => r.Name == key.Value.Name && r.Version == key.Value.Version, cancellationToken) + .ConfigureAwait(false); + result?.Findings?.Sort((a, b) => + { + var bySeverity = b.Severity.CompareTo(a.Severity); + return bySeverity != 0 ? bySeverity : string.CompareOrdinal(a.VulnerabilityId, b.VulnerabilityId); + }); + return result; + } + + /// + public async Task ForgetAsync(string name, string version, CancellationToken cancellationToken) + { + if (_context is NullContext) return; + var key = Normalize(name, version); + if (key == null) return; + + await RemoveAsync(key.Value.Name, key.Value.Version, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task ScanAsync(string name, string version, CancellationToken cancellationToken) + { + _gate.ThrowIfClosed(); + var status = GetEngineStatus(); + if (!status.Available) throw new ScanUnavailableException(status.Reason ?? "Scanning is not available."); + + var key = Normalize(name, version); + if (key == null) return null; + var (normalizedName, normalizedVersion) = key.Value; + + var scanner = _services.GetFormatService(Repository.Format)!; + IReadOnlyList hits; + string scannerName; + try + { + if (scanner.Engine == ScanEngine.Osv) + { + scannerName = _source.Name; + var components = await scanner.ListComponentsAsync(name, version, cancellationToken).ConfigureAwait(false); + if (components.Count == 0) + { + await RemoveAsync(normalizedName, normalizedVersion, cancellationToken).ConfigureAwait(false); + return null; + } + + var answers = await _source.QueryAsync(components, cancellationToken).ConfigureAwait(false); + hits = answers + .SelectMany(kv => kv.Value.Select(h => new ScanHit(h.Id, kv.Key.Name, kv.Key.Version, h.Severity, h.Summary, h.Url, h.FixedVersion))) + .ToList(); + } + else + { + scannerName = "trivy"; + var reference = await scanner.GetImageReferenceAsync(name, version, cancellationToken).ConfigureAwait(false); + if (reference == null) + { + await RemoveAsync(normalizedName, normalizedVersion, cancellationToken).ConfigureAwait(false); + return null; + } + + using var inFlight = ScanInFlight.Begin(Repository.Key, name, version, _cluster?.Store); + hits = await _trivy.ScanImageAsync(Options, Options.TrivyRegistryHost!.Trim().TrimEnd('/') + "/" + Repository.Name + "/" + reference, cancellationToken).ConfigureAwait(false); + } + } + catch (ScanUnavailableException e) + { + _logger.LogWarning("Scan of {Name} {Version} in {Repository} failed: {Reason}", name, version, Repository.Name, e.Message); + var scannerOfFormat = scanner.Engine == ScanEngine.Osv ? _source.Name : "trivy"; + return await StoreFailureAsync(normalizedName, normalizedVersion, scannerOfFormat, e.Message, cancellationToken).ConfigureAwait(false); + } + + return await StoreAsync(normalizedName, normalizedVersion, scannerName, hits, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task ScanRepositoryAsync(bool onlyStale, CancellationToken cancellationToken) + { + var status = GetEngineStatus(); + if (!status.Available) throw new ScanUnavailableException(status.Reason ?? "Scanning is not available."); + + var scanner = _services.GetFormatService(Repository.Format)!; + var artifacts = await scanner.ListArtifactsAsync(cancellationToken).ConfigureAwait(false); + var existing = await _context.ScanResults! + .AsNoTracking() + .Select(r => new { r.Name, r.Version, r.ScannedAt, r.Attempted }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + var known = existing.ToDictionary(r => (r.Name!, r.Version!)); + + // Stale results: the artifact was deleted since. + var current = new HashSet<(string, string)>(); + foreach (var artifact in artifacts) + { + var key = Normalize(artifact.Name, artifact.Version); + if (key != null) current.Add((key.Value.Name, key.Value.Version)); + } + + var removed = 0; + foreach (var gone in known.Keys.Where(k => !current.Contains(k)).ToList()) + { + _gate.ThrowIfClosed(); + await RemoveAsync(gone.Item1, gone.Item2, cancellationToken).ConfigureAwait(false); + removed++; + } + + var now = _time.UtcNow; + var interval = Options.RescanInterval; + int scanned = 0, skipped = 0, failed = 0, withFindings = 0; + foreach (var artifact in artifacts) + { + cancellationToken.ThrowIfCancellationRequested(); + var key = Normalize(artifact.Name, artifact.Version); + if (key == null) continue; + + if (onlyStale && known.TryGetValue((key.Value.Name, key.Value.Version), out var row)) + { + var fresh = row.ScannedAt != null && interval > TimeSpan.Zero && now - row.ScannedAt.Value < interval; + // A failed attempt is retried after a short pause, not on every sweep. + var retryLater = row.ScannedAt == null && now - row.Attempted < TimeSpan.FromMinutes(10); + if (fresh || retryLater) + { + skipped++; + continue; + } + } + + ScanResult? result; + try + { + result = await ScanAsync(artifact.Name, artifact.Version, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) when (e is not OperationCanceledException && e is not MaintenanceException) + { + // One bad artifact must not end the sweep of the repository (the artifacts after it would never be rescanned): + // record the failure on it and go on. + _logger.LogWarning(e, "Scan of {Name} {Version} in {Repository} failed", artifact.Name, artifact.Version, Repository.Name); + result = null; + + // A save that failed half way leaves its entities tracked; they would fail every later save of the sweep. + (_context as Microsoft.EntityFrameworkCore.DbContext)?.ChangeTracker.Clear(); + try + { + await StoreFailureAsync(key.Value.Name, key.Value.Version, "scan", e.GetType().Name + ": " + e.Message, cancellationToken).ConfigureAwait(false); + } + catch (Exception inner) when (inner is not OperationCanceledException && inner is not MaintenanceException) + { + _logger.LogWarning(inner, "The failure of {Name} {Version} could not be recorded", artifact.Name, artifact.Version); + } + + failed++; + } + + if (result == null) continue; + if (result.Error != null && result.ScannedAt == null) failed++; + else + { + scanned++; + if (result.FindingCount > 0) withFindings++; + } + } + + return new ScanRepositoryReport(scanned, skipped, failed, withFindings, removed); + } + + /// + public async Task SummarizeAsync(CancellationToken cancellationToken) + { + var status = GetEngineStatus(); + var bySeverity = new int[4]; + if (_context is NullContext || Repository.Kind == RepositoryKind.Virtual) + { + return new ScanSummary(status, 0, 0, 0, 0, bySeverity); + } + + var scanner = _services.GetFormatService(Repository.Format); + var artifacts = scanner == null ? Array.Empty() : (await scanner.ListArtifactsAsync(cancellationToken).ConfigureAwait(false)).ToArray(); + var rows = await _context.ScanResults! + .AsNoTracking() + .Select(r => new { r.Name, r.Version, r.ScannedAt, r.Highest, r.Error }) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + var byKey = rows.ToDictionary(r => (r.Name!, r.Version!)); + + int unscanned = 0, failed = 0, clean = 0; + foreach (var artifact in artifacts) + { + var key = Normalize(artifact.Name, artifact.Version); + if (key == null || !byKey.TryGetValue((key.Value.Name, key.Value.Version), out var row) || row.ScannedAt == null) + { + unscanned++; + if (key != null && byKey.TryGetValue((key.Value.Name, key.Value.Version), out var failedRow) && failedRow.Error != null) failed++; + } + else if (row.Highest < 0) clean++; + else bySeverity[Math.Min(row.Highest, 3)]++; + } + + return new ScanSummary(status, artifacts.Length, unscanned, failed, clean, bySeverity); + } + + /// + public async Task> ListAsync(int minSeverity, int skip, int take, CancellationToken cancellationToken) + { + if (_context is NullContext) return Array.Empty(); + + return await _context.ScanResults! + .AsNoTracking() + .Where(r => r.ScannedAt != null && r.Highest >= minSeverity && r.FindingCount > 0) + .OrderByDescending(r => r.Highest) + .ThenByDescending(r => r.FindingCount) + .ThenBy(r => r.Name) + .ThenBy(r => r.Version) + .Skip(Math.Max(0, skip)) + .Take(Math.Clamp(take, 1, 500)) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + } + + /// + public async Task> CheckAsync(IReadOnlyList components, CancellationToken cancellationToken) + { + if (!Options.Enabled) throw new ScanUnavailableException("Scanning is turned off (Scanning:Enabled)."); + if (components.Count == 0) return Array.Empty(); + + var answers = await _source.QueryAsync(components, cancellationToken).ConfigureAwait(false); + return answers + .SelectMany(kv => kv.Value.Select(h => new ScanHit(h.Id, kv.Key.Name, kv.Key.Version, h.Severity, h.Summary, h.Url, h.FixedVersion))) + .ToList(); + } + + /// + /// The key a version is stored under: NuGet ids are lower-cased and versions normalized (so any spelling finds the same + /// row on every database), others are used as given. Null when the name or version does not fit the columns. + /// + internal (string Name, string Version)? Normalize(string name, string version) + { + if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(version)) return null; + if (Repository.Format == RepositoryFormat.NuGet) + { + name = name.ToLowerInvariant(); + if (NuGetVersion.TryParse(version, out var parsed)) version = parsed.ToNormalizedString(); + } + + if (name.Length > ScanLimits.NameLength || version.Length > ScanLimits.VersionLength) return null; + return (name, version); + } + + private async Task RemoveAsync(string name, string version, CancellationToken cancellationToken) + { + var row = await _context.ScanResults!.FirstOrDefaultAsync(r => r.Name == name && r.Version == version, cancellationToken).ConfigureAwait(false); + if (row == null) return; + + _context.ScanResults!.Remove(row); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (Repository.Format == RepositoryFormat.NuGet) await SyncNuGetAsync(name, version, Array.Empty(), cancellationToken).ConfigureAwait(false); + } + + private async Task StoreFailureAsync(string name, string version, string scanner, string message, CancellationToken cancellationToken) + { + for (var attempt = 0; ; attempt++) + { + var row = await _context.ScanResults!.Include(r => r.Findings).FirstOrDefaultAsync(r => r.Name == name && r.Version == version, cancellationToken).ConfigureAwait(false); + if (row == null) + { + row = new ScanResult { Name = name, Version = version, Scanner = scanner }; + _context.ScanResults!.Add(row); + } + + row.Attempted = _time.UtcNow; + row.Error = Cut(message, ScanLimits.ErrorLength); + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return row; + } + catch (DbUpdateException e) when (attempt == 0 && _context.IsUniqueConstraintViolationException(e)) + { + (_context as DbContext)?.ChangeTracker.Clear(); + } + } + } + + private async Task StoreAsync(string name, string version, string scanner, IReadOnlyList hits, CancellationToken cancellationToken) + { + var distinct = hits + .GroupBy(h => (h.Id, h.Component, h.ComponentVersion)) + .Select(g => g.OrderByDescending(h => h.Severity).First()) + .OrderByDescending(h => h.Severity) + .ThenBy(h => h.Id, StringComparer.Ordinal) + .ThenBy(h => h.Component, StringComparer.Ordinal) + .ToList(); + var kept = distinct.Take(MaxFindingsPerResult).ToList(); + + for (var attempt = 0; ; attempt++) + { + var row = await _context.ScanResults!.Include(r => r.Findings).FirstOrDefaultAsync(r => r.Name == name && r.Version == version, cancellationToken).ConfigureAwait(false); + if (row == null) + { + row = new ScanResult { Name = name, Version = version }; + _context.ScanResults!.Add(row); + } + else if (row.Findings != null) + { + _context.ScanFindings!.RemoveRange(row.Findings); + } + + var now = _time.UtcNow; + row.Scanner = scanner; + row.Attempted = now; + row.ScannedAt = now; + row.Error = null; + row.Highest = distinct.Count == 0 ? ScanSeverities.None : distinct.Max(h => h.Severity); + row.FindingCount = kept.Count; + row.Findings = kept.Select(h => new ScanFinding + { + VulnerabilityId = Cut(h.Id, ScanLimits.IdLength), + Component = Cut(h.Component, ScanLimits.NameLength), + ComponentVersion = Cut(h.ComponentVersion, ScanLimits.VersionLength), + Severity = Math.Clamp(h.Severity, 0, PackageVulnerabilityRules.MaxSeverity), + Summary = h.Summary == null ? null : Cut(h.Summary, ScanLimits.SummaryLength), + AdvisoryUrl = Cut(h.Url, ScanLimits.UrlLength), + FixedVersion = h.FixedVersion == null ? null : Cut(h.FixedVersion, ScanLimits.VersionLength), + }).ToList(); + + try + { + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbUpdateException e) when (attempt == 0 && _context.IsUniqueConstraintViolationException(e)) + { + (_context as DbContext)?.ChangeTracker.Clear(); + continue; + } + + if (Repository.Format == RepositoryFormat.NuGet) await SyncNuGetAsync(name, version, distinct, cancellationToken).ConfigureAwait(false); + return row; + } + } + + /// + /// Feeds NuGet's vulnerability resource: the findings that are about the package version itself replace the entries the scanner + /// recorded before ( osv); entries set by hand stay. + /// + private async Task SyncNuGetAsync(string lowerId, string normalizedVersion, IReadOnlyList hits, CancellationToken cancellationToken) + { + var package = await _context.Packages! + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .FirstOrDefaultAsync(p => p.Id == lowerId && p.NormalizedVersionString == normalizedVersion, cancellationToken) + .ConfigureAwait(false); + if (package == null) return; + + var own = hits + .Where(h => string.Equals(h.Component, package.Id, StringComparison.OrdinalIgnoreCase) + && string.Equals(NormalizeVersion(h.ComponentVersion), normalizedVersion, StringComparison.OrdinalIgnoreCase)) + .Select(h => new PackageVulnerability + { + AdvisoryUrl = h.Url, + Severity = Math.Clamp(h.Severity, 0, PackageVulnerabilityRules.MaxSeverity), + VersionRange = "[" + normalizedVersion + "]", + Source = _source.Name, + }) + .GroupBy(v => (v.AdvisoryUrl, v.Severity)) + .Select(g => g.First()) + .ToList(); + + var old = (package.Vulnerabilities ?? new List()).Where(v => v.Source == _source.Name).ToList(); + var unchanged = old.Count == own.Count && old.All(o => own.Any(n => n.AdvisoryUrl == o.AdvisoryUrl && n.Severity == o.Severity)); + if (unchanged) return; + + _context.PackageVulnerabilities!.RemoveRange(old); + package.Vulnerabilities ??= new List(); + package.Vulnerabilities.AddRange(own); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + private static string NormalizeVersion(string version) + => NuGetVersion.TryParse(version, out var parsed) ? parsed.ToNormalizedString() : version; + + private static string Cut(string value, int max) => value.Length <= max ? value : value.Substring(0, max); +} diff --git a/src/BaGet.Core/Scanning/ScanSeverities.cs b/src/BaGet.Core/Scanning/ScanSeverities.cs new file mode 100644 index 000000000..aac0f8d2e --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanSeverities.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace BaGet.Core; + +/// +/// Severities as the scanner stores them: the numbers of NuGet's vulnerability resource (0 low, 1 moderate, 2 high, 3 critical), +/// with -1 for "none". Advisory databases name them differently (GitHub: LOW, MODERATE, HIGH, CRITICAL; Trivy: LOW, MEDIUM, HIGH, +/// CRITICAL, UNKNOWN) or give only a CVSS vector; this class maps all of them onto the four. +/// +public static class ScanSeverities +{ + /// "No finding". + public const int None = -1; + + /// The severity of a finding the source does not rate; treated as moderate so it is neither hidden nor alarming. + public const int Unrated = 1; + + /// The display name of a severity (Low… Critical), or None. + public static string Name(int severity) + => severity >= 0 && severity < PackageVulnerabilityRules.SeverityNames.Count ? PackageVulnerabilityRules.SeverityNames[severity] : "None"; + + /// The severity named by a database (case-insensitive), or false when it is not one of the usual words. + public static bool TryParseName(string? name, out int severity) + { + switch (name?.Trim().ToUpperInvariant()) + { + case "LOW": severity = 0; return true; + case "MODERATE": + case "MEDIUM": severity = 1; return true; + case "HIGH": severity = 2; return true; + case "CRITICAL": severity = 3; return true; + default: severity = Unrated; return false; + } + } + + /// The CVSS qualitative rating of a base score: below 4 low, below 7 moderate, below 9 high, else critical. + public static int FromScore(double score) => score < 4.0 ? 0 : score < 7.0 ? 1 : score < 9.0 ? 2 : 3; + + /// + /// The CVSS v3.x base score of a vector (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H), or null when it is not a valid + /// v3 vector. Version 4 vectors are not computed (they carry no number); the caller falls back to . + /// + public static double? CvssV3BaseScore(string? vector) + { + if (string.IsNullOrWhiteSpace(vector) || !vector.StartsWith("CVSS:3", StringComparison.Ordinal)) return null; + + var metrics = new Dictionary(StringComparer.Ordinal); + foreach (var part in vector.Split('/')) + { + var colon = part.IndexOf(':'); + if (colon > 0) metrics[part.Substring(0, colon)] = part.Substring(colon + 1); + } + + if (!metrics.TryGetValue("AV", out var av) || !metrics.TryGetValue("AC", out var ac) || !metrics.TryGetValue("PR", out var pr) + || !metrics.TryGetValue("UI", out var ui) || !metrics.TryGetValue("S", out var scope) + || !metrics.TryGetValue("C", out var c) || !metrics.TryGetValue("I", out var i) || !metrics.TryGetValue("A", out var a)) + { + return null; + } + + var changed = scope == "C"; + if (scope != "C" && scope != "U") return null; + + double? avW = av switch { "N" => 0.85, "A" => 0.62, "L" => 0.55, "P" => 0.2, _ => null }; + double? acW = ac switch { "L" => 0.77, "H" => 0.44, _ => null }; + double? prW = pr switch { "N" => 0.85, "L" => changed ? 0.68 : 0.62, "H" => changed ? 0.5 : 0.27, _ => null }; + double? uiW = ui switch { "N" => 0.85, "R" => 0.62, _ => null }; + double? cW = Cia(c), iW = Cia(i), aW = Cia(a); + if (avW == null || acW == null || prW == null || uiW == null || cW == null || iW == null || aW == null) return null; + + var iss = 1 - (1 - cW.Value) * (1 - iW.Value) * (1 - aW.Value); + var impact = changed ? 7.52 * (iss - 0.029) - 3.25 * Math.Pow(iss - 0.02, 15) : 6.42 * iss; + var exploitability = 8.22 * avW.Value * acW.Value * prW.Value * uiW.Value; + if (impact <= 0) return 0; + + var raw = changed ? Math.Min(1.08 * (impact + exploitability), 10) : Math.Min(impact + exploitability, 10); + return Math.Ceiling(raw * 10 - 1e-9) / 10; + + static double? Cia(string value) => value switch { "H" => 0.56, "L" => 0.22, "N" => 0.0, _ => null }; + } + + /// Formats a version number for display in a reason (invariant culture). + internal static string Format(int count) => count.ToString(CultureInfo.InvariantCulture); +} diff --git a/src/BaGet.Core/Scanning/ScanWorker.cs b/src/BaGet.Core/Scanning/ScanWorker.cs new file mode 100644 index 000000000..46b0aa8f6 --- /dev/null +++ b/src/BaGet.Core/Scanning/ScanWorker.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Core; + +/// A version waiting to be scanned. +/// The repository it is stored in. +/// The artifact name. +/// The version. +public sealed record QueuedScan(RepositoryInfo Repository, string Name, string Version); + +/// +/// Versions to scan soon (just stored by a deploy or a cache fill, or found unscanned by a download), in memory per node. The same +/// version is queued once; a full queue drops new entries (the scheduled sweep finds them). +/// +public sealed class ScanQueue +{ + private const int Capacity = 5000; + + private readonly Channel _channel = Channel.CreateBounded(new BoundedChannelOptions(Capacity) + { + FullMode = BoundedChannelFullMode.DropWrite, + SingleReader = true, + }); + + private readonly ConcurrentDictionary<(int, string, string), byte> _queued = new(); + + internal ChannelReader Reader => _channel.Reader; + + /// Queues a version unless it is queued already. + public void Enqueue(RepositoryInfo repository, string name, string version) + { + if (repository == null) throw new ArgumentNullException(nameof(repository)); + if (!_queued.TryAdd((repository.Key, name, version), 0)) return; + if (!_channel.Writer.TryWrite(new QueuedScan(repository, name, version))) _queued.TryRemove((repository.Key, name, version), out _); + } + + internal void Done(QueuedScan item) => _queued.TryRemove((item.Repository.Key, item.Name, item.Version), out _); + + /// How many versions are waiting (for tests and status). + public int Pending => _queued.Count; +} + +/// +/// Scans what holds and, every ten minutes, repositories whose results are older than +/// (new advisories appear after the first scan). Idle when scanning is off. +/// +public sealed class ScanWorker : BackgroundService +{ + private static readonly TimeSpan SweepEvery = TimeSpan.FromMinutes(10); + private static readonly TimeSpan FirstSweepAfter = TimeSpan.FromMinutes(1); + + private readonly ScanQueue _queue; + private readonly IServiceScopeFactory _scopes; + private readonly ILogger _logger; + private readonly IJobLease? _lease; + + public ScanWorker(ScanQueue queue, IServiceScopeFactory scopes, ILogger logger, IJobLease? lease = null) + { + _lease = lease; + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var nextSweep = DateTime.UtcNow + FirstSweepAfter; + while (!stoppingToken.IsCancellationRequested) + { + try + { + using (var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken)) + { + wait.CancelAfter(TimeSpan.FromSeconds(30)); + try + { + await _queue.Reader.WaitToReadAsync(wait.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) + { + // Nothing queued for a while: time to look at the schedule. + } + } + + while (_queue.Reader.TryRead(out var item)) + { + await ProcessAsync(item, stoppingToken).ConfigureAwait(false); + } + + if (DateTime.UtcNow >= nextSweep) + { + nextSweep = DateTime.UtcNow + SweepEvery; + await SweepAsync(stoppingToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception e) + { + _logger.LogError(e, "Scanning worker iteration failed."); + try { await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + } + } + } + + private async Task ProcessAsync(QueuedScan item, CancellationToken cancellationToken) + { + try + { + using var scope = _scopes.CreateRepositoryScope(item.Repository); + var scans = scope.ServiceProvider.GetRequiredService(); + if (!scans.GetEngineStatus().Available) return; + await scans.ScanAsync(item.Name, item.Version, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (MaintenanceException) + { + // Read-only while a copy runs; the next sweep picks the version up. + } + catch (Exception e) + { + _logger.LogWarning(e, "Scanning {Name} {Version} in {Repository} failed.", item.Name, item.Version, item.Repository.Name); + } + finally + { + _queue.Done(item); + } + } + + private async Task SweepAsync(CancellationToken cancellationToken) + { + // The scheduled rescan runs on one node of a cluster at a time (the queue of just-stored versions stays per node). + await using var sweep = await _lease.AcquireAsync("scan:sweep", cancellationToken).ConfigureAwait(false); + if (sweep == null) return; + + using var root = _scopes.CreateScope(); + var options = root.ServiceProvider.GetRequiredService>().Value; + if (!options.Enabled || options.RescanInterval <= TimeSpan.Zero) return; + if (root.ServiceProvider.GetRequiredService() is NullContext) return; + + var repositories = await root.ServiceProvider.GetRequiredService().ListAsync(cancellationToken).ConfigureAwait(false); + foreach (var repository in repositories.Where(r => r.Kind != RepositoryKind.Virtual)) + { + try + { + using var scope = _scopes.CreateRepositoryScope(repository); + var scans = scope.ServiceProvider.GetRequiredService(); + if (!scans.GetEngineStatus().Available) continue; + var report = await scans.ScanRepositoryAsync(onlyStale: true, cancellationToken).ConfigureAwait(false); + if (report.Scanned + report.Failed + report.Removed > 0) + { + _logger.LogInformation("Scheduled scan of {Repository}: {Report}", repository.Name, report); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (MaintenanceException) + { + return; + } + catch (Exception e) + { + _logger.LogWarning(e, "Scheduled scan of {Repository} failed.", repository.Name); + } + } + } +} + +/// The Scan repository operation of the Operations page: scans every version now. +public sealed class ScanRepositoryOperation : IAdminOperation +{ + public string Name => "vulnerability-scan"; + + public string Title => "Scan for vulnerabilities"; + + public string Description => "Checks every artifact of the repository against the vulnerability database (OSV, or Trivy for container images) and stores the findings. Needs Scanning:Enabled."; + + public bool IsAvailable(IServiceProvider services) + => services.GetRequiredService>().Value.Enabled + && services.GetRequiredService() is not NullContext; + + public bool AppliesTo(RepositoryInfo repository) => repository.Kind != RepositoryKind.Virtual; + + public async Task RunAsync(IServiceProvider services, CancellationToken cancellationToken) + { + var report = await services.GetRequiredService().ScanRepositoryAsync(onlyStale: false, cancellationToken).ConfigureAwait(false); + return report.ToString(); + } +} diff --git a/src/BaGet.Core/Scanning/Trivy.cs b/src/BaGet.Core/Scanning/Trivy.cs new file mode 100644 index 000000000..dda1c5ff8 --- /dev/null +++ b/src/BaGet.Core/Scanning/Trivy.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// A vulnerability a scanner found, before it is stored as a . +/// The advisory id. +/// The vulnerable component. +/// Its version. +/// 0 low … 3 critical. +/// One line, or null. +/// An absolute http(s) link. +/// The first fixed version, or null. +public sealed record ScanHit(string Id, string Component, string ComponentVersion, int Severity, string? Summary, string Url, string? FixedVersion); + +/// Runs Trivy on a container image reference. Replaced in tests; the default runs the configured executable. +public interface ITrivyRunner +{ + /// Whether Trivy is configured ( and a registry host are set). + bool IsConfigured(ScanningOptions options); + + /// Scans (host/repository/image@digest) and returns what Trivy reports. + /// Trivy is not usable or failed; the message is safe to show. + Task> ScanImageAsync(ScanningOptions options, string imageReference, CancellationToken cancellationToken); +} + +/// Reads the JSON Trivy prints with --format json. +public static class TrivyReport +{ + /// The vulnerabilities of every result of the report (OS packages and language packages alike). + /// The text is not a Trivy report. + public static IReadOnlyList Parse(string json) + { + JsonDocument document; + try + { + document = JsonDocument.Parse(json); + } + catch (JsonException e) + { + throw new ScanUnavailableException("Trivy printed something that is not JSON.", e); + } + + using (document) + { + var hits = new List(); + if (document.RootElement.ValueKind != JsonValueKind.Object) throw new ScanUnavailableException("Trivy printed an unexpected document."); + + if (document.RootElement.TryGetProperty("Results", out var results) && results.ValueKind == JsonValueKind.Array) + { + foreach (var result in results.EnumerateArray()) + { + if (!result.TryGetProperty("Vulnerabilities", out var vulnerabilities) || vulnerabilities.ValueKind != JsonValueKind.Array) continue; + foreach (var vulnerability in vulnerabilities.EnumerateArray()) + { + var id = Text(vulnerability, "VulnerabilityID"); + var name = Text(vulnerability, "PkgName"); + if (id == null || name == null) continue; + + ScanSeverities.TryParseName(Text(vulnerability, "Severity"), out var severity); + var url = Text(vulnerability, "PrimaryURL"); + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp) || url!.Length > 900) + { + url = "https://avd.aquasec.com/nvd/" + Uri.EscapeDataString(id.ToLowerInvariant()); + } + + var summary = Text(vulnerability, "Title") ?? Text(vulnerability, "Description"); + if (summary != null && summary.Length > 500) summary = summary.Substring(0, 500); + + hits.Add(new ScanHit(id, name, Text(vulnerability, "InstalledVersion") ?? "unknown", severity, summary, url!, Text(vulnerability, "FixedVersion"))); + } + } + } + + return hits; + } + } + + private static string? Text(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(value.GetString()) ? value.GetString() : null; +} + +/// +/// Runs the configured trivy executable: trivy image --format json --scanners vuln [--server URL] [--insecure] REF. +/// The registry credentials travel in the environment (TRIVY_USERNAME, TRIVY_PASSWORD), never on the command line. +/// +public sealed class ProcessTrivyRunner : ITrivyRunner +{ + private const int MaxOutputBytes = 64 * 1024 * 1024; + + /// + public bool IsConfigured(ScanningOptions options) + => !string.IsNullOrWhiteSpace(options.TrivyPath) && !string.IsNullOrWhiteSpace(options.TrivyRegistryHost); + + /// + public async Task> ScanImageAsync(ScanningOptions options, string imageReference, CancellationToken cancellationToken) + { + if (!IsConfigured(options)) throw new ScanUnavailableException("Trivy is not configured."); + + var start = new ProcessStartInfo(options.TrivyPath!) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = Encoding.UTF8, + }; + foreach (var argument in new[] { "image", "--quiet", "--no-progress", "--format", "json", "--scanners", "vuln" }) + { + start.ArgumentList.Add(argument); + } + + if (!string.IsNullOrWhiteSpace(options.TrivyServerUrl)) + { + start.ArgumentList.Add("--server"); + start.ArgumentList.Add(options.TrivyServerUrl!); + } + + if (options.TrivyInsecure) + { + start.ArgumentList.Add("--insecure"); + start.Environment["TRIVY_NON_SSL"] = "true"; + } + + if (!string.IsNullOrEmpty(options.TrivyRegistryUser)) start.Environment["TRIVY_USERNAME"] = options.TrivyRegistryUser; + if (!string.IsNullOrEmpty(options.TrivyRegistryPassword)) start.Environment["TRIVY_PASSWORD"] = options.TrivyRegistryPassword; + start.ArgumentList.Add(imageReference); + + Process process; + try + { + process = Process.Start(start) ?? throw new ScanUnavailableException("Trivy could not be started."); + } + catch (Exception e) when (e is System.ComponentModel.Win32Exception || e is InvalidOperationException || e is IOException) + { + throw new ScanUnavailableException("Trivy could not be started: " + e.Message, e); + } + + using (process) + using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + timeout.CancelAfter(options.TrivyTimeout > TimeSpan.Zero ? options.TrivyTimeout : TimeSpan.FromMinutes(10)); + process.StandardInput.Close(); + var output = ReadCappedAsync(process.StandardOutput, timeout.Token); + var error = ReadCappedAsync(process.StandardError, timeout.Token); + try + { + // A reader that hits the output cap stops draining the pipe and the child would block on it until the timeout: + // watch the readers too and kill the process as soon as one fails. + var exited = process.WaitForExitAsync(timeout.Token); + // Task.WhenAll would wait for the other reader too, which never ends while the child blocks on the full pipe. + var pending = new List { exited, output, error }; + while (!exited.IsCompleted) + { + var done = await Task.WhenAny(pending).ConfigureAwait(false); + if (done == exited) break; + await done.ConfigureAwait(false); + pending.Remove(done); + } + + await exited.ConfigureAwait(false); + } + catch (ScanUnavailableException) + { + try { process.Kill(entireProcessTree: true); } catch (Exception) { /* already gone */ } + throw; + } + catch (OperationCanceledException) + { + try { process.Kill(entireProcessTree: true); } catch (Exception) { /* already gone */ } + if (cancellationToken.IsCancellationRequested) throw; + throw new ScanUnavailableException("Trivy did not finish in time."); + } + + var text = await output.ConfigureAwait(false); + var errors = await error.ConfigureAwait(false); + if (process.ExitCode != 0) + { + throw new ScanUnavailableException("Trivy failed (exit code " + process.ExitCode + "): " + Scrub(FirstLine(errors), options)); + } + + return TrivyReport.Parse(text); + } + } + + private static string FirstLine(string text) + { + var line = text.Split('\n').Select(l => l.Trim()).LastOrDefault(l => l.Length > 0) ?? "no message"; + return line.Length > 300 ? line.Substring(0, 300) : line; + } + + private static string Scrub(string text, ScanningOptions options) + => string.IsNullOrEmpty(options.TrivyRegistryPassword) ? text : text.Replace(options.TrivyRegistryPassword, "***", StringComparison.Ordinal); + + private static async Task ReadCappedAsync(StreamReader reader, CancellationToken cancellationToken) + { + var builder = new StringBuilder(); + var buffer = new char[8192]; + int read; + while ((read = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false)) > 0) + { + if (builder.Length + read > MaxOutputBytes) throw new ScanUnavailableException("Trivy printed more than 64 MB."); + builder.Append(buffer, 0, read); + } + + return builder.ToString(); + } +} diff --git a/src/BaGet.Core/Search/AutocompleteRequest.cs b/src/BaGet.Core/Search/AutocompleteRequest.cs index ef5b0b976..d6f51e603 100644 --- a/src/BaGet.Core/Search/AutocompleteRequest.cs +++ b/src/BaGet.Core/Search/AutocompleteRequest.cs @@ -1,39 +1,38 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet V3 search request. +/// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters +/// +public class AutocompleteRequest { /// - /// The NuGet V3 search request. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters + /// The number of results to skip, for pagination. /// - public class AutocompleteRequest - { - /// - /// The number of results to skip, for pagination. - /// - public int Skip { get; set; } + public int Skip { get; set; } - /// - /// The number of results to return, for pagination. - /// - public int Take { get; set; } + /// + /// The number of results to return, for pagination. + /// + public int Take { get; set; } - /// - /// Whether to include pre-release packages. - /// - public bool IncludePrerelease { get; set; } + /// + /// Whether to include pre-release packages. + /// + public bool IncludePrerelease { get; set; } - /// - /// Whether to include SemVer 2.0.0 compatible packages. - /// - public bool IncludeSemVer2 { get; set; } + /// + /// Whether to include SemVer 2.0.0 compatible packages. + /// + public bool IncludeSemVer2 { get; set; } - /// - /// Filter results to a package type. If null, no filter is applied. - /// - public string PackageType { get; set; } + /// + /// Filter results to a package type. If null, no filter is applied. + /// + public string? PackageType { get; set; } - /// - /// The search query. - /// - public string Query { get; set; } - } -} + /// + /// The search query. + /// + public string? Query { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/DatabaseSearchService.cs b/src/BaGet.Core/Search/DatabaseSearchService.cs index 1ab64a411..96dd6eca8 100644 --- a/src/BaGet.Core/Search/DatabaseSearchService.cs +++ b/src/BaGet.Core/Search/DatabaseSearchService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -6,192 +6,316 @@ using BaGet.Protocol.Models; using Microsoft.EntityFrameworkCore; -namespace BaGet.Core +namespace BaGet.Core; + +public class DatabaseSearchService : ISearchService { - public class DatabaseSearchService : ISearchService + private readonly IContext _context; + private readonly IFrameworkCompatibilityService _frameworks; + private readonly ISearchResponseBuilder _searchBuilder; + + public DatabaseSearchService( + IContext context, + IFrameworkCompatibilityService frameworks, + ISearchResponseBuilder searchBuilder) { - private readonly IContext _context; - private readonly IFrameworkCompatibilityService _frameworks; - private readonly ISearchResponseBuilder _searchBuilder; - - public DatabaseSearchService( - IContext context, - IFrameworkCompatibilityService frameworks, - ISearchResponseBuilder searchBuilder) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); - _searchBuilder = searchBuilder ?? throw new ArgumentNullException(nameof(searchBuilder)); - } + _context = context ?? throw new ArgumentNullException(nameof(context)); + _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); + _searchBuilder = searchBuilder ?? throw new ArgumentNullException(nameof(searchBuilder)); + } - public async Task SearchAsync(SearchRequest request, CancellationToken cancellationToken) - { - var frameworks = GetCompatibleFrameworksOrNull(request.Framework); - - IQueryable search = _context.Packages; - search = ApplySearchQuery(search, request.Query); - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - request.PackageType, - frameworks); - - var packageIds = search - .Select(p => p.Id) - .Distinct() - .OrderBy(id => id) - .Skip(request.Skip) - .Take(request.Take); - - // This query MUST fetch all versions for each package that matches the search, - // otherwise the results for a package's latest version may be incorrect. - // If possible, we'll find all these packages in a single query by matching - // the package IDs in a subquery. Otherwise, run two queries: - // 1. Find the package IDs that match the search - // 2. Find all package versions for these package IDs - if (_context.SupportsLimitInSubqueries) - { - search = _context.Packages.Where(p => packageIds.Contains(p.Id)); - } - else - { - var packageIdResults = await packageIds.ToListAsync(cancellationToken); + public IReadOnlyCollection SupportedSorts { get; } = new[] + { + SearchSort.Relevance, + SearchSort.TotalDownloads, + SearchSort.LastUpdated, + }; - search = _context.Packages.Where(p => packageIdResults.Contains(p.Id)); - } + public async Task SearchAsync(SearchRequest request, CancellationToken cancellationToken) + { + var frameworks = GetCompatibleFrameworksOrNull(request.Framework); - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - request.PackageType, - frameworks); + IQueryable? search = _context.Packages; + search = ApplySearchQuery(search, request.Query); + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + request.PackageType, + frameworks); - var results = await search.ToListAsync(cancellationToken); - var groupedResults = results - .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) - .Select(group => new PackageRegistration(group.Key, group.ToList())) - .ToList(); + // "TotalHits" is the number of matches disregarding skip and take. A page of results is + // drawn from the distinct package ids that match the filters, so the total must count + // those distinct ids - not the matching rows, of which there is one per package version. + var totalHits = await CountDistinctPackageIdsAsync(search, cancellationToken); - return _searchBuilder.BuildSearch(groupedResults); - } + // The page is drawn from the distinct package ids, in the requested order. Every order + // ends in the id so that it is total: without a tie-breaker, equal downloads or dates + // would let a package appear on two pages or on none. + // + // The ids are fetched first, rather than as a subquery of the next query, because that + // query returns one row per version in no particular order: the page's order has to be + // restored from this list. (It also covers providers that cannot limit a subquery.) + var packageIdPage = await OrderPackageIds(search, request.SortBy) + .Skip(request.Skip) + .Take(request.Take) + .ToListAsync(cancellationToken); - public async Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) - { - IQueryable search = _context.Packages; - - search = ApplySearchQuery(search, request.Query); - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - request.PackageType, - frameworks: null); - - var packageIds = await search - .OrderByDescending(p => p.Downloads) - .Select(p => p.Id) - .Distinct() - .Skip(request.Skip) - .Take(request.Take) - .ToListAsync(cancellationToken); - - return _searchBuilder.BuildAutocomplete(packageIds); - } + search = _context.Packages?.Where(p => packageIdPage.Contains(p.Id)); - public async Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) - { - var packageId = request.PackageId.ToLower(); - var search = _context - .Packages - .Where(p => p.Id.ToLower().Equals(packageId)); - - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - packageType: null, - frameworks: null); - - var packageVersions = await search - .Select(p => p.NormalizedVersionString) - .ToListAsync(cancellationToken); - - return _searchBuilder.BuildAutocomplete(packageVersions); - } + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + request.PackageType, + frameworks); + + #pragma warning disable CS8604 + var results = await search + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + var position = new Dictionary(StringComparer.OrdinalIgnoreCase); + #pragma warning disable CS8604 + for (var i = 0; i < packageIdPage.Count; i++) position.TryAdd(packageIdPage[i], i); + #pragma warning restore CS8604 + + #pragma warning disable CS8604 + var groupedResults = results + .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) + .OrderBy(group => position.TryGetValue(group.Key, out var index) ? index : int.MaxValue) + .Select(group => new PackageRegistration(group.Key, group.ToList())) + .ToList(); + #pragma warning restore CS8604 + + var response = _searchBuilder.BuildSearch(groupedResults, totalHits); - public async Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + await AddOwnersAsync(response, cancellationToken); + + return response; + } + + /// + /// Report each result's owners. A package pushed before accounts existed has none, + /// and then neither field is reported. + /// + private async Task AddOwnersAsync(SearchResponse response, CancellationToken cancellationToken) + { + if (response.Data?.Count == 0) return; + + var ids = response.Data?.Select(r => r.PackageId?.ToLower()).ToList(); + #pragma warning disable CS8602, CS8604 + var owners = await _context.PackageOwners + .AsNoTracking() + .Where(o => ids.Contains(o.PackageId.ToLower())) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + var byId = owners.ToLookup(o => o.PackageId, StringComparer.OrdinalIgnoreCase); + #pragma warning disable CS8602 + foreach (var result in response.Data) + #pragma warning restore CS8602 { - var dependents = await _context - .Packages - .Where(p => p.Listed) - .OrderByDescending(p => p.Downloads) - .Where(p => p.Dependencies.Any(d => d.Id == packageId)) - .Take(20) - .Select(r => new PackageDependent - { - Id = r.Id, - Description = r.Description, - TotalDownloads = r.Downloads - }) - .Distinct() - .ToListAsync(cancellationToken); - - return _searchBuilder.BuildDependents(dependents); + var resultOwners = byId[result.PackageId].ToList(); + if (resultOwners.Count == 0) continue; + + result.Owners = resultOwners.Select(o => o.OwnerName).OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList(); + result.Verified = resultOwners.Any(o => o.IsVerified); } + } - private IQueryable ApplySearchQuery(IQueryable query, string search) - { - if (string.IsNullOrEmpty(search)) + public async Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + IQueryable? search = _context.Packages; + + search = ApplySearchQuery(search, request.Query); + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + request.PackageType, + frameworks: null); + + // See the comment in "SearchAsync": the total disregards skip and take and counts + // distinct package ids, which is what the page below is drawn from. + var totalHits = await CountDistinctPackageIdsAsync(search, cancellationToken); + + // Group by package ID so that the column the results are ordered by is part of + // the query's projection. Ordering before a "Distinct" over a narrower projection + // is silently dropped, and SQL Server rejects the resulting query outright: + // "ORDER BY items must appear in the select list if SELECT DISTINCT is specified." + #pragma warning disable CS8604 + var packageIds = await search + .GroupBy(p => p.Id) + .OrderByDescending(packages => packages.Sum(p => p.Downloads)) + .Select(packages => packages.Key) + .Skip(request.Skip) + .Take(request.Take) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + return _searchBuilder.BuildAutocomplete(packageIds, totalHits); + } + + public async Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + var packageId = request.PackageId?.ToLower(); + #pragma warning disable CS8602, CS8604 + var search = _context + .Packages + .Where(p => p.Id.ToLower().Equals(packageId)); + #pragma warning restore CS8602, CS8604 + + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + packageType: null, + frameworks: null); + + #pragma warning disable CS8604 + var packageVersions = await search + .Select(p => p.NormalizedVersionString) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + // Version enumeration is not paged, so every match is on the single page returned. + return _searchBuilder.BuildAutocomplete(packageVersions, packageVersions.Count); + } + + public async Task FindDependentsAsync(string? packageId, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + // One row per dependent id (its versions' downloads summed), then the top 20: taking 20 versions first + // listed one id once per version and returned fewer than 20 distinct dependents. + var dependents = await _context + .Packages + .Where(p => p.Listed) + .Where(p => p.Dependencies.Any(d => d.Id == packageId)) + .GroupBy(p => p.Id) + .OrderByDescending(g => g.Sum(p => p.Downloads)) + .ThenBy(g => g.Key) + .Take(20) + .Select(g => new PackageDependent { - return query; - } + Id = g.Key, + Description = g.Max(p => p.Description), + TotalDownloads = g.Sum(p => p.Downloads) + }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + return _searchBuilder.BuildDependents(dependents); + } - search = search.ToLowerInvariant(); + internal static IQueryable OrderPackageIds(IQueryable? search, SearchSort sort) + { + // Grouping by id puts the sort key in the projection, which SQL Server requires of + // an order over a distinct list (see "AutocompleteAsync"). + var groups = search?.GroupBy(p => p.Id); - return query.Where(p => p.Id.ToLower().Contains(search)); + switch (sort) + { + case SearchSort.TotalDownloads: + #pragma warning disable CS8604 + return groups + .OrderByDescending(g => g.Sum(p => p.Downloads)) + .ThenBy(g => g.Key) + .Select(g => g.Key); + #pragma warning restore CS8604 + + case SearchSort.LastUpdated: + #pragma warning disable CS8604 + return groups + .OrderByDescending(g => g.Max(p => p.Published)) + .ThenBy(g => g.Key) + .Select(g => g.Key); + #pragma warning restore CS8604 + + default: + #pragma warning disable CS8604 + return groups + .OrderBy(g => g.Key) + .Select(g => g.Key); + #pragma warning restore CS8604 } + } - private IQueryable ApplySearchFilters( - IQueryable query, - bool includePrerelease, - bool includeSemVer2, - string packageType, - IReadOnlyList frameworks) + /// + /// Count the packages matched by a filtered query, disregarding skip and take. + /// A single package is stored as one row per version, so the matching rows must be + /// reduced to their distinct package ids first. This mirrors the projection that the + /// paged queries use, so the total is always consistent with the page. + /// + private static Task CountDistinctPackageIdsAsync( + IQueryable? search, + CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + return search + .Select(p => p.Id) + .Distinct() + .CountAsync(cancellationToken); + #pragma warning restore CS8604 + } + + private IQueryable? ApplySearchQuery(IQueryable? query, string? search) + { + if (string.IsNullOrEmpty(search)) { - if (!includePrerelease) - { - query = query.Where(p => !p.IsPrerelease); - } + return query; + } - if (!includeSemVer2) - { - query = query.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); - } + search = search.ToLowerInvariant(); - if (!string.IsNullOrEmpty(packageType)) - { - query = query.Where(p => p.PackageTypes.Any(t => t.Name == packageType)); - } + #pragma warning disable CS8602 + return query?.Where(p => p.Id.ToLower().Contains(search)); + #pragma warning restore CS8602 + } - if (frameworks != null) - { - query = query.Where(p => p.TargetFrameworks.Any(f => frameworks.Contains(f.Moniker))); - } + private IQueryable? ApplySearchFilters( + IQueryable? query, + bool includePrerelease, + bool includeSemVer2, + string? packageType, + IReadOnlyList? frameworks) + { + if (!includePrerelease) + { + query = query?.Where(p => !p.IsPrerelease); + } - return query.Where(p => p.Listed); + if (!includeSemVer2) + { + query = query?.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); } - private IReadOnlyList GetCompatibleFrameworksOrNull(string framework) + if (!string.IsNullOrEmpty(packageType)) { - if (framework == null) return null; + #pragma warning disable CS8604 + query = query?.Where(p => p.PackageTypes.Any(t => t.Name == packageType)); + #pragma warning restore CS8604 + } - return _frameworks.FindAllCompatibleFrameworks(framework); + if (frameworks != null) + { + #pragma warning disable CS8604 + query = query?.Where(p => p.TargetFrameworks.Any(f => frameworks.Contains(f.Moniker))); + #pragma warning restore CS8604 } + + return query?.Where(p => p.Listed); + } + + private IReadOnlyList? GetCompatibleFrameworksOrNull(string? framework) + { + if (framework == null) return null; + + return _frameworks.FindAllCompatibleFrameworks(framework); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/DependentsResponse.cs b/src/BaGet.Core/Search/DependentsResponse.cs index 2d7970455..2be22718f 100644 --- a/src/BaGet.Core/Search/DependentsResponse.cs +++ b/src/BaGet.Core/Search/DependentsResponse.cs @@ -1,48 +1,47 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The package ids that depend on the queried package. +/// This is an unofficial API that isn't part of the NuGet protocol. +/// +public class DependentsResponse { /// - /// The package ids that depend on the queried package. - /// This is an unofficial API that isn't part of the NuGet protocol. + /// The total number of matches, disregarding skip and take. /// - public class DependentsResponse - { - /// - /// The total number of matches, disregarding skip and take. - /// - [JsonPropertyName("totalHits")] - public long TotalHits { get; set; } + [JsonPropertyName("totalHits")] + public long TotalHits { get; set; } - /// - /// The package IDs matched by the dependent query. - /// - [JsonPropertyName("data")] - public IReadOnlyList Data { get; set; } - } + /// + /// The package IDs matched by the dependent query. + /// + [JsonPropertyName("data")] + public IReadOnlyList? Data { get; set; } +} +/// +/// A package that depends on the queried package. +/// +public class PackageDependent +{ /// - /// A package that depends on the queried package. + /// The dependent package id. /// - public class PackageDependent - { - /// - /// The dependent package id. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + [JsonPropertyName("id")] + public string? Id { get; set; } - /// - /// The description of the dependent package. - /// - [JsonPropertyName("description")] - public string Description { get; set; } + /// + /// The description of the dependent package. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } - /// - /// The total downloads for the dependent package. - /// - [JsonPropertyName("totalDownloads")] - public long TotalDownloads { get; set; } - } -} + /// + /// The total downloads for the dependent package. + /// + [JsonPropertyName("totalDownloads")] + public long TotalDownloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/ISearchIndexer.cs b/src/BaGet.Core/Search/ISearchIndexer.cs index dd2ff4064..4a9c9e203 100644 --- a/src/BaGet.Core/Search/ISearchIndexer.cs +++ b/src/BaGet.Core/Search/ISearchIndexer.cs @@ -1,16 +1,15 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public interface ISearchIndexer { - public interface ISearchIndexer - { - /// - /// Add a package to the search index. - /// - /// The package to add. - /// A token to cancel the task. - /// A task that completes once the package has been added. - Task IndexAsync(Package package, CancellationToken cancellationToken); - } -} + /// + /// Add a package to the search index. + /// + /// The package to add. + /// A token to cancel the task. + /// A task that completes once the package has been added. + Task IndexAsync(Package package, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/ISearchResponseBuilder.cs b/src/BaGet.Core/Search/ISearchResponseBuilder.cs index 734d96143..66fea9d24 100644 --- a/src/BaGet.Core/Search/ISearchResponseBuilder.cs +++ b/src/BaGet.Core/Search/ISearchResponseBuilder.cs @@ -1,12 +1,31 @@ -using System.Collections.Generic; +using System.Collections.Generic; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public interface ISearchResponseBuilder { - public interface ISearchResponseBuilder - { - SearchResponse BuildSearch(IReadOnlyList results); - AutocompleteResponse BuildAutocomplete(IReadOnlyList data); - DependentsResponse BuildDependents(IReadOnlyList results); - } -} + /// + /// Build a search response. + /// + /// The page of package registrations that should be returned. + /// + /// The total number of packages that matched the search, disregarding skip and take. + /// This is reported as , so it must count every + /// match and not merely the ones on the current page. + /// + SearchResponse BuildSearch(IReadOnlyList results, long totalHits); + + /// + /// Build an autocomplete response. + /// + /// The page of results that should be returned. + /// + /// The total number of results that matched the query, disregarding skip and take. + /// This is reported as , so it must count + /// every match and not merely the ones on the current page. + /// + AutocompleteResponse BuildAutocomplete(IReadOnlyList data, long totalHits); + + DependentsResponse BuildDependents(IReadOnlyList results); +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/ISearchService.cs b/src/BaGet.Core/Search/ISearchService.cs index 0aeb9f928..303a6c367 100644 --- a/src/BaGet.Core/Search/ISearchService.cs +++ b/src/BaGet.Core/Search/ISearchService.cs @@ -1,51 +1,58 @@ +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The service used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource +/// +public interface ISearchService { /// - /// The service used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// The orders this provider can apply on the server. A provider that cannot sort + /// reports only and ignores : + /// sorting one page in memory would be wrong, so the UI hides its sort control instead. /// - public interface ISearchService - { - /// - /// Perform a search query. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages - /// - /// The search request. - /// A token to cancel the task. - /// The search response. - Task SearchAsync(SearchRequest request, CancellationToken cancellationToken); + IReadOnlyCollection SupportedSorts => new[] { SearchSort.Relevance }; - /// - /// Perform an autocomplete query. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids - /// - /// The autocomplete request. - /// A token to cancel the task. - /// The autocomplete response. - Task AutocompleteAsync(AutocompleteRequest request, CancellationToken cancellationToken); + /// + /// Perform a search query. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages + /// + /// The search request. + /// A token to cancel the task. + /// The search response. + Task SearchAsync(SearchRequest request, CancellationToken cancellationToken); + + /// + /// Perform an autocomplete query. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids + /// + /// The autocomplete request. + /// A token to cancel the task. + /// The autocomplete response. + Task AutocompleteAsync(AutocompleteRequest request, CancellationToken cancellationToken); - /// - /// Enumerate listed package versions. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions - /// - /// The autocomplete request. - /// A token to cancel the task. - /// The package versions that matched the request. - Task ListPackageVersionsAsync(VersionsRequest request, CancellationToken cancellationToken); + /// + /// Enumerate listed package versions. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions + /// + /// The autocomplete request. + /// A token to cancel the task. + /// The package versions that matched the request. + Task ListPackageVersionsAsync(VersionsRequest request, CancellationToken cancellationToken); - /// - /// Find the packages that depend on a given package. - /// - /// The package whose dependents should be found. - /// A token to cancel the task. - /// The dependents response. - Task FindDependentsAsync( - string packageId, - CancellationToken cancellationToken); - } -} + /// + /// Find the packages that depend on a given package. + /// + /// The package whose dependents should be found. + /// A token to cancel the task. + /// The dependents response. + Task FindDependentsAsync( + string? packageId, + CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/NullSearchIndexer.cs b/src/BaGet.Core/Search/NullSearchIndexer.cs index 0dd1c5ce8..1a85bf412 100644 --- a/src/BaGet.Core/Search/NullSearchIndexer.cs +++ b/src/BaGet.Core/Search/NullSearchIndexer.cs @@ -1,16 +1,15 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A no-op indexer, used when search does not need to index packages. +/// +public class NullSearchIndexer : ISearchIndexer { - /// - /// A no-op indexer, used when search does not need to index packages. - /// - public class NullSearchIndexer : ISearchIndexer + public Task IndexAsync(Package package, CancellationToken cancellationToken = default) { - public Task IndexAsync(Package package, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/NullSearchService.cs b/src/BaGet.Core/Search/NullSearchService.cs index 33ac06cfc..a9622c3ed 100644 --- a/src/BaGet.Core/Search/NullSearchService.cs +++ b/src/BaGet.Core/Search/NullSearchService.cs @@ -3,61 +3,63 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A minimal search service implementation, used for advanced scenarios. +/// +public class NullSearchService : ISearchService { - /// - /// A minimal search service implementation, used for advanced scenarios. - /// - public class NullSearchService : ISearchService - { - private static readonly IReadOnlyList EmptyStringList = new List(); - - private static readonly Task EmptyAutocompleteResponseTask = - Task.FromResult(new AutocompleteResponse - { - TotalHits = 0, - Data = EmptyStringList, - Context = AutocompleteContext.Default - }); - - private static readonly Task EmptyDependentsResponseTask = - Task.FromResult(new DependentsResponse - { - TotalHits = 0, - Data = new List() - }); - - private static readonly Task EmptySearchResponseTask = - Task.FromResult(new SearchResponse - { - TotalHits = 0, - Data = new List() - }); - - public Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) - { - return EmptyAutocompleteResponseTask; - } + private static readonly IReadOnlyList EmptyStringList = new List(); + + // This service never matches anything, so zero is the total number of matches + // disregarding skip and take, not merely the size of the page returned. - public Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) + private static readonly Task EmptyAutocompleteResponseTask = + Task.FromResult(new AutocompleteResponse { - return EmptyAutocompleteResponseTask; - } + TotalHits = 0, + Data = EmptyStringList, + Context = AutocompleteContext.Default + }); - public Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + private static readonly Task EmptyDependentsResponseTask = + Task.FromResult(new DependentsResponse { - return EmptyDependentsResponseTask; - } + TotalHits = 0, + Data = new List() + }); - public Task SearchAsync( - SearchRequest request, - CancellationToken cancellationToken) + private static readonly Task EmptySearchResponseTask = + Task.FromResult(new SearchResponse { - return EmptySearchResponseTask; - } + TotalHits = 0, + Data = new List() + }); + + public Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + return EmptyAutocompleteResponseTask; + } + + public Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + return EmptyAutocompleteResponseTask; + } + + public Task FindDependentsAsync(string? packageId, CancellationToken cancellationToken) + { + return EmptyDependentsResponseTask; + } + + public Task SearchAsync( + SearchRequest request, + CancellationToken cancellationToken) + { + return EmptySearchResponseTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/RepositorySearchService.cs b/src/BaGet.Core/Search/RepositorySearchService.cs new file mode 100644 index 000000000..9a108a40e --- /dev/null +++ b/src/BaGet.Core/Search/RepositorySearchService.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Protocol.Models; +using Microsoft.Extensions.DependencyInjection; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// The search the protocol endpoints and pages use: the configured for an ordinary +/// repository, and for a virtual one the merge of its readable members' searches. +/// +/// +/// +/// A virtual search reads each member in its own order, page by page, only as far as the page asked for needs: the first +/// skip + take + 1 results of each member (at most , that is at most +/// / page calls per member and request), so a request for the +/// first page costs one small call per member however large the members are (a member of at most +/// results is then read to its end, at most that many results in +/// / page calls, so small and medium installs keep exact +/// totals). The windows are then merged once. A package id +/// found in several members is one result: the first member entry, with the versions of the others added and the download +/// counts summed. The order is total and does not depend on the page asked for: is the +/// id (case-insensitive), is the summed downloads then the id. +/// +/// +/// Exactness: the page is exact whenever each member window covers it, which holds for +/// (a member lists ids in ascending order, so an id of the merged first n is in its member first n; databases +/// that order mixed-case ids differently from the case-insensitive merge can misplace one at a window edge) and for every +/// result set that fits a window. For an id held by several members is summed from +/// the entries inside each member window, so an id near the edge of one window can rank slightly lower than its full +/// total says. totalHits is the number of distinct ids when every member was read to its end (always the case when each +/// has at most results), else an estimate +/// (the ids seen plus each member unseen remainder, an upper bound); results deeper than +/// per member are cut off. is not offered (results carry no date). +/// +/// Autocomplete and the dependents list are merged the same way (ids ordered by name). +/// +public sealed class RepositorySearchService : ISearchService +{ + /// Page size used to read a member. + internal const int MemberPageSize = 500; + + /// A member with at most this many results is always read completely, which keeps the merged total exact. + public const int ExactScanPerMember = 2_000; + + /// Most results read from one member for one query (so also the deepest page a virtual search can serve). + public const int MaxScanPerMember = 10_000; + + private static readonly IReadOnlyCollection VirtualSorts = new[] { SearchSort.Relevance, SearchSort.TotalDownloads }; + + private readonly ISearchService _inner; + private readonly VirtualRepositoryReader _reader; + private readonly ISearchResponseBuilder _builder; + + public RepositorySearchService(ISearchService inner, VirtualRepositoryReader reader, ISearchResponseBuilder builder) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + } + + /// + public IReadOnlyCollection SupportedSorts => _reader.IsVirtual ? VirtualSorts : _inner.SupportedSorts; + + /// + public async Task SearchAsync(SearchRequest request, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.SearchAsync(request, cancellationToken).ConfigureAwait(false); + + var sort = request.SortBy == SearchSort.TotalDownloads ? SearchSort.TotalDownloads : SearchSort.Relevance; + var skip = Math.Max(request.Skip, 0); + var take = Math.Max(request.Take, 0); + var window = Window(skip, take); + var members = await _reader.AllAsync( + packageId: null, + sp => DrainSearchAsync(sp.GetRequiredService(), request, sort, window, cancellationToken), + cancellationToken).ConfigureAwait(false); + + var merged = Merge(members.Select(m => m.Value.Items), sort); + var remainder = members.Sum(m => Math.Max(0, m.Value.Total - m.Value.Items.Count)); + + var response = _builder.BuildSearch(Array.Empty(), merged.Count + remainder); + response.Data = merged.Skip(skip).Take(take).ToList(); + + return response; + } + + /// + public async Task AutocompleteAsync(AutocompleteRequest request, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.AutocompleteAsync(request, cancellationToken).ConfigureAwait(false); + + var window = Window(Math.Max(request.Skip, 0), Math.Max(request.Take, 0)); + var members = await _reader.AllAsync( + packageId: null, + sp => DrainAutocompleteAsync(sp.GetRequiredService(), request, window, cancellationToken), + cancellationToken).ConfigureAwait(false); + + var ids = DistinctIgnoreCase(members.SelectMany(m => m.Value.Items)) + .OrderBy(id => id, StringComparer.OrdinalIgnoreCase) + .ThenBy(id => id, StringComparer.Ordinal) + .ToList(); + var remainder = members.Sum(m => Math.Max(0, m.Value.Total - m.Value.Items.Count)); + + return _builder.BuildAutocomplete( + ids.Skip(Math.Max(request.Skip, 0)).Take(Math.Max(request.Take, 0)).ToList(), + ids.Count + remainder); + } + + /// + public async Task ListPackageVersionsAsync(VersionsRequest request, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.ListPackageVersionsAsync(request, cancellationToken).ConfigureAwait(false); + + var members = await _reader.AllAsync( + request.PackageId, + sp => sp.GetRequiredService().ListPackageVersionsAsync(request, cancellationToken), + cancellationToken).ConfigureAwait(false); + + var versions = DistinctIgnoreCase(members.SelectMany(m => m.Value.Data ?? Array.Empty())) + .OrderBy(v => NuGetVersion.TryParse(v, out var parsed) ? parsed : null, Comparer.Create(CompareVersions)) + .ThenBy(v => v, StringComparer.Ordinal) + .ToList(); + + return _builder.BuildAutocomplete(versions, versions.Count); + } + + /// + public async Task FindDependentsAsync(string? packageId, CancellationToken cancellationToken) + { + if (!_reader.IsVirtual) return await _inner.FindDependentsAsync(packageId, cancellationToken).ConfigureAwait(false); + + var members = await _reader.AllAsync( + packageId: null, + sp => sp.GetRequiredService().FindDependentsAsync(packageId, cancellationToken), + cancellationToken).ConfigureAwait(false); + + var dependents = members + .SelectMany(m => m.Value.Data ?? Array.Empty()) + .GroupBy(d => d.Id ?? string.Empty, StringComparer.OrdinalIgnoreCase) + .Select(g => new PackageDependent { Id = g.First().Id, Description = g.First().Description, TotalDownloads = g.Sum(d => d.TotalDownloads) }) + .OrderByDescending(d => d.TotalDownloads) + .ThenBy(d => d.Id, StringComparer.OrdinalIgnoreCase) + .Take(20) + .ToList(); + + return _builder.BuildDependents(dependents); + } + + private static int CompareVersions(NuGetVersion? a, NuGetVersion? b) + => a == null ? (b == null ? 0 : 1) : b == null ? -1 : a.CompareTo(b); + + private static IEnumerable DistinctIgnoreCase(IEnumerable values) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var value in values) + { + if (value != null && seen.Add(value)) yield return value; + } + } + + /// + /// The search results of several members as one ordered list of distinct package ids. The earliest member's entry + /// stands for an id found in several; the others add their versions and downloads. + /// + internal static List Merge(IEnumerable> members, SearchSort sort) + { + var byId = new Dictionary(StringComparer.OrdinalIgnoreCase); + var order = new List(); + + foreach (var result in members.SelectMany(m => m)) + { + if (result.PackageId == null) continue; + + if (!byId.TryGetValue(result.PackageId, out var winner)) + { + byId[result.PackageId] = result; + order.Add(result); + continue; + } + + winner.TotalDownloads += result.TotalDownloads; + AddVersions(winner, result); + } + + var ordered = sort == SearchSort.TotalDownloads + ? order.OrderByDescending(r => r.TotalDownloads) + .ThenBy(r => r.PackageId, StringComparer.OrdinalIgnoreCase) + .ThenBy(r => r.PackageId, StringComparer.Ordinal) + : order.OrderBy(r => r.PackageId, StringComparer.OrdinalIgnoreCase) + .ThenBy(r => r.PackageId, StringComparer.Ordinal); + + return ordered.ToList(); + } + + // The winner lists every version of the id once (highest first, as a single repository does) and reports the highest. + private static void AddVersions(SearchResult winner, SearchResult other) + { + var versions = new List(winner.Versions ?? Array.Empty()); + var known = new HashSet(versions.Select(v => v.Version ?? string.Empty), StringComparer.OrdinalIgnoreCase); + foreach (var version in other.Versions ?? Array.Empty()) + { + if (known.Add(version.Version ?? string.Empty)) versions.Add(version); + } + + versions = versions + .OrderByDescending(v => NuGetVersion.TryParse(v.Version, out var parsed) ? parsed : null, Comparer.Create(CompareVersions)) + .ToList(); + + winner.Versions = versions; + if (versions.Count > 0) winner.Version = versions[0].Version; + } + + // How many results of each member the page [skip, skip + take) needs, plus one to see that there are more. + private static int Window(int skip, int take) + => (int)Math.Min((long)skip + take + 1, MaxScanPerMember); + + private static async Task> DrainSearchAsync(ISearchService search, SearchRequest request, SearchSort sort, int window, CancellationToken cancellationToken) + { + var items = new List(); + long total = 0; + + var limit = window; + while (items.Count < limit) + { + var take = Math.Min(MemberPageSize, limit - items.Count); + var page = await search.SearchAsync( + new SearchRequest + { + Skip = items.Count, + Take = take, + IncludePrerelease = request.IncludePrerelease, + IncludeSemVer2 = request.IncludeSemVer2, + PackageType = request.PackageType, + Framework = request.Framework, + Query = request.Query, + SortBy = sort, + }, + cancellationToken).ConfigureAwait(false); + + total = page.TotalHits; + + // A member that is small anyway is read to its end, so its total (and the merged one) stays exact. + if (total <= ExactScanPerMember) limit = Math.Max(limit, (int)total); + var data = page.Data ?? Array.Empty(); + items.AddRange(data); + + if (data.Count < take || items.Count >= total) break; + } + + return new Drained(items, Math.Max(total, items.Count)); + } + + private static async Task> DrainAutocompleteAsync(ISearchService search, AutocompleteRequest request, int window, CancellationToken cancellationToken) + { + var items = new List(); + long total = 0; + + var limit = window; + while (items.Count < limit) + { + var take = Math.Min(MemberPageSize, limit - items.Count); + var page = await search.AutocompleteAsync( + new AutocompleteRequest + { + Skip = items.Count, + Take = take, + IncludePrerelease = request.IncludePrerelease, + IncludeSemVer2 = request.IncludeSemVer2, + PackageType = request.PackageType, + Query = request.Query, + }, + cancellationToken).ConfigureAwait(false); + + total = page.TotalHits; + if (total <= ExactScanPerMember) limit = Math.Max(limit, (int)total); + var data = page.Data ?? Array.Empty(); + items.AddRange(data); + + if (data.Count < take || items.Count >= total) break; + } + + return new Drained(items, Math.Max(total, items.Count)); + } + + private sealed record Drained(List Items, long Total); +} diff --git a/src/BaGet.Core/Search/SearchRequest.cs b/src/BaGet.Core/Search/SearchRequest.cs index fd81250b0..2abb8e6a3 100644 --- a/src/BaGet.Core/Search/SearchRequest.cs +++ b/src/BaGet.Core/Search/SearchRequest.cs @@ -1,44 +1,49 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet V3 search request. +/// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters +/// +public class SearchRequest { /// - /// The NuGet V3 search request. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters - /// - public class SearchRequest - { - /// - /// The number of results to skip, for pagination. - /// - public int Skip { get; set; } - - /// - /// The number of results to return, for pagination. - /// - public int Take { get; set; } - - /// - /// Whether to include pre-release packages. - /// - public bool IncludePrerelease { get; set; } - - /// - /// Whether to include SemVer 2.0.0 compatible packages. - /// - public bool IncludeSemVer2 { get; set; } - - /// - /// Filter results to a package type. If null, no filter is applied. - /// - public string PackageType { get; set; } - - /// - /// Filters results to a target framework. If null, no filter is applied. - /// - public string Framework { get; set; } - - /// - /// The search query. - /// - public string Query { get; set; } - } + /// The number of results to skip, for pagination. + /// + public int Skip { get; set; } + + /// + /// The number of results to return, for pagination. + /// + public int Take { get; set; } + + /// + /// Whether to include pre-release packages. + /// + public bool IncludePrerelease { get; set; } + + /// + /// Whether to include SemVer 2.0.0 compatible packages. + /// + public bool IncludeSemVer2 { get; set; } + + /// + /// Filter results to a package type. If null, no filter is applied. + /// + public string? PackageType { get; set; } + + /// + /// Filters results to a target framework. If null, no filter is applied. + /// + public string? Framework { get; set; } + + /// + /// The search query. + /// + public string? Query { get; set; } + + /// + /// How to order the results. Set by the web UI only; a provider that cannot sort on + /// the server ignores it (see ). + /// + public SearchSort SortBy { get; set; } = SearchSort.Relevance; } diff --git a/src/BaGet.Core/Search/SearchResponseBuilder.cs b/src/BaGet.Core/Search/SearchResponseBuilder.cs index 8ccd91e91..cc4be6335 100644 --- a/src/BaGet.Core/Search/SearchResponseBuilder.cs +++ b/src/BaGet.Core/Search/SearchResponseBuilder.cs @@ -3,79 +3,80 @@ using System.Linq; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public class SearchResponseBuilder : ISearchResponseBuilder { - public class SearchResponseBuilder : ISearchResponseBuilder + private readonly IUrlGenerator _url; + + public SearchResponseBuilder(IUrlGenerator url) { - private readonly IUrlGenerator _url; + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public SearchResponseBuilder(IUrlGenerator url) - { - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public SearchResponse BuildSearch(IReadOnlyList packageRegistrations, long totalHits) + { + var result = new List(); - public SearchResponse BuildSearch(IReadOnlyList packageRegistrations) + foreach (var packageRegistration in packageRegistrations) { - var result = new List(); + var versions = packageRegistration.Packages.OrderByDescending(p => p.Version).ToList(); + var latest = versions.First(); + var iconUrl = latest.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(latest.Id, latest.Version) + : latest.IconUrlString; - foreach (var packageRegistration in packageRegistrations) + result.Add(new SearchResult { - var versions = packageRegistration.Packages.OrderByDescending(p => p.Version).ToList(); - var latest = versions.First(); - var iconUrl = latest.HasEmbeddedIcon - ? _url.GetPackageIconDownloadUrl(latest.Id, latest.Version) - : latest.IconUrlString; - - result.Add(new SearchResult - { - PackageId = latest.Id, - Version = latest.Version.ToFullString(), - Description = latest.Description, - Authors = latest.Authors, - IconUrl = iconUrl, - LicenseUrl = latest.LicenseUrlString, - ProjectUrl = latest.ProjectUrlString, - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(latest.Id), - Summary = latest.Summary, - Tags = latest.Tags, - Title = latest.Title, - TotalDownloads = versions.Sum(p => p.Downloads), - Versions = versions - .Select(p => new SearchResultVersion - { - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(p.Id, p.Version), - Version = p.Version.ToFullString(), - Downloads = p.Downloads, - }) - .ToList(), - }); - } - - return new SearchResponse - { - TotalHits = result.Count, - Data = result, - Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()), - }; + PackageId = latest.Id, + Version = latest.Version.ToFullString(), + Description = latest.Description, + Authors = latest.Authors, + IconUrl = iconUrl, + LicenseUrl = latest.LicenseUrlString, + ProjectUrl = latest.ProjectUrlString, + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(latest.Id), + Summary = latest.Summary, + Tags = latest.Tags, + Title = latest.Title, + TotalDownloads = versions.Sum(p => p.Downloads), + Versions = versions + .Select(p => new SearchResultVersion + { + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(p.Id, p.Version), + Version = p.Version.ToFullString(), + Downloads = p.Downloads, + }) + .ToList(), + Deprecation = RegistrationBuilder.ToDeprecation(latest.Deprecation), + Vulnerabilities = RegistrationBuilder.ToVulnerabilities(latest.Vulnerabilities), + }); } - public AutocompleteResponse BuildAutocomplete(IReadOnlyList data) + return new SearchResponse { - return new AutocompleteResponse - { - TotalHits = data.Count, - Data = data, - Context = AutocompleteContext.Default - }; - } + TotalHits = totalHits, + Data = result, + Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()), + }; + } - public DependentsResponse BuildDependents(IReadOnlyList packages) + public AutocompleteResponse BuildAutocomplete(IReadOnlyList data, long totalHits) + { + return new AutocompleteResponse { - return new DependentsResponse - { - TotalHits = packages.Count, - Data = packages, - }; - } + TotalHits = totalHits, + Data = data, + Context = AutocompleteContext.Default + }; + } + + public DependentsResponse BuildDependents(IReadOnlyList packages) + { + return new DependentsResponse + { + TotalHits = packages.Count, + Data = packages, + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/SearchSort.cs b/src/BaGet.Core/Search/SearchSort.cs new file mode 100644 index 000000000..7c45cf112 --- /dev/null +++ b/src/BaGet.Core/Search/SearchSort.cs @@ -0,0 +1,23 @@ +namespace BaGet.Core; + +/// +/// How the web UI orders search results. The V3 search API has no sort parameter, so +/// it always uses . +/// +public enum SearchSort +{ + /// + /// The provider's default order. + /// + Relevance, + + /// + /// Most downloaded package first. + /// + TotalDownloads, + + /// + /// Most recently published package first. + /// + LastUpdated, +} diff --git a/src/BaGet.Core/Search/VersionsRequest.cs b/src/BaGet.Core/Search/VersionsRequest.cs index 974fc5d90..bde63d07a 100644 --- a/src/BaGet.Core/Search/VersionsRequest.cs +++ b/src/BaGet.Core/Search/VersionsRequest.cs @@ -1,24 +1,23 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet V3 enumerate package versions request. +/// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters-1 +/// +public class VersionsRequest { /// - /// The NuGet V3 enumerate package versions request. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters-1 + /// Whether to include pre-release packages. /// - public class VersionsRequest - { - /// - /// Whether to include pre-release packages. - /// - public bool IncludePrerelease { get; set; } + public bool IncludePrerelease { get; set; } - /// - /// Whether to include SemVer 2.0.0 compatible packages. - /// - public bool IncludeSemVer2 { get; set; } + /// + /// Whether to include SemVer 2.0.0 compatible packages. + /// + public bool IncludeSemVer2 { get; set; } - /// - /// The package ID whose versions should be fetched. - /// - public string PackageId { get; set; } - } -} + /// + /// The package ID whose versions should be fetched. + /// + public string? PackageId { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs b/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs index db84b65fd..41d69a2e0 100644 --- a/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs +++ b/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs @@ -1,52 +1,80 @@ -using System; +using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public class BaGetServiceIndex : IServiceIndexService { - public class BaGetServiceIndex : IServiceIndexService + private readonly IUrlGenerator _url; + private readonly IReadOnlyList _providers; + + public BaGetServiceIndex(IUrlGenerator url) + : this(url, Array.Empty()) { - private readonly IUrlGenerator _url; + } - public BaGetServiceIndex(IUrlGenerator url) - { - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public BaGetServiceIndex(IUrlGenerator url, IEnumerable? providers) + { + _url = url ?? throw new ArgumentNullException(nameof(url)); + _providers = providers?.ToList() ?? throw new ArgumentNullException(nameof(providers)); + } - private IEnumerable BuildResource(string name, string url, params string[] versions) + private IEnumerable BuildResource(string name, string? url, params string[] versions) + { + foreach (var version in versions) { - foreach (var version in versions) + var type = string.IsNullOrEmpty(version) ? name : $"{name}/{version}"; + + yield return new ServiceIndexItem { - var type = string.IsNullOrEmpty(version) ? name : $"{name}/{version}"; - - yield return new ServiceIndexItem - { - ResourceUrl = url, - Type = type, - }; - } + ResourceUrl = url, + Type = type, + }; } + } - public Task GetAsync(CancellationToken cancellationToken = default) + public Task GetAsync(CancellationToken cancellationToken = default) + { + var resources = new List(); + + resources.AddRange(BuildResource("PackagePublish", _url.GetPackagePublishResourceUrl(), "2.0.0")); + resources.AddRange(BuildResource("SymbolPackagePublish", _url.GetSymbolPublishResourceUrl(), "4.9.0")); + resources.AddRange(BuildResource("SearchQueryService", _url.GetSearchResourceUrl(), "", "3.0.0-beta", "3.0.0-rc")); + resources.AddRange(BuildResource("RegistrationsBaseUrl", _url.GetPackageMetadataResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); + resources.AddRange(BuildResource("PackageBaseAddress", _url.GetPackageContentResourceUrl(), "3.0.0")); + resources.AddRange(BuildResource("SearchAutocompleteService", _url.GetAutocompleteResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); + + // The web pages these templates expand to exist under every repository (/r/{name}/packages/…), so each + // repository's index advertises its own; a host without pages returns null and leaves them out. + var detailsTemplate = _url.GetPackageDetailsUriTemplate(); + if (detailsTemplate != null) { - var resources = new List(); + resources.AddRange(BuildResource("PackageDetailsUriTemplate", detailsTemplate, "5.1.0")); + } - resources.AddRange(BuildResource("PackagePublish", _url.GetPackagePublishResourceUrl(), "2.0.0")); - resources.AddRange(BuildResource("SymbolPackagePublish", _url.GetSymbolPublishResourceUrl(), "4.9.0")); - resources.AddRange(BuildResource("SearchQueryService", _url.GetSearchResourceUrl(), "", "3.0.0-beta", "3.0.0-rc")); - resources.AddRange(BuildResource("RegistrationsBaseUrl", _url.GetPackageMetadataResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); - resources.AddRange(BuildResource("PackageBaseAddress", _url.GetPackageContentResourceUrl(), "3.0.0")); - resources.AddRange(BuildResource("SearchAutocompleteService", _url.GetAutocompleteResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); + var abuseTemplate = _url.GetReportAbuseUriTemplate(); + if (abuseTemplate != null) + { + resources.AddRange(BuildResource("ReportAbuseUriTemplate", abuseTemplate, "3.0.0-beta", "3.0.0-rc")); + } - var result = new ServiceIndexResponse - { - Version = "3.0.0", - Resources = resources, - }; + resources.AddRange(BuildResource("VulnerabilityInfo", _url.GetVulnerabilityIndexUrl(), "6.7.0")); - return Task.FromResult(result); + foreach (var provider in _providers) + { + resources.AddRange(provider.GetResources()); } + + var result = new ServiceIndexResponse + { + Version = "3.0.0", + Resources = resources, + }; + + return Task.FromResult(result); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/ServiceIndex/IServiceIndexResourceProvider.cs b/src/BaGet.Core/ServiceIndex/IServiceIndexResourceProvider.cs new file mode 100644 index 000000000..1d5d59c1f --- /dev/null +++ b/src/BaGet.Core/ServiceIndex/IServiceIndexResourceProvider.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using BaGet.Protocol.Models; + +namespace BaGet.Core; + +/// +/// Adds resources to the service index, for features that live outside BaGet.Core. +/// +public interface IServiceIndexResourceProvider +{ + IEnumerable GetResources(); +} \ No newline at end of file diff --git a/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs b/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs index 67bf9a8b0..b7687b0d8 100644 --- a/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs +++ b/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs @@ -2,20 +2,19 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet Service Index service, used to discover other resources. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index +/// +public interface IServiceIndexService { /// - /// The NuGet Service Index service, used to discover other resources. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// Get the resources available on this package feed. + /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources /// - public interface IServiceIndexService - { - /// - /// Get the resources available on this package feed. - /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources - /// - /// The resources available on this package feed. - Task GetAsync(CancellationToken cancellationToken = default); - } -} + /// The resources available on this package feed. + Task GetAsync(CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Staging/IPackageStagingService.cs b/src/BaGet.Core/Staging/IPackageStagingService.cs new file mode 100644 index 000000000..1df1d573b --- /dev/null +++ b/src/BaGet.Core/Staging/IPackageStagingService.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Holds a package between the two requests of a browser upload: the first stages it and +/// shows what it contains, the second confirms it. The upload is stored, not held in the +/// request, so the two requests may land on different instances. +/// +public interface IPackageStagingService +{ + /// + /// Stage an upload for . + /// + /// An opaque token identifying the staged upload. + Task StageAsync(Stream? package, string? ownerId, CancellationToken cancellationToken = default); + + /// + /// The staged package, or null if the token is unknown, incomplete, or was staged by + /// a different user. + /// + Task OpenAsync(string token, string? ownerId, CancellationToken cancellationToken = default); + + /// + /// Forget a staged upload, whether it was confirmed or cancelled. The owner is + /// checked exactly as checks it: the token is the only handle + /// on an upload, so without this anyone who learned one could discard someone else's + /// pending upload. An unknown token is not an error. + /// + /// + /// Whether an upload was removed. False when the token is unknown or belongs to a + /// different user, which are deliberately indistinguishable. + /// + Task RemoveAsync(string? token, string? ownerId, CancellationToken cancellationToken = default); + + /// + /// Remove every upload staged before . An upload that + /// is never confirmed nor cancelled - a closed browser tab - is only collected here, + /// so without this staging grows without bound. + /// + /// How many staged uploads were removed. + Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Staging/StoragePackageStagingService.cs b/src/BaGet.Core/Staging/StoragePackageStagingService.cs new file mode 100644 index 000000000..909a23b0a --- /dev/null +++ b/src/BaGet.Core/Staging/StoragePackageStagingService.cs @@ -0,0 +1,400 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace BaGet.Core; + +/// +/// Stages uploads in under a prefix of their own, so that +/// the two requests of a browser upload may land on different instances and so that +/// every storage provider works, exactly as the validation pipeline stages pushed +/// packages under "validation/". +/// +/// +/// Nothing serves the staging prefix: no route turns a request into a storage path, so a +/// staged upload is reachable only through , which is where the +/// owner is checked. +/// +public class StoragePackageStagingService : IPackageStagingService +{ + /// + /// The prefix every staged upload lives under. A token never becomes anything else. + /// + internal const string StagingPathPrefix = "staging"; + + /// + /// 128 bits from a cryptographic generator, hex encoded. The token is the only thing + /// naming a staged upload, so guessing one must not be feasible. + /// + private const int TokenBytes = 16; + + private const int TokenLength = TokenBytes * 2; + + private readonly IStorageService _storage; + private readonly SystemTime _time; + private readonly ILogger _logger; + private readonly IRepositoryContext? _repository; + + /// + /// The repository uploads are staged for: the default one stages under staging/, any other under + /// repos/{name}/staging/, so a token staged for one repository cannot be opened from another and + /// collects the current repository's uploads only. Null means the default repository. + /// + public StoragePackageStagingService( + IStorageService storage, + SystemTime time, + ILogger logger, + IRepositoryContext? repository = null) + { + _repository = repository; + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private RepositoryInfo Repository => _repository?.Current ?? RepositoryInfo.Default; + + /// + /// The staging prefix of the current repository: staging, or repos/{name}/staging. + /// + private string Prefix => RepositoryStorage.Scope(Repository, StagingPathPrefix); + + internal static string StagedPath(string? token) => StagedPath(RepositoryInfo.Default, token); + + internal static string StagedPath(RepositoryInfo repository, string? token) + => RepositoryStorage.Scope(repository, $"{StagingPathPrefix}/{token}.nupkg"); + + internal static string MetadataPath(string? token) => MetadataPath(RepositoryInfo.Default, token); + + internal static string MetadataPath(RepositoryInfo repository, string? token) + => RepositoryStorage.Scope(repository, $"{StagingPathPrefix}/{token}.json"); + + public async Task StageAsync(Stream? package, string? ownerId, CancellationToken cancellationToken = default) + { + if (package == null) throw new ArgumentNullException(nameof(package)); + + var token = CreateToken(); + var metadata = new StagedUpload + { + OwnerId = Owner(ownerId), + StagedAtUtc = _time.UtcNow, + }; + + // The metadata is written before the package because the sweep finds abandoned + // uploads through the metadata: a package whose metadata never arrived would be + // collected by nothing. + using (var json = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(metadata))) + { + await StoreAsync(MetadataPath(Repository, token), json, "application/json", cancellationToken); + } + + try + { + await StoreAsync(StagedPath(Repository, token), package, "application/octet-stream", cancellationToken); + } + catch + { + // Half a staged upload can never be confirmed, so it is removed now rather + // than left for the sweep. + await ForgetAsync(token, CancellationToken.None); + throw; + } + + // The token itself only ever reaches Debug. It is the whole capability over a + // staged upload, and a log at Information is on by default and usually shipped + // to a store read by far more people than the uploader; the correlation id is + // enough to follow one upload through the log without handing it over. + _logger.LogDebug("Staged an upload as {Token}", token); + _logger.LogInformation("Staged an upload, correlation {Correlation}", Correlation(token)); + + return token; + } + + public async Task OpenAsync(string? token, string? ownerId, CancellationToken cancellationToken = default) + { + if (!IsToken(token)) return null; + + var read = await ReadMetadataAsync(token, cancellationToken); + if (read.Metadata == null) return null; + + // The real authorization: the prefix being unreachable over HTTP is a property of + // the route table, not an access check, and two users share one store. + if (!IsOwner(read.Metadata, ownerId)) + { + _logger.LogWarning( + "Refusing staged upload {Correlation}: it was staged by a different user", + Correlation(token)); + + return null; + } + + return await OpenOrNullAsync(StagedPath(Repository, token), cancellationToken); + } + + public async Task RemoveAsync(string? token, string? ownerId, CancellationToken cancellationToken = default) + { + if (!IsToken(token)) return false; + + // The same owner check makes. Removal is not a read, but + // it destroys an upload its owner may be about to confirm, so a token someone + // else learned must not be enough to discard it. + var read = await ReadMetadataAsync(token, cancellationToken); + if (read.Metadata == null || !IsOwner(read.Metadata, ownerId)) + { + return false; + } + + await ForgetAsync(token, cancellationToken); + + return true; + } + + public async Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default) + { + if (!(_storage is IListableStorageService listable)) + { + // Said out loud: silence here would mean staged uploads accumulating + // unnoticed on a store that cannot be swept. + _logger.LogWarning( + "Cannot sweep abandoned staged uploads: {Storage} cannot list what it holds", + _storage.GetType().Name); + + return 0; + } + + var paths = await listable.ListAsync(Prefix, cancellationToken); + var stored = new HashSet(paths, StringComparer.Ordinal); + + var tokens = new HashSet(StringComparer.Ordinal); + foreach (var path in paths) + { + var token = TokenOrNull(path); + if (token != null) tokens.Add(token); + } + + var swept = 0; + foreach (var token in tokens) + { + if (!await IsCollectableAsync(token, stagedBefore, stored, cancellationToken)) continue; + + await ForgetAsync(token, cancellationToken); + swept++; + } + + if (swept > 0) + { + _logger.LogInformation("Swept {Count} staged uploads abandoned before {Cutoff}", swept, stagedBefore); + } + + return swept; + } + + /// + /// Whether the sweep may discard an upload. An upload is collected when it is older + /// than the cutoff, when its metadata is gone - nobody can open it then, since the + /// owner it belonged to is unknowable - or when its metadata will never parse. It is + /// kept when the metadata is there but could not be read this time: a store that is + /// briefly unreachable, or a file a backup or a scanner is holding, says nothing + /// about whether the upload was abandoned, and collecting it then would discard an + /// upload staged a minute ago whose preview is still open. + /// + private async Task IsCollectableAsync( + string? token, + DateTime stagedBefore, + HashSet stored, + CancellationToken cancellationToken) + { + var read = await ReadMetadataAsync(token, cancellationToken); + + switch (read.Status) + { + case StagedMetadataStatus.Readable: + return read.Metadata?.StagedAtUtc < stagedBefore; + + case StagedMetadataStatus.Unreadable: + return true; + + default: + if (!stored.Contains(MetadataPath(Repository, token))) return true; + + _logger.LogWarning( + "Keeping staged upload {Correlation}: its metadata could not be read this time", + Correlation(token)); + + return false; + } + } + + private async Task StoreAsync(string path, Stream content, string contentType, CancellationToken cancellationToken) + { + var result = await _storage.PutAsync(path, content, contentType, cancellationToken); + + if (result == StoragePutResult.Conflict) + { + throw new InvalidOperationException($"Could not stage an upload at '{path}'; the path is already in use"); + } + } + + /// + /// Remove both of an upload's blobs, whoever owns it. Every caller that reaches here + /// has already decided it may. + /// + private async Task ForgetAsync(string? token, CancellationToken cancellationToken) + { + await DeleteAsync(StagedPath(Repository, token), cancellationToken); + await DeleteAsync(MetadataPath(Repository, token), cancellationToken); + } + + private async Task ReadMetadataAsync(string? token, CancellationToken cancellationToken) + { + using var stream = await OpenOrNullAsync(MetadataPath(Repository, token), cancellationToken); + if (stream == null) return new StagedMetadataRead(StagedMetadataStatus.Unavailable, null); + + try + { + var metadata = await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); + + return metadata == null + ? new StagedMetadataRead(StagedMetadataStatus.Unreadable, null) + : new StagedMetadataRead(StagedMetadataStatus.Readable, metadata); + } + catch (JsonException e) + { + // Content that does not parse will not parse on the next pass either, unlike + // a file that could not be opened this time. + _logger.LogWarning(e, "Staged upload {Correlation} has unreadable metadata", Correlation(token)); + + return new StagedMetadataRead(StagedMetadataStatus.Unreadable, null); + } + } + + private async Task OpenOrNullAsync(string path, CancellationToken cancellationToken) + { + try + { + // IStorageService is documented to answer a missing path with null, but no + // implementation does: the file store throws, each cloud store throws its + // own type, and the null store really does return null. An upload that + // cannot be read back is an unknown token either way. + return await _storage.GetAsync(path, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogDebug(e, "Nothing staged at {Path}", path); + return null; + } + } + + private async Task DeleteAsync(string path, CancellationToken cancellationToken) + { + try + { + await _storage.DeleteAsync(path, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // Left for the next sweep rather than failing a confirmed upload. + _logger.LogWarning(e, "Could not remove staged content under {Prefix}", StagingPathPrefix); + } + } + + private static string CreateToken() + => Convert.ToHexString(RandomNumberGenerator.GetBytes(TokenBytes)).ToLowerInvariant(); + + /// + /// A short, non-reversible name for an upload, so a log can follow one upload without + /// carrying the token that would let its reader act on it. + /// + #pragma warning disable CS8604 + private static string Correlation(string? token) + => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)), 0, 4).ToLowerInvariant(); + #pragma warning restore CS8604 + + private static bool IsOwner(StagedUpload metadata, string? ownerId) + => string.Equals(metadata.OwnerId, Owner(ownerId), StringComparison.Ordinal); + + /// + /// A token becomes a storage path, so anything that is not one is refused before it + /// gets there - a caller-supplied "../packages/..." must never be opened or deleted. + /// + private static bool IsToken(string? token) + { + if (token == null || token.Length != TokenLength) return false; + + foreach (var character in token) + { + var isHex = (character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'); + if (!isHex) return false; + } + + return true; + } + + /// + /// The token a staged path belongs to, or null if the path is not one of ours. + /// + private string? TokenOrNull(string? path) + { + if (path == null) return null; + if (!path.StartsWith(Prefix + "/", StringComparison.Ordinal)) return null; + + var extension = Path.GetExtension(path); + if (extension != ".json" && extension != ".nupkg") return null; + + var token = Path.GetFileNameWithoutExtension(path); + + return IsToken(token) ? token : null; + } + + /// + /// With accounts disabled there is no user to own an upload, so every upload shares + /// the one empty owner - the same identity the API key path has there. + /// + private static string Owner(string? ownerId) => ownerId ?? string.Empty; + + /// + /// Why a metadata read did not produce metadata. "Not there" and "not readable right + /// now" are different facts, and the sweep must not treat the second as the first. + /// + private enum StagedMetadataStatus + { + Readable, + + /// + /// The metadata could not be opened. It may be absent, or the store may be + /// unreachable or the file held open by something else. + /// + Unavailable, + + /// + /// The metadata was read and is not metadata, so it will never become readable. + /// + Unreadable, + } + + private readonly struct StagedMetadataRead + { + public StagedMetadataRead(StagedMetadataStatus status, StagedUpload? metadata) + { + Status = status; + Metadata = metadata; + } + + public StagedMetadataStatus Status { get; } + + public StagedUpload? Metadata { get; } + } + + internal class StagedUpload + { + public string? OwnerId { get; set; } + + public DateTime StagedAtUtc { get; set; } + } +} \ No newline at end of file diff --git a/src/BaGet.Core/Statistics/StatisticsService.cs b/src/BaGet.Core/Statistics/StatisticsService.cs new file mode 100644 index 000000000..28f7d0c75 --- /dev/null +++ b/src/BaGet.Core/Statistics/StatisticsService.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core; + +public class FeedStatistics +{ + public int PackageIds { get; set; } + + public int PackageVersions { get; set; } + + public long Downloads { get; set; } + + /// + /// The most downloaded package IDs, all versions together. + /// + public IReadOnlyList? TopPackages { get; set; } + + /// + /// The most recently published versions. + /// + public IReadOnlyList? RecentVersions { get; set; } +} + +public class PackageDownloads +{ + public string? Id { get; set; } + + /// + /// Null when the downloads are a whole package ID's. + /// + public string? Version { get; set; } + + public long Downloads { get; set; } + + public DateTime? Published { get; set; } +} + +/// +/// Feed-wide download statistics, from the per-version counts the database keeps. +/// There is no per-day history: a count only ever goes up. +/// +public class StatisticsService +{ + private const int ListSize = 10; + + private readonly IContext _context; + + public StatisticsService(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + /// False when the database cannot be queried for aggregates, such as Azure Table storage. + /// + public bool IsSupported => !(_context is NullContext); + + public async Task GetAsync(CancellationToken cancellationToken) + { + var listed = _context.Packages?.AsNoTracking().Where(p => p.Listed); + + #pragma warning disable CS8604 + var top = await listed + .GroupBy(p => p.Id) + .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) + .OrderByDescending(p => p.Downloads) + .ThenBy(p => p.Id) + .Take(ListSize) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + var recent = await listed + .OrderByDescending(p => p.Published) + .ThenByDescending(p => p.Key) + .Take(ListSize) + .Select(p => new PackageDownloads + { + Id = p.Id, + Version = p.OriginalVersionString ?? p.NormalizedVersionString, + Downloads = p.Downloads, + Published = p.Published, + }) + .ToListAsync(cancellationToken); + + return new FeedStatistics + { + PackageIds = await listed.Select(p => p.Id).Distinct().CountAsync(cancellationToken), + PackageVersions = await listed.CountAsync(cancellationToken), + Downloads = await listed.SumAsync(p => p.Downloads, cancellationToken), + TopPackages = top, + RecentVersions = recent, + }; + } + + /// + /// When each package ID was last published to, for the IDs that have a listed version. + /// Empty when is false. Only the versions a search with the same + /// prerelease and SemVer 2 filters would match are considered, so the date agrees with the + /// "last updated" order. + /// + public async Task> GetLastUpdatedAsync( + IReadOnlyCollection? packageIds, + CancellationToken cancellationToken, + bool includePrerelease = true, + bool includeSemVer2 = true) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (!IsSupported || packageIds == null || packageIds.Count == 0) return result; + + var lowered = packageIds.Select(id => id?.ToLower()).ToList(); + var packages = _context.Packages?.AsNoTracking(); + #pragma warning disable CS8604 + if (!includePrerelease) packages = packages.Where(p => !p.IsPrerelease); + if (!includeSemVer2) packages = packages.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); + #pragma warning restore CS8604 + + #pragma warning disable CS8602, CS8604 + var rows = await packages + .Where(p => p.Listed && lowered.Contains(p.Id.ToLower())) + .GroupBy(p => p.Id) + .Select(g => new { Id = g.Key, Published = g.Max(p => p.Published) }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + #pragma warning disable CS8604 + foreach (var row in rows) result[row.Id] = row.Published; + #pragma warning restore CS8604 + + return result; + } +} diff --git a/src/BaGet.Core/Storage/FileStorageService.cs b/src/BaGet.Core/Storage/FileStorageService.cs index 26d6f6ec0..41b29aeb0 100644 --- a/src/BaGet.Core/Storage/FileStorageService.cs +++ b/src/BaGet.Core/Storage/FileStorageService.cs @@ -1,118 +1,338 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Stores content on disk. Streaming uploads () grow a file under +/// in the store and are moved into place on commit (same volume, so atomic). +/// +public class FileStorageService : IStreamingStorageService, IListableStorageService { - /// - /// Stores content on disk. - /// - public class FileStorageService : IStorageService + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; + + /// Suffix of the temporary file a put writes before moving it into place; never listed. + internal const string TemporarySuffix = ".baget-tmp"; + + private readonly string _storePath; + + public FileStorageService(IOptionsSnapshot options) { - // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 - private const int DefaultCopyBufferSize = 81920; + if (options == null) throw new ArgumentNullException(nameof(options)); - private readonly string _storePath; + // Resolve relative path components ('.'/'..') and ensure there is a trailing slash. + #pragma warning disable CS8604 + _storePath = Path.GetFullPath(options.Value.Path); + #pragma warning restore CS8604 + if (!_storePath.EndsWith(Path.DirectorySeparatorChar.ToString())) + _storePath += Path.DirectorySeparatorChar; + } - public FileStorageService(IOptionsSnapshot options) - { - if (options == null) throw new ArgumentNullException(nameof(options)); + public Task GetAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - // Resolve relative path components ('.'/'..') and ensure there is a trailing slash. - _storePath = Path.GetFullPath(options.Value.Path); - if (!_storePath.EndsWith(Path.DirectorySeparatorChar.ToString())) - _storePath += Path.DirectorySeparatorChar; - } + path = GetFullPath(path); + var content = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - public Task GetAsync(string path, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(content); + } - path = GetFullPath(path); - var content = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(content); - } + var result = new Uri(GetFullPath(path)); - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(result); + } - var result = new Uri(GetFullPath(path)); + public async Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken = default) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + if (string.IsNullOrEmpty(contentType)) throw new ArgumentException("Content type is required", nameof(contentType)); - return Task.FromResult(result); - } + cancellationToken.ThrowIfCancellationRequested(); - public async Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken = default) - { - if (content == null) throw new ArgumentNullException(nameof(content)); - if (string.IsNullOrEmpty(contentType)) throw new ArgumentException("Content type is required", nameof(contentType)); + path = GetFullPath(path); - cancellationToken.ThrowIfCancellationRequested(); + // Ensure that the path exists. + #pragma warning disable CS8604 + Directory.CreateDirectory(Path.GetDirectoryName(path)); + #pragma warning restore CS8604 - path = GetFullPath(path); + // Write to a temporary file in the same folder and move it into place, so a failed or cancelled copy + // never leaves a truncated file at the final path (a later put would compare against it and conflict). + var temporaryPath = path + "." + Guid.NewGuid().ToString("N") + TemporarySuffix; - // Ensure that the path exists. - Directory.CreateDirectory(Path.GetDirectoryName(path)); + try + { + using (var fileStream = File.Open(temporaryPath, FileMode.CreateNew)) + { + await content.CopyToAsync(fileStream, DefaultCopyBufferSize, cancellationToken); + } + File.Move(temporaryPath, path); + return StoragePutResult.Success; + } + catch (IOException) when (File.Exists(path)) + { + using (var targetStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + content.Position = 0; + return content.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; + } + } + finally + { try { - using (var fileStream = File.Open(path, FileMode.CreateNew)) - { - await content.CopyToAsync(fileStream, DefaultCopyBufferSize, cancellationToken); - return StoragePutResult.Success; - } + File.Delete(temporaryPath); } - catch (IOException) when (File.Exists(path)) + catch (IOException) { - using (var targetStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - content.Position = 0; - return content.Matches(targetStream) - ? StoragePutResult.AlreadyExists - : StoragePutResult.Conflict; - } } + catch (UnauthorizedAccessException) + { + } + } + } + + public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + // GetFullPath keeps the prefix inside the store, exactly as for a read or write. + var fullPath = GetFullPath(pathPrefix); + + if (!Directory.Exists(fullPath)) + { + return Task.FromResult>(Array.Empty()); } - public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + var paths = Directory + .EnumerateFiles(fullPath, "*", SearchOption.AllDirectories) + .Where(path => !path.EndsWith(TemporarySuffix, StringComparison.Ordinal)) + .Select(path => path + .Substring(_storePath.Length) + .Replace(Path.DirectorySeparatorChar, '/') + .Replace(Path.AltDirectorySeparatorChar, '/')) + .ToList(); + + return Task.FromResult>(paths); + } + + public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + File.Delete(GetFullPath(path)); + } + catch (DirectoryNotFoundException) { - cancellationToken.ThrowIfCancellationRequested(); + } + + return Task.CompletedTask; + } + public Task BeginUploadAsync(string contentType, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + var id = Guid.NewGuid().ToString("N"); + Directory.CreateDirectory(Path.Combine(_storePath, StreamingStorage.UploadsFolder)); + using (File.Open(UploadPath(id), FileMode.CreateNew)) { } + + return Task.FromResult(id); + } + + public async Task AppendAsync(string uploadId, long offset, Stream chunk, CancellationToken cancellationToken = default) + { + if (chunk == null) throw new ArgumentNullException(nameof(chunk)); + + var path = UploadPath(uploadId); + var tracked = UploadDigestTracker.Shared.Track(uploadId, offset, chunk); + try + { + FileStream file; try { - File.Delete(GetFullPath(path)); + file = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.None, DefaultCopyBufferSize, useAsync: true); + } + catch (FileNotFoundException) + { + throw new StorageUploadNotFoundException(uploadId); } catch (DirectoryNotFoundException) { + throw new StorageUploadNotFoundException(uploadId); + } + + using (file) + { + if (file.Length != offset) throw new StorageUploadOffsetException(file.Length, offset); + + file.Seek(0, SeekOrigin.End); + await tracked.CopyToAsync(file, DefaultCopyBufferSize, cancellationToken).ConfigureAwait(false); + await file.FlushAsync(cancellationToken).ConfigureAwait(false); + + tracked.Complete(file.Length); + return file.Length; } + } + catch + { + tracked.Fail(); + throw; + } + } - return Task.CompletedTask; + public Task GetUploadLengthAsync(string uploadId, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (!Guid.TryParseExact(uploadId, "N", out _)) return Task.FromResult(null); + + var file = new FileInfo(UploadPath(uploadId)); + return Task.FromResult(file.Exists ? file.Length : null); + } + + public async Task CommitAsync(string uploadId, string path, string? expectedSha256, CancellationToken cancellationToken = default) + { + var part = new FileInfo(UploadPath(uploadId)); + if (!part.Exists) throw new StorageUploadNotFoundException(uploadId); + + var length = part.Length; + var sha = UploadDigestTracker.Shared.TryComplete(uploadId, length); + if (sha == null) + { + using var read = File.Open(part.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); + sha = await StreamingStorage.Sha256HexAsync(read, cancellationToken).ConfigureAwait(false); } - private string GetFullPath(string path) + if (expectedSha256 != null && !string.Equals(expectedSha256, sha, StringComparison.OrdinalIgnoreCase)) { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("Path is required", nameof(path)); - } + part.Delete(); + throw new StorageDigestMismatchException(expectedSha256, sha); + } - var fullPath = Path.GetFullPath(Path.Combine(_storePath, path)); + var target = GetFullPath(path); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); - // Verify path is under the _storePath. - if (!fullPath.StartsWith(_storePath, StringComparison.Ordinal) || - fullPath.Length == _storePath.Length) + try + { + File.Move(part.FullName, target, overwrite: false); + return new StorageCommitResult(StoragePutResult.Success, length, sha); + } + catch (IOException) when (File.Exists(target)) + { + string existing; + using (var stored = File.Open(target, FileMode.Open, FileAccess.Read, FileShare.Read)) { - throw new ArgumentException("Path resolves outside store path", nameof(path)); + existing = await StreamingStorage.Sha256HexAsync(stored, cancellationToken).ConfigureAwait(false); } - return fullPath; + part.Delete(); + return new StorageCommitResult( + string.Equals(existing, sha, StringComparison.Ordinal) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict, + length, + sha); + } + } + + public Task AbortAsync(string uploadId, CancellationToken cancellationToken = default) + { + UploadDigestTracker.Shared.Forget(uploadId); + if (!Guid.TryParseExact(uploadId, "N", out _)) return Task.CompletedTask; + + try + { + File.Delete(UploadPath(uploadId)); + } + catch (DirectoryNotFoundException) + { + } + + return Task.CompletedTask; + } + + public Task GetInfoAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + var file = new FileInfo(GetFullPath(path)); + return Task.FromResult(file.Exists ? new StorageBlobInfo(file.Length, null) : null); + } + + public Task GetRangeAsync(string path, long offset, long? length, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + FileStream file; + try + { + file = new FileStream(GetFullPath(path), FileMode.Open, FileAccess.Read, FileShare.Read, DefaultCopyBufferSize, useAsync: true); + } + catch (FileNotFoundException) + { + return Task.FromResult(null); + } + catch (DirectoryNotFoundException) + { + return Task.FromResult(null); + } + + try + { + var count = StreamingStorage.ResolveRange(file.Length, offset, length); + file.Seek(offset, SeekOrigin.Begin); + return Task.FromResult(new RangeReadStream(file, count)); + } + catch + { + file.Dispose(); + throw; } } -} + + // An id is a GUID in "N" form; anything else could climb out of the uploads folder. + private string UploadPath(string uploadId) + { + if (!Guid.TryParseExact(uploadId, "N", out _)) throw new StorageUploadNotFoundException(uploadId); + + return Path.Combine(_storePath, StreamingStorage.UploadsFolder, uploadId + ".part"); + } + + private string GetFullPath(string path) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("Path is required", nameof(path)); + } + + var fullPath = Path.GetFullPath(Path.Combine(_storePath, path)); + + // Verify path is under the _storePath. + if (!fullPath.StartsWith(_storePath, StringComparison.Ordinal) || + fullPath.Length == _storePath.Length) + { + throw new ArgumentException("Path resolves outside store path", nameof(path)); + } + + return fullPath; + } +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/IListableStorageService.cs b/src/BaGet.Core/Storage/IListableStorageService.cs new file mode 100644 index 000000000..be44553e0 --- /dev/null +++ b/src/BaGet.Core/Storage/IListableStorageService.cs @@ -0,0 +1,29 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// An optional capability of an : list what it holds under a +/// path prefix. Content that is only ever read back through the path that stored it does +/// not need this; collecting content whose paths nobody remembers - abandoned staged +/// uploads, for one - does. +/// +/// +/// A store that does not implement this cannot be swept, so a caller must degrade +/// rather than cast and assume. +/// +public interface IListableStorageService +{ + /// + /// The prefix to list, as a path of one or more segments ("staging"). + /// + /// A token to cancel the task. + /// + /// The path of every item under the prefix, relative to the store's root and + /// separated with "/", so each can be passed straight back to + /// . Empty if the prefix holds nothing. + /// + Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/IPackageStorageService.cs b/src/BaGet.Core/Storage/IPackageStorageService.cs index b16fbb55a..0d6922a68 100644 --- a/src/BaGet.Core/Storage/IPackageStorageService.cs +++ b/src/BaGet.Core/Storage/IPackageStorageService.cs @@ -3,70 +3,86 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Stores packages' content. Packages' state are stored by the +/// . +/// +public interface IPackageStorageService { /// - /// Stores packages' content. Packages' state are stored by the - /// . + /// Persist a package's content to storage. This operation MUST NOT store the content if a + /// package with the same id/version but different content has already been stored. /// - public interface IPackageStorageService - { - /// - /// Persist a package's content to storage. This operation MUST fail if a package - /// with the same id/version but different content has already been stored. - /// - /// The package's metadata. - /// The package's nupkg stream. - /// The package's nuspec stream. - /// The package's readme stream, or null if none. - /// The package's icon stream, or null if none. - /// - /// - Task SavePackageContentAsync( - Package package, - Stream packageStream, - Stream nuspecStream, - Stream readmeStream, - Stream iconStream, - CancellationToken cancellationToken); + /// The package's metadata. + /// The package's nupkg stream. + /// The package's nuspec stream. + /// The package's readme stream, or null if none. + /// The package's icon stream, or null if none. + /// + /// The result of the attempted save operation. + Task SavePackageContentAsync( + Package package, + Stream? packageStream, + Stream nuspecStream, + Stream? readmeStream, + Stream? iconStream, + CancellationToken cancellationToken); - /// - /// Retrieve a package's nupkg stream. - /// - /// The package's id. - /// The package's version. - /// - /// The package's nupkg stream. - Task GetPackageStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Retrieve a package's nupkg stream. + /// + /// The package's id. + /// The package's version. + /// + /// The package's nupkg stream, or if it is missing from storage. + Task GetPackageStreamAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Retrieve a package's nuspec stream. - /// - /// The package's id. - /// The package's version. - /// - /// The package's nuspec stream. - Task GetNuspecStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Retrieve a package's nuspec stream. + /// + /// The package's id. + /// The package's version. + /// + /// The package's nuspec stream, or if it is missing from storage. + Task GetNuspecStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Retrieve a package's readme stream. - /// - /// The package's id. - /// The package's version. - /// - /// The package's readme stream. - Task GetReadmeStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Retrieve a package's readme stream. + /// + /// The package's id. + /// The package's version. + /// + /// The package's readme stream, or if it is missing from storage. + Task GetReadmeStreamAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); - Task GetIconStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + Task GetIconStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Remove a package's content from storage. This operation SHOULD succeed - /// even if the package does not exist. - /// - /// The package's id. - /// The package's version. - /// - /// - Task DeleteAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } + /// + /// Remove a package's content from storage. This operation SHOULD succeed + /// even if the package does not exist. + /// + /// The package's id. + /// The package's version. + /// + /// + Task DeleteAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); } + +/// +/// The result of a operation. +/// +public enum PackageSaveResult +{ + /// + /// Content for this package's id/version has already been stored and does not + /// match the content that was submitted. Nothing further was stored. + /// + Conflict, + + /// + /// The package's content was stored, or the exact same content had already been stored. + /// + Success, +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/IStorageService.cs b/src/BaGet.Core/Storage/IStorageService.cs index 50e122f1a..b322273fc 100644 --- a/src/BaGet.Core/Storage/IStorageService.cs +++ b/src/BaGet.Core/Storage/IStorageService.cs @@ -3,82 +3,81 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A low-level storage abstraction. +/// +/// +/// This is used to store: +/// +/// * Packages, through +/// * Symbols, through +/// +/// This storage abstraction has implementations for disk, +/// Azure Blob Storage, Amazon Web Services S3, and Google Cloud Storage. +/// +public interface IStorageService { /// - /// A low-level storage abstraction. + /// Get content from storage. /// - /// - /// This is used to store: - /// - /// * Packages, through - /// * Symbols, through - /// - /// This storage abstraction has implementations for disk, - /// Azure Blob Storage, Amazon Web Services S3, and Google Cloud Storage. - /// - public interface IStorageService - { - /// - /// Get content from storage. - /// - /// The content's path. - /// A token to cancel the task. - /// The path's content or null if the content does not exist. - Task GetAsync(string path, CancellationToken cancellationToken = default); + /// The content's path. + /// A token to cancel the task. + /// The path's content or null if the content does not exist. + Task GetAsync(string path, CancellationToken cancellationToken = default); - /// - /// Get a URI that can be used to download the content. - /// - /// The content's path. - /// A token to cancel the task. - /// - /// The content's URI. This may be a local file. Returns null if the content - /// does not exist or if a URI could not be created. - /// - Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default); + /// + /// Get a URI that can be used to download the content. + /// + /// The content's path. + /// A token to cancel the task. + /// + /// The content's URI. This may be a local file. Returns null if the content + /// does not exist or if a URI could not be created. + /// + Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default); - /// - /// Store content into storage. - /// - /// The path at which to store the content. - /// The content to store at the given path. - /// The type of content that is being stored. - /// A token to cancel the task. - /// The result of the put operation. - Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken = default); + /// + /// Store content into storage. + /// + /// The path at which to store the content. + /// The content to store at the given path. + /// The type of content that is being stored. + /// A token to cancel the task. + /// The result of the put operation. + Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken = default); - /// - /// Remove content from storage. - /// - /// The path to the content to delete. - /// A token to cancel the task. - /// A task that completes when the content has been deleted. - Task DeleteAsync(string path, CancellationToken cancellationToken = default); - } + /// + /// Remove content from storage. + /// + /// The path to the content to delete. + /// A token to cancel the task. + /// A task that completes when the content has been deleted. + Task DeleteAsync(string path, CancellationToken cancellationToken = default); +} +/// +/// The result of a operation. +/// +public enum StoragePutResult +{ /// - /// The result of a operation. + /// The given path is already used to store different content. /// - public enum StoragePutResult - { - /// - /// The given path is already used to store different content. - /// - Conflict, + Conflict, - /// - /// This content is already stored at the given path. - /// - AlreadyExists, + /// + /// This content is already stored at the given path. + /// + AlreadyExists, - /// - /// The content was sucessfully stored. - /// - Success, - } -} + /// + /// The content was sucessfully stored. + /// + Success, +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/IStreamingStorageService.cs b/src/BaGet.Core/Storage/IStreamingStorageService.cs new file mode 100644 index 000000000..ee2a8db85 --- /dev/null +++ b/src/BaGet.Core/Storage/IStreamingStorageService.cs @@ -0,0 +1,136 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// An optional capability of an : store content of any size without ever holding it in memory, +/// in several requests, and read it back by range. Docker layers reach many gigabytes and arrive as chunked uploads +/// (PATCH with Content-Range), are verified against a digest and are served with HEAD and range +/// GET; takes a whole stream in one call and the providers buffer it. +/// +/// +/// Life of an upload. returns an opaque id; adds bytes at +/// the offset the store already holds (a different offset is refused with , which +/// carries the real length so a client can resume); makes the content visible at its final path and +/// removes the upload; discards it. The final path is only given at commit because a content-addressed +/// path (a digest) is not known before the last byte. An upload that is neither committed nor aborted stays in the store: the +/// caller owns its lifetime (sessions expire, the caller aborts). +/// Memory. At most one part buffer per request (a few MiB, never the blob). The SHA-256 is computed while the bytes +/// stream through (); when a node lost that running state (restart, another node took the next +/// chunk) the digest is recomputed from the stored content at commit, still streaming. +/// Concurrency. One writer per upload; the same upload appended by two requests at once is undefined (the +/// protocols forbid it). Different uploads, and reads, are independent. +/// A caller must not cast and assume: a store that does not implement this () +/// cannot hold a format that needs it, see . +/// +public interface IStreamingStorageService : IStorageService +{ + /// Starts an empty upload. + /// The content type the committed blob will carry. + /// A token to cancel the task. + /// An opaque id (URL-safe), valid until committed or aborted. + Task BeginUploadAsync(string contentType, CancellationToken cancellationToken = default); + + /// Appends to the upload. + /// The id from . + /// Where the chunk starts; must equal the upload's current length. + /// The bytes, read once and forward only (it may be a request body). + /// A token to cancel the task. + /// The upload's length after the chunk. + /// No such upload. + /// is not the upload's length. + Task AppendAsync(string uploadId, long offset, Stream chunk, CancellationToken cancellationToken = default); + + /// The upload's current length (what a client resumes from), or null when there is no such upload. + Task GetUploadLengthAsync(string uploadId, CancellationToken cancellationToken = default); + + /// Stores the upload at and removes it. + /// The id from . + /// The final path, as for . + /// The lower-case hex SHA-256 the content must have, or null to skip the check. + /// A token to cancel the task. + /// + /// ; when the path holds identical content + /// (the upload is discarded); when it holds different content (discarded as well). + /// + /// No such upload. + /// The content does not have ; nothing is + /// stored at and the upload is discarded. + Task CommitAsync(string uploadId, string path, string? expectedSha256, CancellationToken cancellationToken = default); + + /// Discards the upload and what it holds; unknown ids are ignored. + Task AbortAsync(string uploadId, CancellationToken cancellationToken = default); + + /// What a HEAD needs: the size (and type, where the store keeps it), or null when the path holds nothing. + Task GetInfoAsync(string path, CancellationToken cancellationToken = default); + + /// + /// Reads bytes from (to the end when null) as a stream that is never + /// buffered whole, or null when the path holds nothing. + /// + /// is past the end, or an argument is negative. + Task GetRangeAsync(string path, long offset, long? length, CancellationToken cancellationToken = default); +} + +/// A stored blob as reports it. +/// Size in bytes. +/// The stored content type, or null when the store does not keep one (the file system). +public sealed record StorageBlobInfo(long Length, string? ContentType); + +/// The outcome of . +/// Whether the content was stored, was already there, or clashed. +/// Size in bytes of the committed content. +/// Lower-case hex SHA-256 of the committed content. +public sealed record StorageCommitResult(StoragePutResult Result, long Length, string Sha256); + +/// The upload id is unknown (never begun, committed, aborted or lost). +public sealed class StorageUploadNotFoundException : Exception +{ + /// The id asked for. + public StorageUploadNotFoundException(string uploadId) + : base("The upload does not exist.") => UploadId = uploadId; + + /// The id asked for. + public string UploadId { get; } +} + +/// A chunk did not start where the upload ends (OCI answers 416 with this length). +public sealed class StorageUploadOffsetException : Exception +{ + /// What the store holds. + /// Where the chunk claimed to start. + public StorageUploadOffsetException(long actualLength, long requestedOffset) + : base($"The chunk starts at {requestedOffset} but the upload holds {actualLength} bytes.") + { + ActualLength = actualLength; + RequestedOffset = requestedOffset; + } + + /// What the store holds. + public long ActualLength { get; } + + /// Where the chunk claimed to start. + public long RequestedOffset { get; } +} + +/// The committed content is not what the caller announced. +public sealed class StorageDigestMismatchException : Exception +{ + /// The announced SHA-256. + /// The computed SHA-256. + public StorageDigestMismatchException(string expected, string actual) + : base("The content does not have the expected digest.") + { + Expected = expected; + Actual = actual; + } + + /// The announced SHA-256 (hex). + public string Expected { get; } + + /// The computed SHA-256 (hex). + public string Actual { get; } +} diff --git a/src/BaGet.Core/Storage/ISymbolRegistry.cs b/src/BaGet.Core/Storage/ISymbolRegistry.cs new file mode 100644 index 000000000..44f9cc214 --- /dev/null +++ b/src/BaGet.Core/Storage/ISymbolRegistry.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// The PDBs a package version's symbol package contributed, so they can be listed and deleted per version. +/// Rows exist only for symbols indexed after the registry was introduced: older PDBs are keyed by file and key +/// alone in storage, which does not say which package they came from, and cannot be listed per package. +/// Operates on the current repository. A database without relational tables (Azure Table) records nothing. +/// +public interface ISymbolRegistry +{ + /// Whether this database can record symbols (false for Azure Table). + bool IsSupported { get; } + + /// Records PDBs for a version; an entry already recorded is left alone. + Task RecordAsync(string packageId, NuGetVersion version, IEnumerable symbols, CancellationToken cancellationToken); + + /// The PDBs recorded for a version, ordered by file name. + Task> ListAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Deletes the PDBs recorded for a version (database rows and stored content). Content another version of + /// the repository still records is kept. + /// + /// How many PDBs were recorded for the version and are now gone from it. + Task DeleteAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken); +} + +/// A PDB as the symbol server addresses it. +/// The PDB's file name. +/// Signature GUID followed by the age. +public readonly record struct SymbolReference(string FileName, string Key); diff --git a/src/BaGet.Core/Storage/ISymbolStorageService.cs b/src/BaGet.Core/Storage/ISymbolStorageService.cs index f8681ab6a..c6a59fcac 100644 --- a/src/BaGet.Core/Storage/ISymbolStorageService.cs +++ b/src/BaGet.Core/Storage/ISymbolStorageService.cs @@ -2,34 +2,41 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Stores the content of symbols, also known as PDBs. +/// +public interface ISymbolStorageService { /// - /// Stores the content of symbols, also known as PDBs. + /// Persist a portable PDB's content to storage. This operation MUST fail if a PDB + /// with the same key but different content has already been stored. + /// + /// The portable PDB's file name. + /// The portable PDB's Signature GUID followed by its age. + /// The PDB's content stream. + /// + /// + Task SavePortablePdbContentAsync( + string file, + string key, + Stream pdbStream, + CancellationToken cancellationToken); + + /// + /// Retrieve a portable PDB's content stream. /// - public interface ISymbolStorageService - { - /// - /// Persist a portable PDB's content to storage. This operation MUST fail if a PDB - /// with the same key but different content has already been stored. - /// - /// The portable PDB's file name. - /// The portable PDB's Signature GUID followed by its age. - /// The PDB's content stream. - /// - /// - Task SavePortablePdbContentAsync( - string file, - string key, - Stream pdbStream, - CancellationToken cancellationToken); + /// The portable PDB's file name. + /// The portable PDB's Signature GUID followed by its age. + /// The portable PDB's stream, or null if it does not exist. + Task GetPortablePdbContentStreamOrNullAsync(string file, string key); - /// - /// Retrieve a portable PDB's content stream. - /// - /// The portable PDB's file name. - /// The portable PDB's Signature GUID followed by its age. - /// The portable PDB's stream, or null if it does not exist. - Task GetPortablePdbContentStreamOrNullAsync(string file, string key); - } -} + /// + /// Delete a portable PDB's stored content. Deleting content that does not exist is not an error. + /// + /// The portable PDB's file name. + /// The portable PDB's Signature GUID followed by its age. + /// + Task DeletePortablePdbContentAsync(string file, string key, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/NullStorageService.cs b/src/BaGet.Core/Storage/NullStorageService.cs index 42aea93a8..8fc4ef98f 100644 --- a/src/BaGet.Core/Storage/NullStorageService.cs +++ b/src/BaGet.Core/Storage/NullStorageService.cs @@ -1,37 +1,76 @@ using System; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A minimal storage implementation, used for advanced scenarios. It is a streaming store that holds nothing: uploaded +/// bytes are counted and discarded, nothing is ever readable, and a commit finds no upload. +/// +public class NullStorageService : IStreamingStorageService, IListableStorageService { + public Task BeginUploadAsync(string contentType, CancellationToken cancellationToken = default) + => Task.FromResult(Guid.NewGuid().ToString("N")); + + public async Task AppendAsync(string uploadId, long offset, Stream chunk, CancellationToken cancellationToken = default) + { + var buffer = new byte[81920]; + var total = offset; + int read; + while ((read = await chunk.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false)) > 0) total += read; + return total; + } + + public Task GetUploadLengthAsync(string uploadId, CancellationToken cancellationToken = default) + => Task.FromResult(null); + + public Task CommitAsync(string uploadId, string path, string? expectedSha256, CancellationToken cancellationToken = default) + => throw new StorageUploadNotFoundException(uploadId); + + public Task AbortAsync(string uploadId, CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task GetInfoAsync(string path, CancellationToken cancellationToken = default) + => Task.FromResult(null); + + public Task GetRangeAsync(string path, long offset, long? length, CancellationToken cancellationToken = default) + => Task.FromResult(null); + + public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + return Task.CompletedTask; + } + /// - /// A minimal storage implementation, used for advanced scenarios. + /// A store that holds nothing lists nothing, so a sweep over it has nothing to do. /// - public class NullStorageService : IStorageService + public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + return Task.FromResult>(Array.Empty()); + } + + public Task GetAsync(string path, CancellationToken cancellationToken = default) + { + #pragma warning disable CS8625 + return Task.FromResult(null); + #pragma warning restore CS8625 + } + + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + #pragma warning disable CS8625 + return Task.FromResult(null); + #pragma warning restore CS8625 + } + + public Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken = default) { - public Task DeleteAsync(string path, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } - - public Task GetAsync(string path, CancellationToken cancellationToken = default) - { - return Task.FromResult(null); - } - - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) - { - return Task.FromResult(null); - } - - public Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken = default) - { - return Task.FromResult(StoragePutResult.Success); - } + return Task.FromResult(StoragePutResult.Success); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/PackageStorageService.cs b/src/BaGet.Core/Storage/PackageStorageService.cs index 55731b004..0846dc7fd 100644 --- a/src/BaGet.Core/Storage/PackageStorageService.cs +++ b/src/BaGet.Core/Storage/PackageStorageService.cs @@ -1,243 +1,254 @@ using System; using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageStorageService : IPackageStorageService { - public class PackageStorageService : IPackageStorageService + private const string PackagesPathPrefix = "packages"; + + // See: https://github.com/NuGet/NuGetGallery/blob/73a5c54629056b25b3a59960373e8fef88abff36/src/NuGetGallery.Core/CoreConstants.cs#L19 + private const string PackageContentType = "binary/octet-stream"; + private const string NuspecContentType = "text/plain"; + private const string ReadmeContentType = "text/markdown"; + private const string IconContentType = "image/xyz"; + + private readonly IStorageService _storage; + private readonly ILogger _logger; + private readonly IRepositoryContext? _repository; + + /// + /// The repository whose files are read and written: the default one keeps packages/…, any other + /// repos/{name}/packages/… (see ). Null means the default repository. + /// + public PackageStorageService( + IStorageService storage, + ILogger logger, + IRepositoryContext? repository = null) { - private const string PackagesPathPrefix = "packages"; - - // See: https://github.com/NuGet/NuGetGallery/blob/73a5c54629056b25b3a59960373e8fef88abff36/src/NuGetGallery.Core/CoreConstants.cs#L19 - private const string PackageContentType = "binary/octet-stream"; - private const string NuspecContentType = "text/plain"; - private const string ReadmeContentType = "text/markdown"; - private const string IconContentType = "image/xyz"; - - private readonly IStorageService _storage; - private readonly ILogger _logger; + _repository = repository; + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public PackageStorageService( - IStorageService storage, - ILogger logger) + public async Task SavePackageContentAsync( + Package? package, + Stream? packageStream, + Stream? nuspecStream, + Stream? readmeStream, + Stream? iconStream, + CancellationToken cancellationToken = default) + { + package = package ?? throw new ArgumentNullException(nameof(package)); + packageStream = packageStream ?? throw new ArgumentNullException(nameof(packageStream)); + nuspecStream = nuspecStream ?? throw new ArgumentNullException(nameof(nuspecStream)); + + var lowercasedId = package.Id?.ToLowerInvariant(); + var lowercasedNormalizedVersion = package.NormalizedVersionString?.ToLowerInvariant(); + + var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); + var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); + var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); + var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); + + _logger.LogInformation( + "Storing package {PackageId} {PackageVersion} at {Path}...", + lowercasedId, + lowercasedNormalizedVersion, + packagePath); + + // Store the package. + var result = await _storage.PutAsync(packagePath, packageStream, PackageContentType, cancellationToken); + if (result == StoragePutResult.Conflict) { - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _logger.LogInformation( + "Could not store package {PackageId} {PackageVersion} at {Path} due to conflict", + lowercasedId, + lowercasedNormalizedVersion, + packagePath); + + return PackageSaveResult.Conflict; } - public async Task SavePackageContentAsync( - Package package, - Stream packageStream, - Stream nuspecStream, - Stream readmeStream, - Stream iconStream, - CancellationToken cancellationToken = default) - { - package = package ?? throw new ArgumentNullException(nameof(package)); - packageStream = packageStream ?? throw new ArgumentNullException(nameof(packageStream)); - nuspecStream = nuspecStream ?? throw new ArgumentNullException(nameof(nuspecStream)); + // Store the package's nuspec. + _logger.LogInformation( + "Storing package {PackageId} {PackageVersion} nuspec at {Path}...", + lowercasedId, + lowercasedNormalizedVersion, + nuspecPath); - var lowercasedId = package.Id.ToLowerInvariant(); - var lowercasedNormalizedVersion = package.NormalizedVersionString.ToLowerInvariant(); + result = await _storage.PutAsync(nuspecPath, nuspecStream, NuspecContentType, cancellationToken); + if (result == StoragePutResult.Conflict) + { + _logger.LogInformation( + "Could not store package {PackageId} {PackageVersion} nuspec at {Path} due to conflict", + lowercasedId, + lowercasedNormalizedVersion, + nuspecPath); - var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); - var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); - var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); - var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); + return PackageSaveResult.Conflict; + } + // Store the package's readme, if one exists. + if (readmeStream != null) + { _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} at {Path}...", + "Storing package {PackageId} {PackageVersion} readme at {Path}...", lowercasedId, lowercasedNormalizedVersion, - packagePath); + readmePath); - // Store the package. - var result = await _storage.PutAsync(packagePath, packageStream, PackageContentType, cancellationToken); + result = await _storage.PutAsync(readmePath, readmeStream, ReadmeContentType, cancellationToken); if (result == StoragePutResult.Conflict) { - // TODO: This should be returned gracefully with an enum. _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} at {Path} due to conflict", + "Could not store package {PackageId} {PackageVersion} readme at {Path} due to conflict", lowercasedId, lowercasedNormalizedVersion, - packagePath); + readmePath); - throw new InvalidOperationException($"Failed to store package {lowercasedId} {lowercasedNormalizedVersion} due to conflict"); + return PackageSaveResult.Conflict; } + } - // Store the package's nuspec. + // Store the package's icon, if one exists. + if (iconStream != null) + { _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} nuspec at {Path}...", + "Storing package {PackageId} {PackageVersion} icon at {Path}...", lowercasedId, lowercasedNormalizedVersion, - nuspecPath); + iconPath); - result = await _storage.PutAsync(nuspecPath, nuspecStream, NuspecContentType, cancellationToken); + result = await _storage.PutAsync(iconPath, iconStream, IconContentType, cancellationToken); if (result == StoragePutResult.Conflict) { - // TODO: This should be returned gracefully with an enum. _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} nuspec at {Path} due to conflict", + "Could not store package {PackageId} {PackageVersion} icon at {Path} due to conflict", lowercasedId, lowercasedNormalizedVersion, - nuspecPath); + iconPath); - throw new InvalidOperationException($"Failed to store package {lowercasedId} {lowercasedNormalizedVersion} nuspec due to conflict"); + return PackageSaveResult.Conflict; } + } - // Store the package's readme, if one exists. - if (readmeStream != null) - { - _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} readme at {Path}...", - lowercasedId, - lowercasedNormalizedVersion, - readmePath); + _logger.LogInformation( + "Finished storing package {PackageId} {PackageVersion}", + lowercasedId, + lowercasedNormalizedVersion); - result = await _storage.PutAsync(readmePath, readmeStream, ReadmeContentType, cancellationToken); - if (result == StoragePutResult.Conflict) - { - // TODO: This should be returned gracefully with an enum. - _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} readme at {Path} due to conflict", - lowercasedId, - lowercasedNormalizedVersion, - readmePath); - - throw new InvalidOperationException($"Failed to store package {lowercasedId} {lowercasedNormalizedVersion} readme due to conflict"); - } - } + return PackageSaveResult.Success; + } - // Store the package's icon, if one exists. - if (iconStream != null) - { - _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} icon at {Path}...", - lowercasedId, - lowercasedNormalizedVersion, - iconPath); + public async Task GetPackageStreamAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, PackagePath, cancellationToken); + } - result = await _storage.PutAsync(iconPath, iconStream, IconContentType, cancellationToken); - if (result == StoragePutResult.Conflict) - { - // TODO: This should be returned gracefully with an enum. - _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} icon at {Path} due to conflict", - lowercasedId, - lowercasedNormalizedVersion, - iconPath); - - throw new InvalidOperationException($"Failed to store package {lowercasedId} {lowercasedNormalizedVersion} icon"); - } - } + public async Task GetNuspecStreamAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, NuspecPath, cancellationToken); + } - _logger.LogInformation( - "Finished storing package {PackageId} {PackageVersion}", - lowercasedId, - lowercasedNormalizedVersion); - } + public async Task GetReadmeStreamAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, ReadmePath, cancellationToken); + } - public async Task GetPackageStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await GetStreamAsync(id, version, PackagePath, cancellationToken); - } + public async Task GetIconStreamAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, IconPath, cancellationToken); + } - public async Task GetNuspecStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await GetStreamAsync(id, version, NuspecPath, cancellationToken); - } + public async Task DeleteAsync(string? id, NuGetVersion version, CancellationToken cancellationToken) + { + var lowercasedId = id?.ToLowerInvariant(); + var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); + + var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); + var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); + var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); + var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); + + await _storage.DeleteAsync(packagePath, cancellationToken); + await _storage.DeleteAsync(nuspecPath, cancellationToken); + await _storage.DeleteAsync(readmePath, cancellationToken); + await _storage.DeleteAsync(iconPath, cancellationToken); + } - public async Task GetReadmeStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await GetStreamAsync(id, version, ReadmePath, cancellationToken); - } + private async Task GetStreamAsync( + string? id, + NuGetVersion version, + Func pathFunc, + CancellationToken cancellationToken) + { + var lowercasedId = id?.ToLowerInvariant(); + var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); + var path = pathFunc(lowercasedId, lowercasedNormalizedVersion); - public async Task GetIconStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + try { - return await GetStreamAsync(id, version, IconPath, cancellationToken); + return await _storage.GetAsync(path, cancellationToken); } - - public async Task DeleteAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + catch (DirectoryNotFoundException) { - var lowercasedId = id.ToLowerInvariant(); - var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); - - var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); - var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); - var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); - var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); - - await _storage.DeleteAsync(packagePath, cancellationToken); - await _storage.DeleteAsync(nuspecPath, cancellationToken); - await _storage.DeleteAsync(readmePath, cancellationToken); - await _storage.DeleteAsync(iconPath, cancellationToken); + // The "packages" prefix was lowercased, which was a breaking change + // on filesystems that are case sensitive. Handle this case to help + // users migrate to the latest version of BaGet. + // See https://github.com/pieroviano/BaGet/issues/298 + _logger.LogError( + $"Unable to find the '{PackagesPathPrefix}' folder. " + + "If you've recently upgraded BaGet Extension, please make sure this folder starts with a lowercased letter. " + + "For more information, please see https://github.com/pieroviano/BaGet/issues/298"); + // If content is referenced in the DB but missing on disk, return null + // so callers handle the missing content gracefully instead of + // throwing an unhandled exception. + return null; } - - private async Task GetStreamAsync( - string id, - NuGetVersion version, - Func pathFunc, - CancellationToken cancellationToken) + catch (FileNotFoundException) { - var lowercasedId = id.ToLowerInvariant(); - var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); - var path = pathFunc(lowercasedId, lowercasedNormalizedVersion); - - try - { - return await _storage.GetAsync(path, cancellationToken); - } - catch (DirectoryNotFoundException) - { - // The "packages" prefix was lowercased, which was a breaking change - // on filesystems that are case sensitive. Handle this case to help - // users migrate to the latest version of BaGet. - // See https://github.com/loic-sharma/BaGet/issues/298 - _logger.LogError( - $"Unable to find the '{PackagesPathPrefix}' folder. " + - "If you've recently upgraded BaGet, please make sure this folder starts with a lowercased letter. " + - "For more information, please see https://github.com/loic-sharma/BaGet/issues/298"); - throw; - } + // The requested file doesn't exist on disk. Log and return null so callers + // treat the content as missing instead of crashing the request. + _logger.LogWarning("Requested file not found on disk at path: {Path}", path); + return null; } + } - private string PackagePath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - $"{lowercasedId}.{lowercasedNormalizedVersion}.nupkg"); - } + private string PackagePath(string? lowercasedId, string? lowercasedNormalizedVersion) + { + return PathFor(lowercasedId, lowercasedNormalizedVersion, $"{lowercasedId}.{lowercasedNormalizedVersion}.nupkg"); + } - private string NuspecPath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - $"{lowercasedId}.nuspec"); - } + private string NuspecPath(string? lowercasedId, string? lowercasedNormalizedVersion) + { + return PathFor(lowercasedId, lowercasedNormalizedVersion, $"{lowercasedId}.nuspec"); + } - private string ReadmePath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - "readme"); - } + private string ReadmePath(string? lowercasedId, string? lowercasedNormalizedVersion) + { + return PathFor(lowercasedId, lowercasedNormalizedVersion, "readme"); + } - private string IconPath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - "icon"); - } + private string IconPath(string? lowercasedId, string? lowercasedNormalizedVersion) + { + return PathFor(lowercasedId, lowercasedNormalizedVersion, "icon"); + } + + private string PathFor(string? lowercasedId, string? lowercasedNormalizedVersion, string fileName) + { + var repository = _repository?.Current ?? RepositoryInfo.Default; + + #pragma warning disable CS8604 + return Path.Combine( + RepositoryStorage.Segments(repository) + .Concat(new string[] { PackagesPathPrefix, lowercasedId!, lowercasedNormalizedVersion!, fileName }) + .ToArray()); + #pragma warning restore CS8604 } } diff --git a/src/BaGet.Core/Storage/RangeReadStream.cs b/src/BaGet.Core/Storage/RangeReadStream.cs new file mode 100644 index 000000000..4fede7518 --- /dev/null +++ b/src/BaGet.Core/Storage/RangeReadStream.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// Exposes at most length bytes of a stream, from where it is; disposing disposes the inner stream. +public sealed class RangeReadStream : Stream +{ + private readonly Stream _inner; + private long _remaining; + + /// The stream, already positioned at the range start. + /// How many bytes to expose. + public RangeReadStream(Stream inner, long length) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); + _remaining = length; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_remaining <= 0 || buffer.Length == 0) return 0; + + var read = await _inner.ReadAsync(buffer.Slice(0, (int)Math.Min(buffer.Length, _remaining)), cancellationToken).ConfigureAwait(false); + _remaining -= read; + return read; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override int Read(byte[] buffer, int offset, int count) + { + if (_remaining <= 0) return 0; + + var read = _inner.Read(buffer, offset, (int)Math.Min(count, _remaining)); + _remaining -= read; + return read; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) _inner.Dispose(); + base.Dispose(disposing); + } +} diff --git a/src/BaGet.Core/Storage/StreamPartitioner.cs b/src/BaGet.Core/Storage/StreamPartitioner.cs new file mode 100644 index 000000000..d249ad48b --- /dev/null +++ b/src/BaGet.Core/Storage/StreamPartitioner.cs @@ -0,0 +1,63 @@ +using System; +using System.Buffers; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Cuts a forward-only stream into parts of a fixed size without holding more than one part: multipart APIs (S3, OSS, Azure +/// blocks, GCS resumable) want parts of a minimum size, while a chunk of a chunked upload may be any size. +/// +public static class StreamPartitioner +{ + /// + /// Reads to its end, handing every full bytes to + /// (the memory is only valid during the call), and returns the remainder (shorter than a part; + /// possibly empty) that the caller keeps for the next chunk or sends as the last part. + /// + /// The bytes to cut. + /// Bytes that come before (the previous chunk's remainder); shorter than a part. + /// The part size; positive. + /// Stores one part. + /// A token to cancel the task. + public static async Task SplitAsync( + Stream source, + ReadOnlyMemory carry, + int partSize, + Func, CancellationToken, Task> onPart, + CancellationToken cancellationToken) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (onPart == null) throw new ArgumentNullException(nameof(onPart)); + if (partSize <= 0) throw new ArgumentOutOfRangeException(nameof(partSize)); + if (carry.Length >= partSize) throw new ArgumentException("The carried bytes are a whole part or more.", nameof(carry)); + + var buffer = ArrayPool.Shared.Rent(partSize); + try + { + carry.CopyTo(buffer); + var filled = carry.Length; + + while (true) + { + var read = await source.ReadAsync(buffer.AsMemory(filled, partSize - filled), cancellationToken).ConfigureAwait(false); + if (read == 0) break; + + filled += read; + if (filled == partSize) + { + await onPart(buffer.AsMemory(0, partSize), cancellationToken).ConfigureAwait(false); + filled = 0; + } + } + + return buffer.AsSpan(0, filled).ToArray(); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } +} diff --git a/src/BaGet.Core/Storage/StreamingStorage.cs b/src/BaGet.Core/Storage/StreamingStorage.cs new file mode 100644 index 000000000..a6f1c2183 --- /dev/null +++ b/src/BaGet.Core/Storage/StreamingStorage.cs @@ -0,0 +1,181 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// Helpers shared by the providers and their callers. +public static class StreamingStorage +{ + /// The folder (and key prefix) in which providers keep uploads that are not committed yet. + public const string UploadsFolder = ".uploads"; + + /// Whether can hold streaming uploads and range reads. + public static bool IsSupported(IStorageService? storage) => storage is IStreamingStorageService; + + /// Returns as a streaming store. + /// The configured store. + /// What needs it, for the message ("Docker repositories"). + /// The store cannot stream. + public static IStreamingStorageService Require(IStorageService? storage, string purpose) + => storage as IStreamingStorageService + ?? throw new NotSupportedException( + $"{purpose} need a storage provider that streams large content (multipart upload and range reads); " + + $"{(storage == null ? "no storage is configured" : storage.GetType().Name + " does not")}. " + + "Use Storage:Type FileSystem, AwsS3, AzureBlobStorage, GoogleCloud or AliyunOss."); + + /// The SHA-256 of a stream, lower-case hex, read once in small blocks. + public static async Task Sha256HexAsync(Stream content, CancellationToken cancellationToken = default) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[81920]; + int read; + while ((read = await content.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false)) > 0) + { + hash.AppendData(buffer, 0, read); + } + + return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); + } + + /// The SHA-256 of bytes already in memory, lower-case hex. + public static string Sha256Hex(byte[] content) => Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant(); + + /// The SHA-256 (hex) of what holds at , streamed; null when absent. + public static async Task Sha256HexAsync(IStreamingStorageService storage, string path, CancellationToken cancellationToken = default) + { + using var stream = await storage.GetRangeAsync(path, 0, null, cancellationToken).ConfigureAwait(false); + return stream == null ? null : await Sha256HexAsync(stream, cancellationToken).ConfigureAwait(false); + } + + /// Whether is a lower-case hex SHA-256. + public static bool IsSha256Hex(string? value) + { + if (value == null || value.Length != 64) return false; + foreach (var c in value) + { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; + } + + return true; + } + + /// Throws unless is null or equals . + /// They differ. + public static void VerifyDigest(string? expected, string actual) + { + if (expected != null && !string.Equals(expected, actual, StringComparison.OrdinalIgnoreCase)) + { + throw new StorageDigestMismatchException(expected, actual); + } + } + + /// Validates / against a blob of bytes and returns the byte count to read. + /// Negative, or the offset is past the end. + public static long ResolveRange(long size, long offset, long? length) + { + if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); + if (offset > size) throw new ArgumentOutOfRangeException(nameof(offset), "The offset is past the end of the blob."); + + return Math.Min(length ?? long.MaxValue, size - offset); + } +} + +/// Stream helpers for providers. +public static class StreamingStreams +{ + /// A read-only stream over without copying it when it is backed by an array. + public static Stream AsStream(ReadOnlyMemory memory) + => System.Runtime.InteropServices.MemoryMarshal.TryGetArray(memory, out var segment) && segment.Array != null + ? new MemoryStream(segment.Array, segment.Offset, segment.Count, writable: false) + : new MemoryStream(memory.ToArray(), writable: false); + + /// + /// Copies to a temporary file and returns it, positioned at 0 and seekable; disposing it deletes the file. + /// Providers upload from it so a large object is never held in managed memory. + /// + public static async Task SpoolAsync(Stream content, CancellationToken cancellationToken) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + + var file = new FileStream( + Path.Combine(Path.GetTempPath(), "baget-spool-" + Guid.NewGuid().ToString("N")), + FileMode.CreateNew, + FileAccess.ReadWrite, + FileShare.None, + 81920, + FileOptions.DeleteOnClose | FileOptions.Asynchronous); + try + { + await content.CopyToAsync(file, 81920, cancellationToken).ConfigureAwait(false); + file.Position = 0; + return file; + } + catch + { + await file.DisposeAsync().ConfigureAwait(false); + throw; + } + } +} + +/// A read stream that disposes the object that owns it (a download response) with it. +public sealed class OwnedReadStream : Stream +{ + private readonly Stream _inner; + private readonly IDisposable? _owner; + + /// The stream to read. + /// Disposed with the stream; may be null. + public OwnedReadStream(Stream inner, IDisposable? owner) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + _owner = owner; + } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + => _inner.ReadAsync(buffer, cancellationToken); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => _inner.ReadAsync(buffer, offset, count, cancellationToken); + + public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _inner.Dispose(); + _owner?.Dispose(); + } + + base.Dispose(disposing); + } +} diff --git a/src/BaGet.Core/Storage/SymbolRegistry.cs b/src/BaGet.Core/Storage/SymbolRegistry.cs new file mode 100644 index 000000000..543b541cf --- /dev/null +++ b/src/BaGet.Core/Storage/SymbolRegistry.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; + +namespace BaGet.Core; + +/// +/// over the database () and the symbol storage. +/// Rows are repository-scoped through the context's query filter, so each repository sees only its own symbols. +/// +public class SymbolRegistry : ISymbolRegistry +{ + private readonly IContext _context; + private readonly ISymbolStorageService _storage; + private readonly SystemTime _time; + + public SymbolRegistry(IContext context, ISymbolStorageService storage, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + public bool IsSupported => _context is not NullContext; + + public async Task RecordAsync( + string packageId, + NuGetVersion version, + IEnumerable symbols, + CancellationToken cancellationToken) + { + if (!IsSupported) return; + + var id = packageId.ToLowerInvariant(); + var normalized = version.ToNormalizedString().ToLowerInvariant(); + var existing = (await ListRowsAsync(id, normalized, asNoTracking: true, cancellationToken)) + .Select(r => (r.FileName, r.SymbolKey)) + .ToHashSet(); + + foreach (var symbol in symbols) + { + var file = symbol.FileName.ToLowerInvariant(); + var key = symbol.Key.ToLowerInvariant(); + if (!existing.Add((file, key))) continue; + + _context.PackageSymbols!.Add(new PackageSymbol + { + PackageId = id, + PackageVersion = normalized, + FileName = file, + SymbolKey = key, + Created = _time.UtcNow, + }); + } + + await _context.SaveChangesAsync(cancellationToken); + } + + public async Task> ListAsync( + string packageId, + NuGetVersion version, + CancellationToken cancellationToken) + { + if (!IsSupported) return Array.Empty(); + + var rows = await ListRowsAsync( + packageId.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant(), + asNoTracking: true, + cancellationToken); + + return rows.Select(r => new SymbolReference(r.FileName!, r.SymbolKey!)).ToList(); + } + + public async Task DeleteAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken) + { + if (!IsSupported) return 0; + + var rows = await ListRowsAsync( + packageId.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant(), + asNoTracking: false, + cancellationToken); + if (rows.Count == 0) return 0; + + // The rows go first: a refused write (read-only gate) must leave the content in place. + _context.PackageSymbols!.RemoveRange(rows); + await _context.SaveChangesAsync(cancellationToken); + + // The same PDB can come from several versions (an unchanged assembly repackaged). Its content goes + // only when no other version of this repository still records it. + foreach (var row in rows) + { + var file = row.FileName!; + var key = row.SymbolKey!; + var stillUsed = await _context.PackageSymbols! + .AnyAsync(s => s.FileName == file && s.SymbolKey == key, cancellationToken); + if (!stillUsed) + { + await _storage.DeletePortablePdbContentAsync(file, key, cancellationToken); + } + } + + return rows.Count; + } + + private async Task> ListRowsAsync(string id, string version, bool asNoTracking, CancellationToken cancellationToken) + { + var query = _context.PackageSymbols!.Where(s => s.PackageId == id && s.PackageVersion == version); + if (asNoTracking) query = query.AsNoTracking(); + + return await query.OrderBy(s => s.FileName).ThenBy(s => s.SymbolKey).ToListAsync(cancellationToken); + } +} diff --git a/src/BaGet.Core/Storage/SymbolStorageService.cs b/src/BaGet.Core/Storage/SymbolStorageService.cs index 4792481f8..853b568d2 100644 --- a/src/BaGet.Core/Storage/SymbolStorageService.cs +++ b/src/BaGet.Core/Storage/SymbolStorageService.cs @@ -4,75 +4,89 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public class SymbolStorageService : ISymbolStorageService { - public class SymbolStorageService : ISymbolStorageService + private const string SymbolsPathPrefix = "symbols"; + private const string PdbContentType = "binary/octet-stream"; + + private readonly IStorageService _storage; + private readonly IRepositoryContext? _repository; + + /// + /// The repository whose symbols are stored and served: the default one keeps symbols/…, any other + /// repos/{name}/symbols/…, so symbols pushed to one repository are not served from another. Null means + /// the default repository. + /// + public SymbolStorageService(IStorageService storage, IRepositoryContext? repository = null) { - private const string SymbolsPathPrefix = "symbols"; - private const string PdbContentType = "binary/octet-stream"; + _repository = repository; + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + } - private readonly IStorageService _storage; + public async Task SavePortablePdbContentAsync( + string filename, + string key, + Stream pdbStream, + CancellationToken cancellationToken) + { + var path = GetPathForKey(filename, key); + var result = await _storage.PutAsync(path, pdbStream, PdbContentType, cancellationToken); - public SymbolStorageService(IStorageService storage) + if (result == StoragePutResult.Conflict) { - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + throw new InvalidOperationException($"Could not save PDB {filename} {key} due to conflict"); } + } - public async Task SavePortablePdbContentAsync( - string filename, - string key, - Stream pdbStream, - CancellationToken cancellationToken) + public async Task GetPortablePdbContentStreamOrNullAsync(string filename, string key) + { + try { + // An invalid file name or key (too short, not alphanumeric) is a miss, not a server error. var path = GetPathForKey(filename, key); - var result = await _storage.PutAsync(path, pdbStream, PdbContentType, cancellationToken); - if (result == StoragePutResult.Conflict) - { - throw new InvalidOperationException($"Could not save PDB {filename} {key} due to conflict"); - } + return await _storage.GetAsync(path); } - - public async Task GetPortablePdbContentStreamOrNullAsync(string filename, string key) + catch { - var path = GetPathForKey(filename, key); - - try - { - return await _storage.GetAsync(path); - } - catch - { - return null; - } + return null; } + } - private string GetPathForKey(string filename, string key) - { - // Ensure the filename doesn't try to escape out of the current directory. - var tempPath = Path.GetDirectoryName(Path.GetTempPath()); - var expandedPath = Path.GetDirectoryName(Path.Combine(tempPath, filename)); + public async Task DeletePortablePdbContentAsync(string filename, string key, CancellationToken cancellationToken) + { + await _storage.DeleteAsync(GetPathForKey(filename, key), cancellationToken); + } + + private string GetPathForKey(string filename, string key) + { + // Ensure the filename doesn't try to escape out of the current directory. + var tempPath = Path.GetDirectoryName(Path.GetTempPath()); + #pragma warning disable CS8604 + var expandedPath = Path.GetDirectoryName(Path.Combine(tempPath, filename)); + #pragma warning restore CS8604 - if (expandedPath != tempPath) - { - throw new ArgumentException(nameof(filename)); - } + if (expandedPath != tempPath) + { + throw new ArgumentException(nameof(filename)); + } - if (!key.All(char.IsLetterOrDigit)) - { - throw new ArgumentException(nameof(key)); - } + if (key.Length < 32 || !key.All(char.IsLetterOrDigit)) + { + throw new ArgumentException(nameof(key)); + } - // The key's first 32 characters are the GUID, the remaining characters are the age. - // See: https://github.com/dotnet/symstore/blob/98717c63ec8342acf8a07aa5c909b88bd0c664cc/docs/specs/SSQP_Key_Conventions.md#portable-pdb-signature - // Debuggers should always use the age "ffffffff", however Visual Studio 2019 - // users have reported other age values. We will ignore the age. - key = key.Substring(0, 32) + "ffffffff"; + // The key's first 32 characters are the GUID, the remaining characters are the age. + // See: https://github.com/dotnet/symstore/blob/98717c63ec8342acf8a07aa5c909b88bd0c664cc/docs/specs/SSQP_Key_Conventions.md#portable-pdb-signature + // Debuggers should always use the age "ffffffff", however Visual Studio 2019 + // users have reported other age values. We will ignore the age. + key = key.Substring(0, 32) + "ffffffff"; - return Path.Combine( - SymbolsPathPrefix, - filename.ToLowerInvariant(), - key.ToLowerInvariant()); - } + return Path.Combine( + RepositoryStorage.Segments(_repository?.Current ?? RepositoryInfo.Default) + .Concat(new[] { SymbolsPathPrefix, filename.ToLowerInvariant(), key.ToLowerInvariant() }) + .ToArray()); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/UploadDigestTracker.cs b/src/BaGet.Core/Storage/UploadDigestTracker.cs new file mode 100644 index 000000000..18609af97 --- /dev/null +++ b/src/BaGet.Core/Storage/UploadDigestTracker.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Keeps the running SHA-256 of each streaming upload on this node, so the digest is known the moment the last byte arrived +/// and a 5 GB layer is not read a second time. SHA-256 state cannot be saved, so a node that did not see every chunk (restart, +/// another node, a failed chunk) loses the entry; then answers null and the provider recomputes the +/// digest from the stored content, streaming. +/// +public sealed class UploadDigestTracker +{ + private static readonly TimeSpan IdleLimit = TimeSpan.FromHours(2); + + /// The tracker the providers share (their instances are transient). + public static UploadDigestTracker Shared { get; } = new(); + + private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); + + /// The uploads being tracked (for tests and the idle sweep). + public int Count => _entries.Count; + + /// + /// Wraps so what the provider reads is hashed. Call with the + /// upload's length after storing it, or when storing failed. + /// + /// The upload. + /// Where the chunk starts. + /// The chunk. + public TrackedChunk Track(string uploadId, long offset, Stream chunk) + { + if (uploadId == null) throw new ArgumentNullException(nameof(uploadId)); + if (chunk == null) throw new ArgumentNullException(nameof(chunk)); + + Sweep(); + + Entry entry; + if (offset == 0) + { + entry = new Entry(); + if (_entries.TryGetValue(uploadId, out var previous)) previous.Dispose(); + _entries[uploadId] = entry; + } + else if (_entries.TryGetValue(uploadId, out var existing) && existing.Valid && existing.Length == offset) + { + entry = existing; + } + else + { + // This node does not hold the bytes before the chunk: the digest will be recomputed at commit. + entry = new Entry { Valid = false }; + if (_entries.TryGetValue(uploadId, out var previous)) previous.Dispose(); + _entries[uploadId] = entry; + } + + entry.Touched = DateTime.UtcNow; + return new TrackedChunk(entry, chunk); + } + + /// + /// The SHA-256 (lower-case hex) of the upload if it is known and covers exactly bytes; + /// null otherwise. Forgets the upload either way. + /// + public string? TryComplete(string uploadId, long totalLength) + { + if (!_entries.TryRemove(uploadId, out var entry)) return null; + + using (entry) + { + if (!entry.Valid || entry.Length != totalLength) return null; + + return Convert.ToHexString(entry.Hash.GetHashAndReset()).ToLowerInvariant(); + } + } + + /// Drops the upload's state (abort, commit). + public void Forget(string uploadId) + { + if (_entries.TryRemove(uploadId, out var entry)) entry.Dispose(); + } + + private void Sweep() + { + if (_entries.Count < 64) return; + + var limit = DateTime.UtcNow - IdleLimit; + foreach (var pair in _entries.Where(p => p.Value.Touched < limit).ToList()) + { + if (_entries.TryRemove(pair.Key, out var entry)) entry.Dispose(); + } + } + + internal sealed class Entry : IDisposable + { + public IncrementalHash Hash { get; } = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + + public long Length; + + public bool Valid = true; + + public DateTime Touched = DateTime.UtcNow; + + public void Dispose() => Hash.Dispose(); + } + + /// A chunk stream that hashes what is read from it. + public sealed class TrackedChunk : Stream + { + private readonly Entry _entry; + private readonly Stream _inner; + + internal TrackedChunk(Entry entry, Stream inner) + { + _entry = entry; + _inner = inner; + } + + /// The chunk was stored; is what the store now holds. + public void Complete(long uploadLength) + { + // A mismatch means the provider stored more or less than was read: the running hash cannot be trusted. + if (_entry.Valid && _entry.Length != uploadLength) _entry.Valid = false; + } + + /// Storing the chunk failed or was cut: part of it may have been hashed without being stored. + public void Fail() => _entry.Valid = false; + + public override int Read(byte[] buffer, int offset, int count) + { + var read = _inner.Read(buffer, offset, count); + Account(buffer.AsSpan(offset, read)); + return read; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = await _inner.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + Account(buffer.Span.Slice(0, read)); + return read; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + private void Account(ReadOnlySpan bytes) + { + if (bytes.Length == 0 || !_entry.Valid) return; + + _entry.Hash.AppendData(bytes); + _entry.Length += bytes.Length; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} diff --git a/src/BaGet.Core/Storage/WindowedReadStream.cs b/src/BaGet.Core/Storage/WindowedReadStream.cs new file mode 100644 index 000000000..398983194 --- /dev/null +++ b/src/BaGet.Core/Storage/WindowedReadStream.cs @@ -0,0 +1,136 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// +/// Reads a byte range of a remote blob as a sequence of bounded range requests ( each) instead of one +/// request for the whole range. A multi-gigabyte GET is one connection that must stay healthy for minutes and cannot resume; +/// here a connection that drops (or a server that closes a long response) costs one window, which is re-requested from the exact +/// byte already delivered. Memory: whatever the inner stream buffers, never the window. +/// +public sealed class WindowedReadStream : Stream +{ + /// The bytes asked for per request: 64 MiB. + public const long DefaultWindow = 64L * 1024 * 1024; + + /// How often one window is re-requested after the connection fails before the error is passed on. + public const int DefaultRetries = 3; + + private readonly Func> _open; + private readonly long _window; + private readonly int _retries; + private long _position; + private readonly long _end; + private Stream? _current; + private long _windowEnd; + private bool _disposed; + + /// Opens count bytes from offset (a stream that ends after them). + /// Where the range starts. + /// How many bytes the range holds. + /// Bytes per request. + /// Re-requests of a window after an I/O failure. + public WindowedReadStream(Func> open, long offset, long count, long window = DefaultWindow, int retries = DefaultRetries) + { + _open = open ?? throw new ArgumentNullException(nameof(open)); + if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); + if (window <= 0) throw new ArgumentOutOfRangeException(nameof(window)); + _position = offset; + _end = offset + count; + _window = window; + _retries = retries; + } + + /// Requests made so far (windows opened, re-requests included), for tests. + public int RequestCount { get; private set; } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_disposed) throw new ObjectDisposedException(nameof(WindowedReadStream)); + if (buffer.Length == 0) return 0; + + var failures = 0; + while (_position < _end) + { + try + { + if (_current == null) + { + _windowEnd = Math.Min(_end, _position + _window); + RequestCount++; + _current = await _open(_position, _windowEnd - _position, cancellationToken).ConfigureAwait(false); + } + + var read = await _current.ReadAsync(buffer.Slice(0, (int)Math.Min(buffer.Length, _windowEnd - _position)), cancellationToken).ConfigureAwait(false); + if (read > 0) + { + _position += read; + if (_position >= _windowEnd) CloseWindow(); + return read; + } + + // The response ended before the window did: ask again from where it stopped. + CloseWindow(); + if (++failures > _retries) throw new EndOfStreamException("The store ended a ranged read early."); + } + catch (Exception e) when ((e is IOException || e is HttpRequestException) && !cancellationToken.IsCancellationRequested && ++failures <= _retries) + { + CloseWindow(); + } + } + + return 0; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override int Read(byte[] buffer, int offset, int count) + => ReadAsync(buffer.AsMemory(offset, count), CancellationToken.None).AsTask().GetAwaiter().GetResult(); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + private void CloseWindow() + { + _current?.Dispose(); + _current = null; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _disposed = true; + CloseWindow(); + } + + base.Dispose(disposing); + } +} diff --git a/src/BaGet.Core/Telemetry/BaGetDiagnostics.cs b/src/BaGet.Core/Telemetry/BaGetDiagnostics.cs new file mode 100644 index 000000000..b5ef70021 --- /dev/null +++ b/src/BaGet.Core/Telemetry/BaGetDiagnostics.cs @@ -0,0 +1,71 @@ +using System.Diagnostics; +using System.Diagnostics.Metrics; + +namespace BaGet.Core; + +/// +/// BaGet's own traces and metrics, emitted with System.Diagnostics only (no OpenTelemetry dependency in the +/// libraries). With no listener attached returns +/// null and counters do nothing, so instrumentation costs nothing until the host subscribes to . +/// +/// +/// Tags carry package ids and versions, results, table names and counts. Never put API keys, connection strings, +/// user names or email addresses in a tag. +/// +public static class BaGetDiagnostics +{ + /// The name of both the and the . + public const string Name = "BaGet"; + + /// Span names. + public static class Spans + { + public const string PackageIndex = "package.index"; + public const string PackageValidate = "package.validate"; + public const string MirrorFetch = "mirror.fetch"; + public const string DatabaseCopy = "database.copy"; + public const string DatabaseCopyTable = "database.copy.table"; + } + + /// Tag names. + public static class Tags + { + public const string PackageId = "baget.package.id"; + public const string PackageVersion = "baget.package.version"; + public const string Result = "baget.result"; + public const string SubmissionId = "baget.validation.submission"; + public const string Validator = "baget.validation.validator"; + public const string Table = "baget.copy.table"; + public const string Rows = "baget.copy.rows"; + public const string Tables = "baget.copy.tables"; + public const string SourceType = "baget.copy.source"; + public const string TargetType = "baget.copy.target"; + } + + /// The source of BaGet's spans. + public static readonly ActivitySource Source = new(Name); + + /// The meter of BaGet's counters. + public static readonly Meter Meter = new(Name); + + /// Packages accepted by a push, tagged by . + public static readonly Counter PackagesPushed + = Meter.CreateCounter("baget.packages.pushed", "{package}", "Packages indexed, by result."); + + /// Package downloads recorded. + public static readonly Counter Downloads + = Meter.CreateCounter("baget.downloads", "{download}", "Package downloads recorded."); + + /// Finished validation submissions, tagged by . + public static readonly Counter ValidationResults + = Meter.CreateCounter("baget.validation.results", "{submission}", "Finished validation submissions, by result."); + + /// Marks an activity as failed without recording the exception message (it may hold paths or connection details). + public static void Fail(Activity? activity, System.Exception exception) + { + if (activity == null) return; + + activity.SetTag(Tags.Result, "error"); + activity.SetStatus(ActivityStatusCode.Error, exception.GetType().Name); + } +} diff --git a/src/BaGet.Core/Telemetry/ITelemetryDiagnostics.cs b/src/BaGet.Core/Telemetry/ITelemetryDiagnostics.cs new file mode 100644 index 000000000..37b910ce1 --- /dev/null +++ b/src/BaGet.Core/Telemetry/ITelemetryDiagnostics.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core; + +/// What one telemetry signal is doing, as the Settings page shows it. +public enum TelemetrySignalState +{ + /// Telemetry or this signal is switched off. + Off, + + /// Switched on but no usable endpoint is set. + NotConfigured, + + /// Configured; nothing has been exported yet. + Waiting, + + /// The last export succeeded. + Ok, + + /// The last export failed. + Failing, +} + +/// One signal's state. is already scrubbed (no headers, credentials or URL paths). +public sealed record TelemetrySignalReport( + string Signal, + TelemetrySignalState State, + DateTimeOffset? LastSuccess, + DateTimeOffset? FailingSince, + string? LastError, + long Dropped); + +/// The outcome of a connection test; and are scrubbed. +/// The collector accepted a test span. +/// What happened. +/// The endpoint that was tested, cut to scheme, host and port. +public sealed record TelemetryTestOutcome(bool Ok, string Message, string? Target); + +/// +/// What the Settings page needs from the host's OpenTelemetry export (the exporters live in the host, which the +/// identity pages cannot reference). Absent when a host does not export telemetry. +/// +public interface ITelemetryDiagnostics +{ + /// The state of traces, metrics and logs. + IReadOnlyList GetStatus(); + + /// + /// Sends one test span with explicit settings, saving and changing nothing. A null argument means the saved + /// value (so a sensitive field left blank on the form keeps its secret); an empty one means none. + /// + Task TestAsync(string? endpoint, string? protocol, string? headers, CancellationToken cancellationToken = default); +} diff --git a/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs b/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs index 482c46a69..0bf4a708d 100644 --- a/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs +++ b/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs @@ -4,32 +4,33 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The client used when there are no upstream package sources. +/// +public class DisabledUpstreamClient : IUpstreamClient { - /// - /// The client used when there are no upstream package sources. - /// - public class DisabledUpstreamClient : IUpstreamClient - { - private readonly IReadOnlyList _emptyVersionList = new List(); - private readonly IReadOnlyList _emptyPackageList = new List(); + private readonly IReadOnlyList _emptyVersionList = new List(); + private readonly IReadOnlyList _emptyPackageList = new List(); - public Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) - { - return Task.FromResult(_emptyVersionList); - } + public Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) + { + return Task.FromResult(_emptyVersionList); + } - public Task> ListPackagesAsync(string id, CancellationToken cancellationToken) - { - return Task.FromResult(_emptyPackageList); - } + public Task> ListPackagesAsync(string id, CancellationToken cancellationToken) + { + return Task.FromResult(_emptyPackageList); + } - public Task DownloadPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) - { - return Task.FromResult(null); - } + public Task DownloadPackageOrNullAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken) + { + #pragma warning disable CS8619, CS8625 + return Task.FromResult(null); + #pragma warning restore CS8619, CS8625 } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs b/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs index 763aed6cb..759e0e769 100644 --- a/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs +++ b/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs @@ -13,193 +13,227 @@ using NuGet.Protocol.Core.Types; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +using ILogger = Microsoft.Extensions.Logging.ILogger; +using INuGetLogger = NuGet.Common.ILogger; + +/// +/// The client to upstream a NuGet server that uses the V2 protocol. +/// +public class V2UpstreamClient : IUpstreamClient, IDisposable { - using ILogger = Microsoft.Extensions.Logging.ILogger; - using INuGetLogger = NuGet.Common.ILogger; + private readonly SourceCacheContext _cache; + private readonly SourceRepository _repository; + private readonly INuGetLogger _ngLogger; + private readonly ILogger _logger; + private readonly bool _propagateErrors; + + public V2UpstreamClient( + IOptionsSnapshot options, + ILogger logger) + { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + + if (options.Value?.PackageSource?.AbsolutePath == null) + { + throw new ArgumentException("No mirror package source has been set."); + } + + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + _ngLogger = NullLogger.Instance; + _cache = new SourceCacheContext(); + _repository = NuGet.Protocol.Core.Types.Repository.Factory.GetCoreV2(new PackageSource(options.Value.PackageSource.AbsoluteUri)); + } /// - /// The client to upstream a NuGet server that uses the V2 protocol. + /// A client of the V2 feed at , for a remote repository. /// - public class V2UpstreamClient : IUpstreamClient, IDisposable + /// The feed URL. + /// The HTTP Basic user name, or null. + /// The HTTP Basic password, or null. + /// The logger. + /// + /// Throw failures other than "not found" instead of answering as if not found (see ). + /// + public V2UpstreamClient(Uri source, string? username, string? password, ILogger logger, bool propagateErrors) { - private readonly SourceCacheContext _cache; - private readonly SourceRepository _repository; - private readonly INuGetLogger _ngLogger; - private readonly ILogger _logger; - - public V2UpstreamClient( - IOptionsSnapshot options, - ILogger logger) - { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + if (source is null) throw new ArgumentNullException(nameof(source)); - if (options.Value?.PackageSource?.AbsolutePath == null) - { - throw new ArgumentException("No mirror package source has been set."); - } + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _propagateErrors = propagateErrors; + _ngLogger = NullLogger.Instance; - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + // The remote repository keeps its own cache (with a metadata period and Purge): NuGet's on-disk HTTP cache + // must not answer instead. + _cache = new SourceCacheContext { NoCache = true, DirectDownload = true }; - _ngLogger = NullLogger.Instance; - _cache = new SourceCacheContext(); - _repository = Repository.Factory.GetCoreV2(new PackageSource(options.Value.PackageSource.AbsoluteUri)); + var packageSource = new PackageSource(source.AbsoluteUri); + if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password)) + { + packageSource.Credentials = new PackageSourceCredential( + source.Host, username ?? string.Empty, password ?? string.Empty, isPasswordClearText: true, validAuthenticationTypesText: null); } - public async Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) + _repository = NuGet.Protocol.Core.Types.Repository.Factory.GetCoreV2(packageSource); + } + + public async Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) + { + try { - try - { - var resource = await _repository.GetResourceAsync(cancellationToken); - var versions = await resource.GetAllVersionsAsync(id, _cache, _ngLogger, cancellationToken); + var resource = await _repository.GetResourceAsync(cancellationToken); + var versions = await resource.GetAllVersionsAsync(id, _cache, _ngLogger, cancellationToken); - return versions.ToList(); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); - return new List(); - } + return versions.ToList(); } - - public async Task> ListPackagesAsync( - string id, - CancellationToken cancellationToken) + catch (Exception e) when (!_propagateErrors) { - try - { - var resource = await _repository.GetResourceAsync(cancellationToken); - var packages = await resource.GetMetadataAsync( - id, - includePrerelease: true, - includeUnlisted: true, - _cache, - _ngLogger, - cancellationToken); - - return packages.Select(ToPackage).ToList(); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); - return new List(); - } + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); + return new List(); } + } - public async Task DownloadPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + public async Task> ListPackagesAsync( + string id, + CancellationToken cancellationToken) + { + try { - var packageStream = new MemoryStream(); - - try - { - var resource = await _repository.GetResourceAsync(cancellationToken); - var success = await resource.CopyNupkgToStreamAsync( - id, version, packageStream, _cache, _ngLogger, - cancellationToken); + var resource = await _repository.GetResourceAsync(cancellationToken); + var packages = await resource.GetMetadataAsync( + id, + includePrerelease: true, + includeUnlisted: true, + _cache, + _ngLogger, + cancellationToken); + + return packages.Select(ToPackage).ToList(); + } + catch (Exception e) when (!_propagateErrors) + { + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); + return new List(); + } + } - if (!success) - { - packageStream.Dispose(); - return null; - } + public async Task DownloadPackageOrNullAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken) + { + var packageStream = new MemoryStream(); - packageStream.Position = 0; + try + { + var resource = await _repository.GetResourceAsync(cancellationToken); + var success = await resource.CopyNupkgToStreamAsync( + id, version, packageStream, _cache, _ngLogger, + cancellationToken); - return packageStream; - } - catch (Exception e) + if (!success) { - _logger.LogError( - e, - "Failed to index package {Id} {Version} from upstream", - id, - version); - packageStream.Dispose(); return null; } - } - public void Dispose() => _cache.Dispose(); + packageStream.Position = 0; - private Package ToPackage(IPackageSearchMetadata package) + return packageStream; + } + catch (Exception e) when (!_propagateErrors) { - return new Package - { - Id = package.Identity.Id, - Version = package.Identity.Version, - Authors = ParseAuthors(package.Authors), - Description = package.Description, - Downloads = 0, - HasReadme = false, - Language = null, - Listed = package.IsListed, - MinClientVersion = null, - Published = package.Published?.UtcDateTime ?? DateTime.MinValue, - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - Summary = package.Summary, - Title = package.Title, - IconUrl = package.IconUrl, - LicenseUrl = package.LicenseUrl, - ProjectUrl = package.ProjectUrl, - PackageTypes = new List(), - RepositoryUrl = null, - RepositoryType = null, - Tags = package.Tags?.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries), - - Dependencies = ToDependencies(package) - }; + _logger.LogError( + e, + "Failed to index package {Id} {Version} from upstream", + id, + version); + + packageStream.Dispose(); + return null; } + } - private string[] ParseAuthors(string authors) + public void Dispose() => _cache.Dispose(); + + private Package ToPackage(IPackageSearchMetadata package) + { + return new Package { - if (string.IsNullOrEmpty(authors)) return Array.Empty(); + Id = package.Identity.Id, + Version = package.Identity.Version, + Authors = ParseAuthors(package.Authors), + Description = package.Description, + Downloads = 0, + HasReadme = false, + Language = null, + Listed = package.IsListed, + MinClientVersion = null, + Published = package.Published?.UtcDateTime ?? DateTime.MinValue, + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + Summary = package.Summary, + Title = package.Title, + IconUrl = package.IconUrl, + LicenseUrl = package.LicenseUrl, + ProjectUrl = package.ProjectUrl, + PackageTypes = new List(), + RepositoryUrl = null, + RepositoryType = null, + Tags = package.Tags?.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries), + + Dependencies = ToDependencies(package) + }; + } - return authors - .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) - .Select(a => a.Trim()) - .ToArray(); - } + private string[] ParseAuthors(string authors) + { + if (string.IsNullOrEmpty(authors)) return Array.Empty(); - private List ToDependencies(IPackageSearchMetadata package) - { - return package - .DependencySets - .SelectMany(ToDependencies) - .ToList(); - } + return authors + .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) + .Select(a => a.Trim()) + .ToArray(); + } - private IEnumerable ToDependencies(PackageDependencyGroup group) - { - var framework = group.TargetFramework.GetShortFolderName(); + private List ToDependencies(IPackageSearchMetadata package) + { + return package + .DependencySets + .SelectMany(ToDependencies) + .ToList(); + } - // BaGet stores a dependency group with no dependencies as a package dependency - // with no package id nor package version. - if ((group.Packages?.Count() ?? 0) == 0) - { - return new[] - { - new PackageDependency - { - Id = null, - VersionRange = null, - TargetFramework = framework, - } - }; - } + private IEnumerable ToDependencies(PackageDependencyGroup group) + { + var framework = group.TargetFramework.GetShortFolderName(); - return group.Packages.Select(d => new PackageDependency + // BaGet stores a dependency group with no dependencies as a package dependency + // with no package id nor package version. + if ((group.Packages?.Count() ?? 0) == 0) + { + return new[] { - Id = d.Id, - VersionRange = d.VersionRange?.ToString(), - TargetFramework = framework, - }); + new PackageDependency + { + Id = null, + VersionRange = null, + TargetFramework = framework, + } + }; } + + #pragma warning disable CS8603 + return group.Packages?.Select(d => new PackageDependency + { + Id = d.Id, + VersionRange = d.VersionRange?.ToString(), + TargetFramework = framework, + }); + #pragma warning restore CS8603 } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs b/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs index bb8855ff9..4776c69f1 100644 --- a/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs +++ b/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs @@ -9,171 +9,188 @@ using NuGet.Versioning; using Microsoft.Extensions.Logging; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The mirroring client for a NuGet server that uses the V3 protocol. +/// +public class V3UpstreamClient : IUpstreamClient { - /// - /// The mirroring client for a NuGet server that uses the V3 protocol. - /// - public class V3UpstreamClient : IUpstreamClient + private readonly NuGetClient _client; + private readonly ILogger _logger; + private readonly bool _propagateErrors; + + public V3UpstreamClient(NuGetClient client, ILogger logger) + : this(client, logger, propagateErrors: false) { - private readonly NuGetClient _client; - private readonly ILogger _logger; + } - public V3UpstreamClient(NuGetClient client, ILogger logger) - { - _client = client ?? throw new ArgumentNullException(nameof(client)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + /// The client of the upstream. + /// The logger. + /// + /// When true only "not found" is an empty answer and every other failure (network, 5xx, 401) is thrown, so a caller + /// that caches answers () can tell "the upstream says no" from "the upstream could + /// not be asked". False (the mirror's historic behaviour) logs the failure and answers as if not found. + /// + public V3UpstreamClient(NuGetClient client, ILogger logger, bool propagateErrors) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _propagateErrors = propagateErrors; + } - public async Task DownloadPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + public async Task DownloadPackageOrNullAsync( + string? id, + NuGetVersion version, + CancellationToken cancellationToken) + { + try { - try + using (var downloadStream = await _client.DownloadPackageAsync(id, version, cancellationToken)) { - using (var downloadStream = await _client.DownloadPackageAsync(id, version, cancellationToken)) - { - return await downloadStream.AsTemporaryFileStreamAsync(cancellationToken); - } - } - catch (PackageNotFoundException) - { - return null; - } - catch (Exception e) - { - _logger.LogError( - e, - "Failed to download {PackageId} {PackageVersion} from upstream", - id, - version); - return null; + return await downloadStream.AsTemporaryFileStreamAsync(cancellationToken); } } + catch (PackageNotFoundException) + { + return null; + } + catch (Exception e) when (!_propagateErrors) + { + _logger.LogError( + e, + "Failed to download {PackageId} {PackageVersion} from upstream", + id, + version); + return null; + } + } - public async Task> ListPackagesAsync( - string id, - CancellationToken cancellationToken) + public async Task> ListPackagesAsync( + string id, + CancellationToken cancellationToken) + { + try { - try - { - var packages = await _client.GetPackageMetadataAsync(id, cancellationToken); + var packages = await _client.GetPackageMetadataAsync(id, cancellationToken); - return packages.Select(ToPackage).ToList(); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream metadata", id); - return new List(); - } + return packages.Select(ToPackage).ToList(); } - - public async Task> ListPackageVersionsAsync( - string id, - CancellationToken cancellationToken) + catch (Exception e) when (!_propagateErrors) { - try - { - return await _client.ListPackageVersionsAsync(id, includeUnlisted: true, cancellationToken); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); - return new List(); - } + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream metadata", id); + return new List(); } + } - private Package ToPackage(PackageMetadata metadata) + public async Task> ListPackageVersionsAsync( + string id, + CancellationToken cancellationToken) + { + try { - var version = metadata.ParseVersion(); - - return new Package - { - Id = metadata.PackageId, - Version = version, - Authors = ParseAuthors(metadata.Authors), - Description = metadata.Description, - Downloads = 0, - HasReadme = false, - IsPrerelease = version.IsPrerelease, - Language = metadata.Language, - Listed = metadata.IsListed(), - MinClientVersion = metadata.MinClientVersion, - Published = metadata.Published.UtcDateTime, - RequireLicenseAcceptance = metadata.RequireLicenseAcceptance, - Summary = metadata.Summary, - Title = metadata.Title, - IconUrl = ParseUri(metadata.IconUrl), - LicenseUrl = ParseUri(metadata.LicenseUrl), - ProjectUrl = ParseUri(metadata.ProjectUrl), - PackageTypes = new List(), - RepositoryUrl = null, - RepositoryType = null, - SemVerLevel = version.IsSemVer2 ? SemVerLevel.SemVer2 : SemVerLevel.Unknown, - Tags = metadata.Tags?.ToArray() ?? Array.Empty(), - - Dependencies = ToDependencies(metadata) - }; + return await _client.ListPackageVersionsAsync(id, includeUnlisted: true, cancellationToken); + } + catch (Exception e) when (!_propagateErrors) + { + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); + return new List(); } + } + + private Package ToPackage(PackageMetadata metadata) + { + var version = metadata.ParseVersion(); - private Uri ParseUri(string uriString) + return new Package { - if (uriString == null) return null; + Id = metadata.PackageId, + Version = version, + Authors = ParseAuthors(metadata.Authors), + Description = metadata.Description, + Downloads = 0, + HasReadme = false, + IsPrerelease = version.IsPrerelease, + Language = metadata.Language, + Listed = metadata.IsListed(), + MinClientVersion = metadata.MinClientVersion, + Published = metadata.Published.UtcDateTime, + RequireLicenseAcceptance = metadata.RequireLicenseAcceptance, + Summary = metadata.Summary, + Title = metadata.Title, + IconUrl = ParseUri(metadata.IconUrl), + LicenseUrl = ParseUri(metadata.LicenseUrl), + ProjectUrl = ParseUri(metadata.ProjectUrl), + PackageTypes = new List(), + RepositoryUrl = null, + RepositoryType = null, + SemVerLevel = version.IsSemVer2 ? SemVerLevel.SemVer2 : SemVerLevel.Unknown, + Tags = metadata.Tags?.ToArray() ?? Array.Empty(), + + Dependencies = ToDependencies(metadata) + }; + } - if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) - { - return null; - } + private Uri? ParseUri(string? uriString) + { + if (uriString == null) return null; - return uri; + if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) + { + return null; } - private string[] ParseAuthors(string authors) - { - if (string.IsNullOrEmpty(authors)) return Array.Empty(); + return uri; + } - return authors - .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) - .Select(a => a.Trim()) - .ToArray(); - } + private string[] ParseAuthors(string? authors) + { + if (string.IsNullOrEmpty(authors)) return Array.Empty(); - private List ToDependencies(PackageMetadata package) - { - if ((package.DependencyGroups?.Count ?? 0) == 0) - { - return new List(); - } + return authors + .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) + .Select(a => a.Trim()) + .ToArray(); + } - return package.DependencyGroups - .SelectMany(ToDependencies) - .ToList(); + private List ToDependencies(PackageMetadata package) + { + if ((package.DependencyGroups?.Count ?? 0) == 0) + { + return new List(); } - private IEnumerable ToDependencies(DependencyGroupItem group) + #pragma warning disable CS8604 + return package.DependencyGroups + .SelectMany(ToDependencies) + .ToList(); + #pragma warning restore CS8604 + } + + private IEnumerable ToDependencies(DependencyGroupItem group) + { + // BaGet stores a dependency group with no dependencies as a package dependency + // with no package id nor package version. + if ((group.Dependencies?.Count ?? 0) == 0) { - // BaGet stores a dependency group with no dependencies as a package dependency - // with no package id nor package version. - if ((group.Dependencies?.Count ?? 0) == 0) + return new[] { - return new[] + new PackageDependency { - new PackageDependency - { - Id = null, - VersionRange = null, - TargetFramework = group.TargetFramework, - } - }; - } - - return group.Dependencies.Select(d => new PackageDependency - { - Id = d.Id, - VersionRange = d.Range, - TargetFramework = group.TargetFramework, - }); + Id = null, + VersionRange = null, + TargetFramework = group.TargetFramework, + } + }; } + + #pragma warning disable CS8603 + return group.Dependencies?.Select(d => new PackageDependency + { + Id = d.Id, + VersionRange = d.Range, + TargetFramework = group.TargetFramework, + }); + #pragma warning restore CS8603 } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/DownloadsImporter.cs b/src/BaGet.Core/Upstream/DownloadsImporter.cs index 120b71460..855b37c0e 100644 --- a/src/BaGet.Core/Upstream/DownloadsImporter.cs +++ b/src/BaGet.Core/Upstream/DownloadsImporter.cs @@ -6,61 +6,66 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; -namespace BaGet.Core +namespace BaGet.Core; + +public class DownloadsImporter { - public class DownloadsImporter - { - private const int BatchSize = 200; + private const int BatchSize = 200; - private readonly IContext _context; - private readonly IPackageDownloadsSource _downloadsSource; - private readonly ILogger _logger; + private readonly IContext _context; + private readonly IPackageDownloadsSource _downloadsSource; + private readonly ILogger _logger; - public DownloadsImporter( - IContext context, - IPackageDownloadsSource downloadsSource, - ILogger logger) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _downloadsSource = downloadsSource ?? throw new ArgumentNullException(nameof(downloadsSource)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public DownloadsImporter( + IContext context, + IPackageDownloadsSource downloadsSource, + ILogger logger) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _downloadsSource = downloadsSource ?? throw new ArgumentNullException(nameof(downloadsSource)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task ImportAsync(CancellationToken cancellationToken) + { + var packageDownloads = await _downloadsSource.GetPackageDownloadsAsync(); + #pragma warning disable CS8602 + var packages = await _context.Packages?.CountAsync(); + #pragma warning restore CS8602 + var batches = (packages / BatchSize) + 1; - public async Task ImportAsync(CancellationToken cancellationToken) + for (var batch = 0; batch < batches; batch++) { - var packageDownloads = await _downloadsSource.GetPackageDownloadsAsync(); - var packages = await _context.Packages.CountAsync(); - var batches = (packages / BatchSize) + 1; + _logger.LogInformation("Importing batch {Batch}...", batch); - for (var batch = 0; batch < batches; batch++) + foreach (var package in await GetBatchAsync(batch, cancellationToken)) { - _logger.LogInformation("Importing batch {Batch}...", batch); + var packageId = package.Id?.ToLowerInvariant(); + var packageVersion = package.NormalizedVersionString?.ToLowerInvariant(); - foreach (var package in await GetBatchAsync(batch, cancellationToken)) + #pragma warning disable CS8604 + if (!packageDownloads.ContainsKey(packageId) || + !packageDownloads[packageId].ContainsKey(packageVersion)) + #pragma warning restore CS8604 { - var packageId = package.Id.ToLowerInvariant(); - var packageVersion = package.NormalizedVersionString.ToLowerInvariant(); - - if (!packageDownloads.ContainsKey(packageId) || - !packageDownloads[packageId].ContainsKey(packageVersion)) - { - continue; - } - - package.Downloads = packageDownloads[packageId][packageVersion]; + continue; } - await _context.SaveChangesAsync(cancellationToken); - - _logger.LogInformation("Imported batch {Batch}", batch); + package.Downloads = packageDownloads[packageId][packageVersion]; } - } - private Task> GetBatchAsync(int batch, CancellationToken cancellationToken) - => _context.Packages - .OrderBy(p => p.Key) - .Skip(batch * BatchSize) - .Take(BatchSize) - .ToListAsync(cancellationToken); + await _context.SaveChangesAsync(cancellationToken); + + _logger.LogInformation("Imported batch {Batch}", batch); + } } -} + + #pragma warning disable CS8604 + private Task> GetBatchAsync(int batch, CancellationToken cancellationToken) + => _context.Packages + .OrderBy(p => p.Key) + .Skip(batch * BatchSize) + .Take(BatchSize) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs b/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs index 706e9638f..23af0909c 100644 --- a/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs +++ b/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs @@ -1,10 +1,9 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IPackageDownloadsSource { - public interface IPackageDownloadsSource - { - Task>> GetPackageDownloadsAsync(); - } -} + Task>> GetPackageDownloadsAsync(); +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/IUpstreamClient.cs b/src/BaGet.Core/Upstream/IUpstreamClient.cs index 648d0c429..0c347cfd2 100644 --- a/src/BaGet.Core/Upstream/IUpstreamClient.cs +++ b/src/BaGet.Core/Upstream/IUpstreamClient.cs @@ -1,51 +1,76 @@ -using BaGet.Protocol.Models; -using NuGet.Versioning; +using NuGet.Versioning; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A client to interact with an upstream package source. +/// +public interface IUpstreamClient { /// - /// A client to interact with an upstream package source. + /// Try to get all versions of a package from the upstream package source. Returns empty + /// if the package could not be found. + /// + /// The package ID to lookup + /// + /// + /// All versions of a package, including unlisted packages. + /// Returns an empty list if the package could not be found. + /// + Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken); + + /// + /// Try to get the metadata for all versions of a package from the upstream package source. Returns empty + /// if the package could not be found. /// - public interface IUpstreamClient - { - /// - /// Try to get all versions of a package from the upstream package source. Returns empty - /// if the package could not be found. - /// - /// The package ID to lookup - /// - /// - /// All versions of a package, including unlisted packages. - /// Returns an empty list if the package could not be found. - /// - Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken); - - /// - /// Try to get the metadata for all versions of a package from the upstream package source. Returns empty - /// if the package could not be found. - /// - /// The package ID to lookup - /// - /// - /// The metadata for all versions of a package, including unlisted versions. - /// Returns an empty list if the package could not be found. - /// - Task> ListPackagesAsync(string id, CancellationToken cancellationToken); - - /// - /// Download a package from the upstream package source. Returns null if the package does not exist. - /// - /// The package ID to download. - /// The package version to download. - /// - /// - /// The package stream or null if the package cannot be found. - /// The stream is guaranteed to be seekable if not not null. - /// - Task DownloadPackageOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } + /// The package ID to lookup + /// + /// + /// The metadata for all versions of a package, including unlisted versions. + /// Returns an empty list if the package could not be found. + /// + Task> ListPackagesAsync(string id, CancellationToken cancellationToken); + + /// + /// Download a package from the upstream package source. Returns null if the package does not exist. + /// + /// The package ID to download. + /// The package version to download. + /// + /// + /// The package stream or null if the package cannot be found. + /// The stream is guaranteed to be seekable if not not null. + /// + Task DownloadPackageOrNullAsync(string? id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Whether would find the version, without downloading it: the same rules + /// (offline mode, a remembered "not found") applied to a version list. What the resolution preview of a virtual + /// repository asks. The default asks . + /// + async Task ProbeAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + => (await ListPackageVersionsAsync(id, cancellationToken).ConfigureAwait(false)).Contains(version) + ? UpstreamProbe.Available + : UpstreamProbe.Absent; } + +/// What found. +public enum UpstreamProbe +{ + /// The upstream does not have the version (or there is no upstream). + Absent, + + /// The upstream has the version: a download would fetch it. + Available, + + /// Offline mode: the upstream is never asked, so a download finds nothing there. + Offline, + + /// The upstream could not be reached. + Unavailable, +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs b/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs index 53c986281..501e69942 100644 --- a/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs +++ b/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -9,101 +9,109 @@ using Newtonsoft.Json.Linq; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +// See https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Indexing/Downloads.cs +public class PackageDownloadsJsonSource : IPackageDownloadsSource { - // See https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Indexing/Downloads.cs - public class PackageDownloadsJsonSource : IPackageDownloadsSource + public const string PackageDownloadsV1Url = "https://nugetprod0.blob.core.windows.net/ng-search-data/downloads.v1.json"; + + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public PackageDownloadsJsonSource(HttpClient httpClient, ILogger logger) { - public const string PackageDownloadsV1Url = "https://nugetprod0.blob.core.windows.net/ng-search-data/downloads.v1.json"; + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - private readonly HttpClient _httpClient; - private readonly ILogger _logger; + public async Task>> GetPackageDownloadsAsync() + { + _logger.LogInformation("Fetching package downloads..."); - public PackageDownloadsJsonSource(HttpClient httpClient, ILogger logger) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + var results = new Dictionary>(); - public async Task>> GetPackageDownloadsAsync() + using (var downloadsStream = await GetDownloadsStreamAsync()) + using (var downloadStreamReader = new StreamReader(downloadsStream)) + using (var jsonReader = new JsonTextReader(downloadStreamReader)) { - _logger.LogInformation("Fetching package downloads..."); + _logger.LogInformation("Parsing package downloads..."); - var results = new Dictionary>(); + jsonReader.Read(); - using (var downloadsStream = await GetDownloadsStreamAsync()) - using (var downloadStreamReader = new StreamReader(downloadsStream)) - using (var jsonReader = new JsonTextReader(downloadStreamReader)) + while (jsonReader.Read()) { - _logger.LogInformation("Parsing package downloads..."); - - jsonReader.Read(); - - while (jsonReader.Read()) + try { - try + if (jsonReader.TokenType == JsonToken.StartArray) { - if (jsonReader.TokenType == JsonToken.StartArray) + // Reads this one record, not the document: the outer array's + // start token was consumed above, so the reader sits inside it. + // What dominates memory is the dictionary returned below, which + // holds every package and version by design. + var record = JToken.ReadFrom(jsonReader); + #pragma warning disable CS8604 + var id = string.Intern(record[0]?.ToString().ToLowerInvariant()); + #pragma warning restore CS8604 + + // The second entry in each record should be an array of versions, if not move on to next entry. + // This is a check to safe guard against invalid entries. + if (record.Count() == 2 && record[1]?.Type != JTokenType.Array) { - // TODO: This line reads the entire document into memory... - var record = JToken.ReadFrom(jsonReader); - var id = string.Intern(record[0].ToString().ToLowerInvariant()); - - // The second entry in each record should be an array of versions, if not move on to next entry. - // This is a check to safe guard against invalid entries. - if (record.Count() == 2 && record[1].Type != JTokenType.Array) - { - continue; - } + continue; + } - if (!results.ContainsKey(id)) - { - results.Add(id, new Dictionary()); - } + if (!results.ContainsKey(id)) + { + results.Add(id, new Dictionary()); + } - foreach (var token in record) + foreach (var token in record) + { + if (token != null && token.Count() == 2) { - if (token != null && token.Count() == 2) - { - var version = string.Intern(NuGetVersion.Parse(token[0].ToString()).ToNormalizedString().ToLowerInvariant()); - var downloads = token[1].ToObject(); - - results[id][version] = downloads; - } + #pragma warning disable CS8604 + var version = string.Intern(NuGetVersion.Parse(token[0]?.ToString()).ToNormalizedString().ToLowerInvariant()); + #pragma warning restore CS8604 + #pragma warning disable CS8602 + var downloads = token[1].ToObject(); + #pragma warning restore CS8602 + + results[id][version] = downloads; } } } - catch (JsonReaderException e) - { - _logger.LogError(e, "Invalid entry in downloads.v1.json"); - } } - - _logger.LogInformation("Parsed package downloads"); + catch (JsonReaderException e) + { + _logger.LogError(e, "Invalid entry in downloads.v1.json"); + } } - return results; + _logger.LogInformation("Parsed package downloads"); } - private async Task GetDownloadsStreamAsync() - { - _logger.LogInformation("Downloading downloads.v1.json..."); + return results; + } - var fileStream = File.Open(Path.GetTempFileName(), FileMode.Create); - var response = await _httpClient.GetAsync(PackageDownloadsV1Url, HttpCompletionOption.ResponseHeadersRead); + internal async Task GetDownloadsStreamAsync() + { + _logger.LogInformation("Downloading downloads.v1.json..."); - response.EnsureSuccessStatusCode(); + var response = await _httpClient.GetAsync(PackageDownloadsV1Url, HttpCompletionOption.ResponseHeadersRead); - using (var networkStream = await response.Content.ReadAsStreamAsync()) - { - await networkStream.CopyToAsync(fileStream); - } + response.EnsureSuccessStatusCode(); - fileStream.Seek(0, SeekOrigin.Begin); + using (var networkStream = await response.Content.ReadAsStreamAsync()) + { + // Spooled to a temporary file rather than held in memory. This one deletes + // itself when the stream is disposed; the hand-rolled file this replaced was + // left behind in the temporary directory on every import. + var fileStream = await networkStream.AsTemporaryFileStreamAsync(); _logger.LogInformation("Downloaded downloads.v1.json"); return fileStream; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Validation/RequiredIfAttribute.cs b/src/BaGet.Core/Validation/RequiredIfAttribute.cs index 56571a3d0..a3c192197 100644 --- a/src/BaGet.Core/Validation/RequiredIfAttribute.cs +++ b/src/BaGet.Core/Validation/RequiredIfAttribute.cs @@ -2,133 +2,132 @@ using System.ComponentModel.DataAnnotations; using System.Globalization; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Provides conditional validation based on related property value. +/// +/// Inspiration: https://stackoverflow.com/a/27666044 +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class RequiredIfAttribute : ValidationAttribute { + #region Properties + /// - /// Provides conditional validation based on related property value. - /// - /// Inspiration: https://stackoverflow.com/a/27666044 + /// Gets or sets the other property name that will be used during validation. /// - [AttributeUsage(AttributeTargets.Property)] - public sealed class RequiredIfAttribute : ValidationAttribute + /// + /// The other property name. + /// + public string OtherProperty { get; } + + /// + /// Gets or sets the display name of the other property. + /// + /// + /// The display name of the other property. + /// + public string? OtherPropertyDisplayName { get; set; } + + /// + /// Gets or sets the other property value that will be relevant for validation. + /// + /// + /// The other property value. + /// + public object? OtherPropertyValue { get; } + + /// + /// Gets or sets a value indicating whether other property's value should match or differ from provided other property's value (default is false). + /// + /// + /// true if other property's value validation should be inverted; otherwise, false. + /// + /// + /// How this works + /// - true: validated property is required when other property doesn't equal provided value + /// - false: validated property is required when other property matches provided value + /// + public bool IsInverted { get; set; } + + /// + /// Gets a value that indicates whether the attribute requires validation context. + /// + /// true if the attribute requires validation context; otherwise, false. + public override bool RequiresValidationContext => true; + + #endregion + + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// The other property. + /// The other property value. + public RequiredIfAttribute(string otherProperty, object? otherPropertyValue) + : base("'{0}' is required because '{1}' has a value {3}'{2}'.") { - #region Properties - - /// - /// Gets or sets the other property name that will be used during validation. - /// - /// - /// The other property name. - /// - public string OtherProperty { get; } - - /// - /// Gets or sets the display name of the other property. - /// - /// - /// The display name of the other property. - /// - public string OtherPropertyDisplayName { get; set; } - - /// - /// Gets or sets the other property value that will be relevant for validation. - /// - /// - /// The other property value. - /// - public object OtherPropertyValue { get; } - - /// - /// Gets or sets a value indicating whether other property's value should match or differ from provided other property's value (default is false). - /// - /// - /// true if other property's value validation should be inverted; otherwise, false. - /// - /// - /// How this works - /// - true: validated property is required when other property doesn't equal provided value - /// - false: validated property is required when other property matches provided value - /// - public bool IsInverted { get; set; } - - /// - /// Gets a value that indicates whether the attribute requires validation context. - /// - /// true if the attribute requires validation context; otherwise, false. - public override bool RequiresValidationContext => true; - - #endregion - - #region Constructor - - /// - /// Initializes a new instance of the class. - /// - /// The other property. - /// The other property value. - public RequiredIfAttribute(string otherProperty, object otherPropertyValue) - : base("'{0}' is required because '{1}' has a value {3}'{2}'.") - { - OtherProperty = otherProperty; - OtherPropertyValue = otherPropertyValue; - IsInverted = false; - } + OtherProperty = otherProperty; + OtherPropertyValue = otherPropertyValue; + IsInverted = false; + } + + #endregion + + /// + /// Applies formatting to an error message, based on the data field where the error occurred. + /// + /// The name to include in the formatted message. + /// + /// An instance of the formatted error message. + /// + public override string FormatErrorMessage(string name) + { + return string.Format( + CultureInfo.CurrentCulture, + ErrorMessageString, + name, + OtherPropertyDisplayName ?? OtherProperty, + OtherPropertyValue, + IsInverted ? "other than " : "of "); + } - #endregion + /// + /// Validates the specified value with respect to the current validation attribute. + /// + /// The value to validate. + /// The context information about the validation operation. + /// + /// An instance of the class. + /// + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) + { + if (validationContext == null) + throw new ArgumentNullException(nameof(validationContext)); - /// - /// Applies formatting to an error message, based on the data field where the error occurred. - /// - /// The name to include in the formatted message. - /// - /// An instance of the formatted error message. - /// - public override string FormatErrorMessage(string name) + var otherProperty = validationContext.ObjectType.GetProperty(OtherProperty); + if (otherProperty == null) { - return string.Format( - CultureInfo.CurrentCulture, - ErrorMessageString, - name, - OtherPropertyDisplayName ?? OtherProperty, - OtherPropertyValue, - IsInverted ? "other than " : "of "); + return new ValidationResult( + string.Format(CultureInfo.CurrentCulture, "Could not find a property named '{0}'.", OtherProperty)); } - /// - /// Validates the specified value with respect to the current validation attribute. - /// - /// The value to validate. - /// The context information about the validation operation. - /// - /// An instance of the class. - /// - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + var otherValue = otherProperty.GetValue(validationContext.ObjectInstance); + + // Check if this value is actually required and validate it. + if (!IsInverted && Equals(otherValue, OtherPropertyValue) || + IsInverted && !Equals(otherValue, OtherPropertyValue)) { - if (validationContext == null) - throw new ArgumentNullException(nameof(validationContext)); - - var otherProperty = validationContext.ObjectType.GetProperty(OtherProperty); - if (otherProperty == null) - { - return new ValidationResult( - string.Format(CultureInfo.CurrentCulture, "Could not find a property named '{0}'.", OtherProperty)); - } - - var otherValue = otherProperty.GetValue(validationContext.ObjectInstance); - - // Check if this value is actually required and validate it. - if (!IsInverted && Equals(otherValue, OtherPropertyValue) || - IsInverted && !Equals(otherValue, OtherPropertyValue)) - { - if (value == null) - return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); - - // Additional check for strings so they're not empty - if (value is string val && val.Trim().Length == 0) - return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); - } - - return ValidationResult.Success; + if (value == null) + return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); + + // Additional check for strings so they're not empty + if (value is string val && val.Trim().Length == 0) + return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } + + return ValidationResult.Success; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Validation/ValidateBaGetOptions.cs b/src/BaGet.Core/Validation/ValidateBaGetOptions.cs index 3c20189dc..fe038525c 100644 --- a/src/BaGet.Core/Validation/ValidateBaGetOptions.cs +++ b/src/BaGet.Core/Validation/ValidateBaGetOptions.cs @@ -2,49 +2,48 @@ using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A configuration that validates options using data annotations. +/// +/// The type of options to validate. +public class ValidateBaGetOptions : IValidateOptions where TOptions : class { + private readonly string? _optionsName; + /// - /// A configuration that validates options using data annotations. + /// Create a new validator. /// - /// The type of options to validate. - public class ValidateBaGetOptions : IValidateOptions where TOptions : class + /// + /// The option's key in the configuration or appsettings.json file, + /// or null if the options was created from the root configuration. + /// + public ValidateBaGetOptions(string? optionsName) { - private readonly string _optionsName; + _optionsName = optionsName; + } - /// - /// Create a new validator. - /// - /// - /// The option's key in the configuration or appsettings.json file, - /// or null if the options was created from the root configuration. - /// - public ValidateBaGetOptions(string optionsName) + public ValidateOptionsResult Validate(string? name, TOptions options) + { + // See: https://github.com/dotnet/runtime/blob/e3ffd343ad5bd3a999cb9515f59e6e7a777b2c34/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs + var context = new ValidationContext(options); + var validationResults = new List(); + if (Validator.TryValidateObject(options, context, validationResults, validateAllProperties: true)) { - _optionsName = optionsName; + return ValidateOptionsResult.Success; } - public ValidateOptionsResult Validate(string name, TOptions options) - { - // See: https://github.com/dotnet/runtime/blob/e3ffd343ad5bd3a999cb9515f59e6e7a777b2c34/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs - var context = new ValidationContext(options); - var validationResults = new List(); - if (Validator.TryValidateObject(options, context, validationResults, validateAllProperties: true)) - { - return ValidateOptionsResult.Success; - } + var errors = new List(); + var message = (_optionsName == null) + ? $"Invalid configs" + : $"Invalid '{_optionsName}' configs"; - var errors = new List(); - var message = (_optionsName == null) - ? $"Invalid configs" - : $"Invalid '{_optionsName}' configs"; - - foreach (var result in validationResults) - { - errors.Add($"{message}: {result}"); - } - - return ValidateOptionsResult.Fail(errors); + foreach (var result in validationResults) + { + errors.Add($"{message}: {result}"); } + + return ValidateOptionsResult.Fail(errors); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Validation/ValidateStartupOptions.cs b/src/BaGet.Core/Validation/ValidateStartupOptions.cs index c662253a2..fc8bf14c0 100644 --- a/src/BaGet.Core/Validation/ValidateStartupOptions.cs +++ b/src/BaGet.Core/Validation/ValidateStartupOptions.cs @@ -2,56 +2,73 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Validates BaGet's options, used at startup. +/// +public class ValidateStartupOptions { - /// - /// Validates BaGet's options, used at startup. - /// - public class ValidateStartupOptions + private readonly IOptions _root; + private readonly IOptions _database; + private readonly IOptions _storage; + private readonly IOptions _mirror; + private readonly IOptions _site; + private readonly ILogger _logger; + private readonly IOptions? _ha; + private readonly HaBackendRules? _haRules; + + public ValidateStartupOptions( + IOptions root, + IOptions database, + IOptions storage, + IOptions mirror, + IOptions site, + ILogger logger, + IOptions? ha = null, + HaBackendRules? haRules = null) { - private readonly IOptions _root; - private readonly IOptions _database; - private readonly IOptions _storage; - private readonly IOptions _mirror; - private readonly ILogger _logger; + _ha = ha; + _haRules = haRules; + _root = root ?? throw new ArgumentNullException(nameof(root)); + _database = database ?? throw new ArgumentNullException(nameof(database)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _mirror = mirror ?? throw new ArgumentNullException(nameof(mirror)); + _site = site ?? throw new ArgumentNullException(nameof(site)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public ValidateStartupOptions( - IOptions root, - IOptions database, - IOptions storage, - IOptions mirror, - ILogger logger) + public bool Validate() + { + try { - _root = root ?? throw new ArgumentNullException(nameof(root)); - _database = database ?? throw new ArgumentNullException(nameof(database)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _mirror = mirror ?? throw new ArgumentNullException(nameof(mirror)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + // Access each option to force validations to run. + // Invalid options will trigger an "OptionsValidationException" exception. + _ = _root.Value; + _ = _database.Value; + _ = _storage.Value; + _ = _mirror.Value; + _ = _site.Value; - public bool Validate() - { - try + // A cluster node on a local database or storage would diverge from the others: refuse before anything starts. + if (_ha != null && _haRules != null) { - // Access each option to force validations to run. - // Invalid options will trigger an "OptionsValidationException" exception. - _ = _root.Value; - _ = _database.Value; - _ = _storage.Value; - _ = _mirror.Value; - - return true; + var problems = _haRules.Check(_ha.Value, _database.Value, _storage.Value); + foreach (var problem in problems) _logger.LogError("High availability: {Problem}", problem); + if (problems.Count > 0) return false; } - catch (OptionsValidationException e) - { - foreach (var failure in e.Failures) - { - _logger.LogError("{OptionsFailure}", failure); - } - _logger.LogError(e, "BaGet configuration is invalid."); - return false; + return true; + } + catch (OptionsValidationException e) + { + foreach (var failure in e.Failures) + { + _logger.LogError("{OptionsFailure}", failure); } + + _logger.LogError(e, "BaGet Extension configuration is invalid."); + return false; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/readme.md b/src/BaGet.Core/readme.md deleted file mode 100644 index d5dbc5235..000000000 --- a/src/BaGet.Core/readme.md +++ /dev/null @@ -1,9 +0,0 @@ -# BaGet.Core - -Contains BaGet's core logic. The important folders are: - -* Indexing - Logic to upload packages and symbols -* Metadata - Used to track packages' metadata, usually in a database -* Storage - Stores the content of packages and symbols -* Search - Used to search for packages -* Mirror - Interactions with an upstream NuGet feed diff --git a/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj b/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj index adb58c0cf..7e17898c8 100644 --- a/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj +++ b/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj @@ -1,19 +1,27 @@ - netstandard2.0 - + net10.0 + latest NuGet - The libraries to host BaGet on MySQL. + The libraries to host BaGet Extension on MySQL. + enable - + + + + + + + + diff --git a/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.Designer.cs b/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.Designer.cs index b29d2b7ef..e57ef6cb0 100644 --- a/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.Designer.cs +++ b/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.Designer.cs @@ -1,3 +1,4 @@ +#nullable disable // using System; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.cs b/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.cs index 90101ee1a..3d5646397 100644 --- a/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.cs +++ b/src/BaGet.Database.MySql/Migrations/20181212113156_Initial.cs @@ -8,6 +8,8 @@ public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { + // The eight 4000-character columns of Packages are longtext: as varchar(4000) in utf8mb4 they + // total over MySQL's 65,535-byte row limit, and a strict-mode server (the default since 5.7) refuses the table. migrationBuilder.CreateTable( name: "Packages", columns: table => new @@ -15,8 +17,8 @@ protected override void Up(MigrationBuilder migrationBuilder) Key = table.Column(nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), Id = table.Column(maxLength: 128, nullable: false), - Authors = table.Column(maxLength: 4000, nullable: true), - Description = table.Column(maxLength: 4000, nullable: true), + Authors = table.Column(type: "longtext", maxLength: 4000, nullable: true), + Description = table.Column(type: "longtext", maxLength: 4000, nullable: true), Downloads = table.Column(nullable: false), HasReadme = table.Column(nullable: false), Language = table.Column(maxLength: 20, nullable: true), @@ -24,14 +26,14 @@ protected override void Up(MigrationBuilder migrationBuilder) MinClientVersion = table.Column(maxLength: 44, nullable: true), Published = table.Column(nullable: false), RequireLicenseAcceptance = table.Column(nullable: false), - Summary = table.Column(maxLength: 4000, nullable: true), + Summary = table.Column(type: "longtext", maxLength: 4000, nullable: true), Title = table.Column(maxLength: 256, nullable: true), - IconUrl = table.Column(maxLength: 4000, nullable: true), - LicenseUrl = table.Column(maxLength: 4000, nullable: true), - ProjectUrl = table.Column(maxLength: 4000, nullable: true), - RepositoryUrl = table.Column(maxLength: 4000, nullable: true), + IconUrl = table.Column(type: "longtext", maxLength: 4000, nullable: true), + LicenseUrl = table.Column(type: "longtext", maxLength: 4000, nullable: true), + ProjectUrl = table.Column(type: "longtext", maxLength: 4000, nullable: true), + RepositoryUrl = table.Column(type: "longtext", maxLength: 4000, nullable: true), RepositoryType = table.Column(maxLength: 100, nullable: true), - Tags = table.Column(maxLength: 4000, nullable: true), + Tags = table.Column(type: "longtext", maxLength: 4000, nullable: true), RowVersion = table.Column(rowVersion: true, nullable: true), Version = table.Column(maxLength: 64, nullable: false) }, diff --git a/src/BaGet.Database.MySql/Migrations/20190303071640_AddSearchDimensions.Designer.cs b/src/BaGet.Database.MySql/Migrations/20190303071640_AddSearchDimensions.Designer.cs index d654ed2ae..97dc7921b 100644 --- a/src/BaGet.Database.MySql/Migrations/20190303071640_AddSearchDimensions.Designer.cs +++ b/src/BaGet.Database.MySql/Migrations/20190303071640_AddSearchDimensions.Designer.cs @@ -1,3 +1,4 @@ +#nullable disable // using System; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.MySql/Migrations/20190914215810_AddOriginalVersionStringColumn.Designer.cs b/src/BaGet.Database.MySql/Migrations/20190914215810_AddOriginalVersionStringColumn.Designer.cs index a535a8230..2dd2898fb 100644 --- a/src/BaGet.Database.MySql/Migrations/20190914215810_AddOriginalVersionStringColumn.Designer.cs +++ b/src/BaGet.Database.MySql/Migrations/20190914215810_AddOriginalVersionStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.MySql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.MySql/Migrations/20200109085155_AddReleaseNotesStringColumn.Designer.cs b/src/BaGet.Database.MySql/Migrations/20200109085155_AddReleaseNotesStringColumn.Designer.cs index 64554a061..8affff195 100644 --- a/src/BaGet.Database.MySql/Migrations/20200109085155_AddReleaseNotesStringColumn.Designer.cs +++ b/src/BaGet.Database.MySql/Migrations/20200109085155_AddReleaseNotesStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.MySql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.MySql/Migrations/20200210004047_AddHasEmbeddedIconColumn.Designer.cs b/src/BaGet.Database.MySql/Migrations/20200210004047_AddHasEmbeddedIconColumn.Designer.cs index 4ad121819..5fbb38020 100644 --- a/src/BaGet.Database.MySql/Migrations/20200210004047_AddHasEmbeddedIconColumn.Designer.cs +++ b/src/BaGet.Database.MySql/Migrations/20200210004047_AddHasEmbeddedIconColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.MySql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.MySql/Migrations/20210919191554_RemoveReleaseNotesMaxLength.Designer.cs b/src/BaGet.Database.MySql/Migrations/20210919191554_RemoveReleaseNotesMaxLength.Designer.cs index cc7b84a2a..dce9f87ae 100644 --- a/src/BaGet.Database.MySql/Migrations/20210919191554_RemoveReleaseNotesMaxLength.Designer.cs +++ b/src/BaGet.Database.MySql/Migrations/20210919191554_RemoveReleaseNotesMaxLength.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.MySql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.MySql/Migrations/20261016055851_AddDeprecationAndVulnerability.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261016055851_AddDeprecationAndVulnerability.Designer.cs new file mode 100644 index 000000000..989cde0a9 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261016055851_AddDeprecationAndVulnerability.Designer.cs @@ -0,0 +1,355 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261016055851_AddDeprecationAndVulnerability")] + partial class AddDeprecationAndVulnerability + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261016055851_AddDeprecationAndVulnerability.cs b/src/BaGet.Database.MySql/Migrations/20261016055851_AddDeprecationAndVulnerability.cs new file mode 100644 index 000000000..2a0f0b3d4 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261016055851_AddDeprecationAndVulnerability.cs @@ -0,0 +1,93 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddDeprecationAndVulnerability : Migration + { + /// + // The alterations Entity Framework scaffolded alongside these tables were removed by + // hand. Every one was "int" to "int" on a primary key, carrying only the + // MySql:ValueGenerationStrategy annotation - EF recording that the column is + // auto_increment, which it already is. Applying them would rebuild seven tables to + // change nothing. The model snapshot keeps the annotations, so later migrations stay + // clean. + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageDeprecations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Reasons = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Message = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + AlternatePackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + AlternateVersionRange = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageKey = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageDeprecations", x => x.Key); + table.ForeignKey( + name: "FK_PackageDeprecations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "PackageVulnerabilities", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + AdvisoryUrl = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Severity = table.Column(type: "int", nullable: false), + VersionRange = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageKey = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageVulnerabilities", x => x.Key); + table.ForeignKey( + name: "FK_PackageVulnerabilities_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_PackageDeprecations_PackageKey", + table: "PackageDeprecations", + column: "PackageKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageVulnerabilities_PackageKey", + table: "PackageVulnerabilities", + column: "PackageKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageDeprecations"); + + migrationBuilder.DropTable( + name: "PackageVulnerabilities"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017011647_AddCatalog.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261017011647_AddCatalog.Designer.cs new file mode 100644 index 000000000..ca82f9d7c --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017011647_AddCatalog.Designer.cs @@ -0,0 +1,394 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261017011647_AddCatalog")] + partial class AddCatalog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017011647_AddCatalog.cs b/src/BaGet.Database.MySql/Migrations/20261017011647_AddCatalog.cs new file mode 100644 index 000000000..0e8d5df7b --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017011647_AddCatalog.cs @@ -0,0 +1,51 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddCatalog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "CatalogLeafs", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + CommitId = table.Column(type: "varchar(36)", maxLength: 36, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + CommitTimestamp = table.Column(type: "datetime(6)", nullable: false), + Type = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageVersion = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_CatalogLeafs", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_CommitId", + table: "CatalogLeafs", + column: "CommitId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "CatalogLeafs"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017012809_AddAccounts.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261017012809_AddAccounts.Designer.cs new file mode 100644 index 000000000..b7122b230 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017012809_AddAccounts.Designer.cs @@ -0,0 +1,781 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261017012809_AddAccounts")] + partial class AddAccounts + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017012809_AddAccounts.cs b/src/BaGet.Database.MySql/Migrations/20261017012809_AddAccounts.cs new file mode 100644 index 000000000..a265d9e50 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017012809_AddAccounts.cs @@ -0,0 +1,390 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddAccounts : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeys", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + UserId = table.Column(type: "varchar(450)", maxLength: 450, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + HashedKey = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Scopes = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageGlobPattern = table.Column(type: "varchar(128)", maxLength: 128, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Expires = table.Column(type: "datetime(6)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeys", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AspNetRoles", + columns: table => new + { + Id = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Name = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + NormalizedName = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ConcurrencyStamp = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoles", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AspNetUsers", + columns: table => new + { + Id = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + UserName = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + NormalizedUserName = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Email = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + NormalizedEmail = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + EmailConfirmed = table.Column(type: "tinyint(1)", nullable: false), + PasswordHash = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + SecurityStamp = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ConcurrencyStamp = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + PhoneNumber = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + PhoneNumberConfirmed = table.Column(type: "tinyint(1)", nullable: false), + TwoFactorEnabled = table.Column(type: "tinyint(1)", nullable: false), + LockoutEnd = table.Column(type: "datetime(6)", nullable: true), + LockoutEnabled = table.Column(type: "tinyint(1)", nullable: false), + AccessFailedCount = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "Organizations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Organizations", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "PackageOwners", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + PackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + OwnerName = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + IsVerified = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageOwners", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RoleId = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ClaimType = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ClaimValue = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AspNetUserClaims", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + UserId = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ClaimType = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ClaimValue = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AspNetUserLogins", + columns: table => new + { + LoginProvider = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ProviderKey = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ProviderDisplayName = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + UserId = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AspNetUserRoles", + columns: table => new + { + UserId = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + RoleId = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "AspNetUserTokens", + columns: table => new + { + UserId = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + LoginProvider = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Name = table.Column(type: "varchar(255)", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Value = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "OrganizationMembers", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + OrganizationKey = table.Column(type: "int", nullable: true), + UserId = table.Column(type: "varchar(450)", maxLength: 450, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + IsAdmin = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OrganizationMembers", x => x.Key); + table.ForeignKey( + name: "FK_OrganizationMembers_Organizations_OrganizationKey", + column: x => x.OrganizationKey, + principalTable: "Organizations", + principalColumn: "Key"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_HashedKey", + table: "ApiKeys", + column: "HashedKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_UserId", + table: "ApiKeys", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "AspNetRoleClaims", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "AspNetRoles", + column: "NormalizedName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserClaims_UserId", + table: "AspNetUserClaims", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserLogins_UserId", + table: "AspNetUserLogins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "AspNetUsers", + column: "NormalizedEmail"); + + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "AspNetUsers", + column: "NormalizedUserName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_OrganizationKey", + table: "OrganizationMembers", + column: "OrganizationKey"); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_UserId", + table: "OrganizationMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Organizations_Name", + table: "Organizations", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_OwnerName", + table: "PackageOwners", + column: "OwnerName"); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeys"); + + migrationBuilder.DropTable( + name: "AspNetRoleClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserLogins"); + + migrationBuilder.DropTable( + name: "AspNetUserRoles"); + + migrationBuilder.DropTable( + name: "AspNetUserTokens"); + + migrationBuilder.DropTable( + name: "OrganizationMembers"); + + migrationBuilder.DropTable( + name: "PackageOwners"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + + migrationBuilder.DropTable( + name: "Organizations"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..624f5097b --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.Designer.cs @@ -0,0 +1,845 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261017014351_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.cs b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.cs new file mode 100644 index 000000000..71f3717ef --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.cs @@ -0,0 +1,70 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + SubmissionId = table.Column(type: "varchar(36)", maxLength: 36, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageVersion = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageKey = table.Column(type: "int", nullable: true), + Type = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + State = table.Column(type: "int", nullable: false), + Message = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Completed = table.Column(type: "datetime(6)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..1f3f9c23b --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.Designer.cs @@ -0,0 +1,890 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261017020123_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.cs b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.cs new file mode 100644 index 000000000..25c5423b3 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.cs @@ -0,0 +1,53 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + PackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageVersion = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Reason = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Details = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ReporterEmail = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Resolved = table.Column(type: "datetime(6)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261018043343_AddAdministrators.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261018043343_AddAdministrators.Designer.cs new file mode 100644 index 000000000..095d83e35 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261018043343_AddAdministrators.Designer.cs @@ -0,0 +1,893 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261018043343_AddAdministrators")] + partial class AddAdministrators + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261018043343_AddAdministrators.cs b/src/BaGet.Database.MySql/Migrations/20261018043343_AddAdministrators.cs new file mode 100644 index 000000000..9a28fa10d --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261018043343_AddAdministrators.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddAdministrators : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsAdministrator", + table: "AspNetUsers", + type: "tinyint(1)", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsAdministrator", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261020072009_AddRepositories.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261020072009_AddRepositories.Designer.cs new file mode 100644 index 000000000..6c2edd485 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261020072009_AddRepositories.Designer.cs @@ -0,0 +1,991 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261020072009_AddRepositories")] + partial class AddRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261020072009_AddRepositories.cs b/src/BaGet.Database.MySql/Migrations/20261020072009_AddRepositories.cs new file mode 100644 index 000000000..cb4664a0c --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261020072009_AddRepositories.cs @@ -0,0 +1,226 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports"); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageValidations", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "Packages", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageOwners", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "CatalogLeafs", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "AbuseReports", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.CreateTable( + name: "Projects", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + DisplayName = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Projects", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "Repositories", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Format = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Kind = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ProjectKey = table.Column(type: "int", nullable: true), + Settings = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + AnonymousRead = table.Column(type: "tinyint(1)", nullable: false), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Repositories", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + // The default repository (key 1 = RepositoryKey's column default, so every existing row already belongs to + // it). Created here, not only by startup, so that applying migrations without RunMigrationsAtStartup + // (dotnet ef database update, an SQL script) cannot leave a new repository to take key 1. + migrationBuilder.InsertData( + table: "Repositories", + columns: new[] { "Key", "Name", "Format", "Kind", "AnonymousRead", "Created" }, + values: new object[] { 1, "default", "NuGet", "Local", true, DateTime.UtcNow }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages", + columns: new[] { "RepositoryKey", "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Projects_Name", + table: "Projects", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Repositories_Name", + table: "Repositories", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Projects"); + + migrationBuilder.DropTable( + name: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "Packages"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_Packages_Id_Version", + table: "Packages", + columns: new[] { "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021035323_AddPackageSymbols.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261021035323_AddPackageSymbols.Designer.cs new file mode 100644 index 000000000..3df307547 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021035323_AddPackageSymbols.Designer.cs @@ -0,0 +1,1036 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261021035323_AddPackageSymbols")] + partial class AddPackageSymbols + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021035323_AddPackageSymbols.cs b/src/BaGet.Database.MySql/Migrations/20261021035323_AddPackageSymbols.cs new file mode 100644 index 000000000..106459c78 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021035323_AddPackageSymbols.cs @@ -0,0 +1,56 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddPackageSymbols : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageSymbols", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + PackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageVersion = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + FileName = table.Column(type: "varchar(255)", maxLength: 255, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + SymbolKey = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageSymbols", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_FileName_SymbolKey", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "FileName", "SymbolKey" }); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_PackageId_PackageVersion", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "PackageId", "PackageVersion" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageSymbols"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021040437_AddAccessControl.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261021040437_AddAccessControl.Designer.cs new file mode 100644 index 000000000..8b2936ffc --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021040437_AddAccessControl.Designer.cs @@ -0,0 +1,1224 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261021040437_AddAccessControl")] + partial class AddAccessControl + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021040437_AddAccessControl.cs b/src/BaGet.Database.MySql/Migrations/20261021040437_AddAccessControl.cs new file mode 100644 index 000000000..2e74912c9 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021040437_AddAccessControl.cs @@ -0,0 +1,249 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddAccessControl : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AccessAuditEntries", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Created = table.Column(type: "datetime(6)", nullable: false), + Actor = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Action = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Subject = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Details = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_AccessAuditEntries", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "Groups", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + IsBuiltIn = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Groups", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "PermissionTargets", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + RepositoryPatterns = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + IncludePatterns = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ExcludePatterns = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ProjectKey = table.Column(type: "int", nullable: true), + IsBuiltIn = table.Column(type: "tinyint(1)", nullable: false), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionTargets", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ProjectMembers", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ProjectKey = table.Column(type: "int", nullable: false), + PrincipalType = table.Column(type: "varchar(16)", maxLength: 16, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PrincipalId = table.Column(type: "varchar(450)", maxLength: 450, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Role = table.Column(type: "varchar(16)", maxLength: 16, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_ProjectMembers", x => x.Key); + table.ForeignKey( + name: "FK_ProjectMembers_Projects_ProjectKey", + column: x => x.ProjectKey, + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "GroupMembers", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + GroupKey = table.Column(type: "int", nullable: false), + UserId = table.Column(type: "varchar(450)", maxLength: 450, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_GroupMembers", x => x.Key); + table.ForeignKey( + name: "FK_GroupMembers_Groups_GroupKey", + column: x => x.GroupKey, + principalTable: "Groups", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "PermissionGrants", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + TargetKey = table.Column(type: "int", nullable: false), + PrincipalType = table.Column(type: "varchar(16)", maxLength: 16, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PrincipalId = table.Column(type: "varchar(450)", maxLength: 450, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Actions = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionGrants", x => x.Key); + table.ForeignKey( + name: "FK_PermissionGrants_PermissionTargets_TargetKey", + column: x => x.TargetKey, + principalTable: "PermissionTargets", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + // The upgrade defaults: what the server did before the access model existed. Everyone reads every + // repository; every authenticated caller deploys, annotates, deletes and manages (package ownership is + // still applied inside those actions). Explicit keys, so the grants below can name them. + var seeded = DateTime.UtcNow; + + migrationBuilder.InsertData( + table: "Groups", + columns: new[] { "Key", "Name", "Description", "Created", "IsBuiltIn" }, + values: new object[,] + { + { 1, "Everyone", "Every caller, anonymous ones included.", seeded, true }, + { 2, "Authenticated", "Every caller that presented valid credentials.", seeded, true }, + }); + + migrationBuilder.InsertData( + table: "PermissionTargets", + columns: new[] { "Key", "Name", "RepositoryPatterns", "IncludePatterns", "ExcludePatterns", "IsBuiltIn", "Created" }, + values: new object[,] + { + { 1, "Anyone reads every repository", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + { 2, "Authenticated users deploy", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + }); + + // Actions: Read = 1; Annotate | Deploy | Delete | Manage = 2 + 4 + 8 + 16 = 30. + migrationBuilder.InsertData( + table: "PermissionGrants", + columns: new[] { "Key", "TargetKey", "PrincipalType", "PrincipalId", "Actions" }, + values: new object[,] + { + { 1, 1, "Group", "1", 1 }, + { 2, 2, "Group", "2", 30 }, + }); + + migrationBuilder.CreateIndex( + name: "IX_AccessAuditEntries_Created", + table: "AccessAuditEntries", + column: "Created"); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_GroupKey_UserId", + table: "GroupMembers", + columns: new[] { "GroupKey", "UserId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_UserId", + table: "GroupMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Groups_Name", + table: "Groups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionGrants_TargetKey_PrincipalType_PrincipalId", + table: "PermissionGrants", + columns: new[] { "TargetKey", "PrincipalType", "PrincipalId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_Name", + table: "PermissionTargets", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ProjectMembers_ProjectKey_PrincipalType_PrincipalId", + table: "ProjectMembers", + columns: new[] { "ProjectKey", "PrincipalType", "PrincipalId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AccessAuditEntries"); + + migrationBuilder.DropTable( + name: "GroupMembers"); + + migrationBuilder.DropTable( + name: "PermissionGrants"); + + migrationBuilder.DropTable( + name: "ProjectMembers"); + + migrationBuilder.DropTable( + name: "Groups"); + + migrationBuilder.DropTable( + name: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021055049_AddApiKeyRepositories.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261021055049_AddApiKeyRepositories.Designer.cs new file mode 100644 index 000000000..b9315cb30 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021055049_AddApiKeyRepositories.Designer.cs @@ -0,0 +1,1304 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261021055049_AddApiKeyRepositories")] + partial class AddApiKeyRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021055049_AddApiKeyRepositories.cs b/src/BaGet.Database.MySql/Migrations/20261021055049_AddApiKeyRepositories.cs new file mode 100644 index 000000000..7adf5fc44 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021055049_AddApiKeyRepositories.cs @@ -0,0 +1,54 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddApiKeyRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeyRepositories", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ApiKeyKey = table.Column(type: "int", nullable: false), + RepositoryKey = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeyRepositories", x => x.Key); + table.ForeignKey( + name: "FK_ApiKeyRepositories_ApiKeys_ApiKeyKey", + column: x => x.ApiKeyKey, + principalTable: "ApiKeys", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_ApiKeyKey_RepositoryKey", + table: "ApiKeyRepositories", + columns: new[] { "ApiKeyKey", "RepositoryKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeyRepositories"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021155644_AddNpmTables.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261021155644_AddNpmTables.Designer.cs new file mode 100644 index 000000000..5d1a8b7ad --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021155644_AddNpmTables.Designer.cs @@ -0,0 +1,1430 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261021155644_AddNpmTables")] + partial class AddNpmTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021155644_AddNpmTables.cs b/src/BaGet.Database.MySql/Migrations/20261021155644_AddNpmTables.cs new file mode 100644 index 000000000..3d7bf5696 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021155644_AddNpmTables.cs @@ -0,0 +1,121 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddNpmTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "NpmPackages", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "varchar(214)", maxLength: 214, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Modified = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmPackages", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "NpmDistTags", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + PackageKey = table.Column(type: "int", nullable: false), + Tag = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Version = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_NpmDistTags", x => x.Key); + table.ForeignKey( + name: "FK_NpmDistTags_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "NpmVersions", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + PackageKey = table.Column(type: "int", nullable: false), + Version = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Integrity = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Shasum = table.Column(type: "varchar(40)", maxLength: 40, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + TarballSize = table.Column(type: "bigint", nullable: false), + Manifest = table.Column(type: "longtext", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Deprecated = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Published = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmVersions", x => x.Key); + table.ForeignKey( + name: "FK_NpmVersions_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_NpmDistTags_PackageKey_Tag", + table: "NpmDistTags", + columns: new[] { "PackageKey", "Tag" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmPackages_RepositoryKey_Name", + table: "NpmPackages", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmVersions_PackageKey_Version", + table: "NpmVersions", + columns: new[] { "PackageKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "NpmDistTags"); + + migrationBuilder.DropTable( + name: "NpmVersions"); + + migrationBuilder.DropTable( + name: "NpmPackages"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021234357_NpmCaseSensitiveNames.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261021234357_NpmCaseSensitiveNames.Designer.cs new file mode 100644 index 000000000..ff7f0abb1 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021234357_NpmCaseSensitiveNames.Designer.cs @@ -0,0 +1,1432 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261021234357_NpmCaseSensitiveNames")] + partial class NpmCaseSensitiveNames + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261021234357_NpmCaseSensitiveNames.cs b/src/BaGet.Database.MySql/Migrations/20261021234357_NpmCaseSensitiveNames.cs new file mode 100644 index 000000000..1b43da473 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261021234357_NpmCaseSensitiveNames.cs @@ -0,0 +1,70 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class NpmCaseSensitiveNames : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Name", + table: "NpmPackages", + type: "varchar(214)", + maxLength: 214, + nullable: false, + collation: "utf8mb4_bin", + oldClrType: typeof(string), + oldType: "varchar(214)", + oldMaxLength: 214) + .Annotation("MySql:CharSet", "utf8mb4") + .OldAnnotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.AlterColumn( + name: "Tag", + table: "NpmDistTags", + type: "varchar(128)", + maxLength: 128, + nullable: false, + collation: "utf8mb4_bin", + oldClrType: typeof(string), + oldType: "varchar(128)", + oldMaxLength: 128) + .Annotation("MySql:CharSet", "utf8mb4") + .OldAnnotation("MySql:CharSet", "utf8mb4"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Name", + table: "NpmPackages", + type: "varchar(214)", + maxLength: 214, + nullable: false, + oldClrType: typeof(string), + oldType: "varchar(214)", + oldMaxLength: 214, + oldCollation: "utf8mb4_bin") + .Annotation("MySql:CharSet", "utf8mb4") + .OldAnnotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.AlterColumn( + name: "Tag", + table: "NpmDistTags", + type: "varchar(128)", + maxLength: 128, + nullable: false, + oldClrType: typeof(string), + oldType: "varchar(128)", + oldMaxLength: 128, + oldCollation: "utf8mb4_bin") + .Annotation("MySql:CharSet", "utf8mb4") + .OldAnnotation("MySql:CharSet", "utf8mb4"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261022010657_AddMavenTables.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261022010657_AddMavenTables.Designer.cs new file mode 100644 index 000000000..f5ce90a20 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261022010657_AddMavenTables.Designer.cs @@ -0,0 +1,1602 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261022010657_AddMavenTables")] + partial class AddMavenTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261022010657_AddMavenTables.cs b/src/BaGet.Database.MySql/Migrations/20261022010657_AddMavenTables.cs new file mode 100644 index 000000000..73e4ce8d9 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261022010657_AddMavenTables.cs @@ -0,0 +1,137 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddMavenTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MavenArtifacts", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + GroupId = table.Column(type: "varchar(200)", maxLength: 200, nullable: false, collation: "utf8mb4_bin") + .Annotation("MySql:CharSet", "utf8mb4"), + ArtifactId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false, collation: "utf8mb4_bin") + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Modified = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenArtifacts", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "MavenVersions", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ArtifactKey = table.Column(type: "int", nullable: false), + Version = table.Column(type: "varchar(128)", maxLength: 128, nullable: false, collation: "utf8mb4_bin") + .Annotation("MySql:CharSet", "utf8mb4"), + IsSnapshot = table.Column(type: "tinyint(1)", nullable: false), + Name = table.Column(type: "varchar(512)", maxLength: 512, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Description = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Packaging = table.Column(type: "varchar(64)", maxLength: 64, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Modified = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenVersions", x => x.Key); + table.ForeignKey( + name: "FK_MavenVersions_MavenArtifacts_ArtifactKey", + column: x => x.ArtifactKey, + principalTable: "MavenArtifacts", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "MavenFiles", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + VersionKey = table.Column(type: "int", nullable: false), + FileName = table.Column(type: "varchar(256)", maxLength: 256, nullable: false, collation: "utf8mb4_bin") + .Annotation("MySql:CharSet", "utf8mb4"), + Classifier = table.Column(type: "varchar(64)", maxLength: 64, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Extension = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + SnapshotTimestamp = table.Column(type: "varchar(15)", maxLength: 15, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + SnapshotBuild = table.Column(type: "int", nullable: false), + Size = table.Column(type: "bigint", nullable: false), + Sha1 = table.Column(type: "varchar(40)", maxLength: 40, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Md5 = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Sha256 = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Sha512 = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenFiles", x => x.Key); + table.ForeignKey( + name: "FK_MavenFiles_MavenVersions_VersionKey", + column: x => x.VersionKey, + principalTable: "MavenVersions", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_MavenArtifacts_RepositoryKey_GroupId_ArtifactId", + table: "MavenArtifacts", + columns: new[] { "RepositoryKey", "GroupId", "ArtifactId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenFiles_VersionKey_FileName", + table: "MavenFiles", + columns: new[] { "VersionKey", "FileName" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenVersions_ArtifactKey_Version", + table: "MavenVersions", + columns: new[] { "ArtifactKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MavenFiles"); + + migrationBuilder.DropTable( + name: "MavenVersions"); + + migrationBuilder.DropTable( + name: "MavenArtifacts"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261022062056_AddOciTables.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261022062056_AddOciTables.Designer.cs new file mode 100644 index 000000000..17f8db7c2 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261022062056_AddOciTables.Designer.cs @@ -0,0 +1,1860 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261022062056_AddOciTables")] + partial class AddOciTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261022062056_AddOciTables.cs b/src/BaGet.Database.MySql/Migrations/20261022062056_AddOciTables.cs new file mode 100644 index 000000000..ae43c209e --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261022062056_AddOciTables.cs @@ -0,0 +1,242 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddOciTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "OciBlobs", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Digest = table.Column(type: "varchar(140)", maxLength: 140, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Size = table.Column(type: "bigint", nullable: false), + RefCount = table.Column(type: "int", nullable: false), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobs", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "OciRepositories", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "varchar(200)", maxLength: 200, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Modified = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciRepositories", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "OciBlobLinks", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ImageKey = table.Column(type: "int", nullable: false), + BlobKey = table.Column(type: "int", nullable: false), + Manifests = table.Column(type: "int", nullable: false), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobLinks", x => x.Key); + table.ForeignKey( + name: "FK_OciBlobLinks_OciBlobs_BlobKey", + column: x => x.BlobKey, + principalTable: "OciBlobs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_OciBlobLinks_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "OciManifests", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ImageKey = table.Column(type: "int", nullable: false), + Digest = table.Column(type: "varchar(140)", maxLength: 140, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + MediaType = table.Column(type: "varchar(255)", maxLength: 255, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ArtifactType = table.Column(type: "varchar(255)", maxLength: 255, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + SubjectDigest = table.Column(type: "varchar(140)", maxLength: 140, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Size = table.Column(type: "bigint", nullable: false), + Content = table.Column(type: "longtext", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciManifests", x => x.Key); + table.ForeignKey( + name: "FK_OciManifests_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "OciUploads", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ImageKey = table.Column(type: "int", nullable: false), + Reference = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + StorageUploadId = table.Column(type: "varchar(512)", maxLength: 512, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Updated = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciUploads", x => x.Key); + table.ForeignKey( + name: "FK_OciUploads_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "OciTags", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ImageKey = table.Column(type: "int", nullable: false), + Name = table.Column(type: "varchar(128)", maxLength: 128, nullable: false, collation: "utf8mb4_bin") + .Annotation("MySql:CharSet", "utf8mb4"), + ManifestKey = table.Column(type: "int", nullable: false), + Updated = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciTags", x => x.Key); + table.ForeignKey( + name: "FK_OciTags_OciManifests_ManifestKey", + column: x => x.ManifestKey, + principalTable: "OciManifests", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_BlobKey", + table: "OciBlobLinks", + column: "BlobKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_ImageKey_BlobKey", + table: "OciBlobLinks", + columns: new[] { "ImageKey", "BlobKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobs_RepositoryKey_Digest", + table: "OciBlobs", + columns: new[] { "RepositoryKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_Digest", + table: "OciManifests", + columns: new[] { "ImageKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_SubjectDigest", + table: "OciManifests", + columns: new[] { "ImageKey", "SubjectDigest" }); + + migrationBuilder.CreateIndex( + name: "IX_OciRepositories_RepositoryKey_Name", + table: "OciRepositories", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ImageKey_Name", + table: "OciTags", + columns: new[] { "ImageKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ManifestKey", + table: "OciTags", + column: "ManifestKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_ImageKey", + table: "OciUploads", + column: "ImageKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_Reference", + table: "OciUploads", + column: "Reference", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OciBlobLinks"); + + migrationBuilder.DropTable( + name: "OciTags"); + + migrationBuilder.DropTable( + name: "OciUploads"); + + migrationBuilder.DropTable( + name: "OciBlobs"); + + migrationBuilder.DropTable( + name: "OciManifests"); + + migrationBuilder.DropTable( + name: "OciRepositories"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261023010852_AddRetention.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261023010852_AddRetention.Designer.cs new file mode 100644 index 000000000..741da4960 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261023010852_AddRetention.Designer.cs @@ -0,0 +1,2014 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261023010852_AddRetention")] + partial class AddRetention + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261023010852_AddRetention.cs b/src/BaGet.Database.MySql/Migrations/20261023010852_AddRetention.cs new file mode 100644 index 000000000..e368fc7c6 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261023010852_AddRetention.cs @@ -0,0 +1,133 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddRetention : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ArtifactUsages", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "varchar(340)", maxLength: 340, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Version = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + LastUsed = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtifactUsages", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "RetentionHolds", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "varchar(340)", maxLength: 340, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Version = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Reason = table.Column(type: "varchar(512)", maxLength: 512, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + CreatedBy = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionHolds", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "RetentionPolicies", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + RepositoryKey = table.Column(type: "int", nullable: true), + ProjectKey = table.Column(type: "int", nullable: true), + Enabled = table.Column(type: "tinyint(1)", nullable: false), + NamePatterns = table.Column(type: "varchar(1024)", maxLength: 1024, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + KeepLast = table.Column(type: "int", nullable: true), + OlderThanDays = table.Column(type: "int", nullable: true), + UnusedDays = table.Column(type: "int", nullable: true), + PrereleaseOnly = table.Column(type: "tinyint(1)", nullable: false), + CacheLimitBytes = table.Column(type: "bigint", nullable: true), + UntaggedAfterDays = table.Column(type: "int", nullable: true), + CollectGarbage = table.Column(type: "tinyint(1)", nullable: false), + ScheduleHours = table.Column(type: "int", nullable: true), + ScheduleStart = table.Column(type: "datetime(6)", nullable: true), + LastRun = table.Column(type: "datetime(6)", nullable: true), + LastResult = table.Column(type: "varchar(1024)", maxLength: 1024, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Modified = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionPolicies", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_ArtifactUsages_RepositoryKey_Name_Version", + table: "ArtifactUsages", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionHolds_RepositoryKey_Name_Version", + table: "RetentionHolds", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_Name", + table: "RetentionPolicies", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ArtifactUsages"); + + migrationBuilder.DropTable( + name: "RetentionHolds"); + + migrationBuilder.DropTable( + name: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261023021756_AddScanning.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261023021756_AddScanning.Designer.cs new file mode 100644 index 000000000..c19461889 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261023021756_AddScanning.Designer.cs @@ -0,0 +1,2176 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261023021756_AddScanning")] + partial class AddScanning + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261023021756_AddScanning.cs b/src/BaGet.Database.MySql/Migrations/20261023021756_AddScanning.cs new file mode 100644 index 000000000..5da787708 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261023021756_AddScanning.cs @@ -0,0 +1,145 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddScanning : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Source", + table: "PackageVulnerabilities", + type: "varchar(32)", + maxLength: 32, + nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ScanPolicies", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: true), + ProjectKey = table.Column(type: "int", nullable: true), + WarnSeverity = table.Column(type: "int", nullable: true), + BlockDownloadSeverity = table.Column(type: "int", nullable: true), + BlockDeploySeverity = table.Column(type: "int", nullable: true), + BlockUnscanned = table.Column(type: "tinyint(1)", nullable: false), + Modified = table.Column(type: "datetime(6)", nullable: false), + ModifiedBy = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_ScanPolicies", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ScanResults", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "varchar(400)", maxLength: 400, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Version = table.Column(type: "varchar(200)", maxLength: 200, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Scanner = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ScannedAt = table.Column(type: "datetime(6)", nullable: true), + Attempted = table.Column(type: "datetime(6)", nullable: false), + Error = table.Column(type: "varchar(1000)", maxLength: 1000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Highest = table.Column(type: "int", nullable: false), + FindingCount = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanResults", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ScanFindings", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ResultKey = table.Column(type: "int", nullable: false), + VulnerabilityId = table.Column(type: "varchar(200)", maxLength: 200, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Component = table.Column(type: "varchar(400)", maxLength: 400, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ComponentVersion = table.Column(type: "varchar(200)", maxLength: 200, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Severity = table.Column(type: "int", nullable: false), + Summary = table.Column(type: "varchar(1000)", maxLength: 1000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + AdvisoryUrl = table.Column(type: "varchar(1000)", maxLength: 1000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + FixedVersion = table.Column(type: "varchar(200)", maxLength: 200, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_ScanFindings", x => x.Key); + table.ForeignKey( + name: "FK_ScanFindings_ScanResults_ResultKey", + column: x => x.ResultKey, + principalTable: "ScanResults", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_ScanFindings_ResultKey", + table: "ScanFindings", + column: "ResultKey"); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScanResults_RepositoryKey_Name_Version", + table: "ScanResults", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScanFindings"); + + migrationBuilder.DropTable( + name: "ScanPolicies"); + + migrationBuilder.DropTable( + name: "ScanResults"); + + migrationBuilder.DropColumn( + name: "Source", + table: "PackageVulnerabilities"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261023050029_AddRetentionUnusedSince.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261023050029_AddRetentionUnusedSince.Designer.cs new file mode 100644 index 000000000..5ddbd1c7a --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261023050029_AddRetentionUnusedSince.Designer.cs @@ -0,0 +1,2179 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261023050029_AddRetentionUnusedSince")] + partial class AddRetentionUnusedSince + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261023050029_AddRetentionUnusedSince.cs b/src/BaGet.Database.MySql/Migrations/20261023050029_AddRetentionUnusedSince.cs new file mode 100644 index 000000000..32b606eb3 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261023050029_AddRetentionUnusedSince.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddRetentionUnusedSince : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "UnusedSince", + table: "RetentionPolicies", + type: "datetime(6)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "UnusedSince", + table: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261024001448_AddReplication.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261024001448_AddReplication.Designer.cs new file mode 100644 index 000000000..f98211b5e --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261024001448_AddReplication.Designer.cs @@ -0,0 +1,2360 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261024001448_AddReplication")] + partial class AddReplication + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("tinyint(1)"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("tinyint(1)"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("varchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime(6)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime(6)"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime(6)"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261024001448_AddReplication.cs b/src/BaGet.Database.MySql/Migrations/20261024001448_AddReplication.cs new file mode 100644 index 000000000..f91715f27 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261024001448_AddReplication.cs @@ -0,0 +1,140 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddReplication : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ReplicationConfigs", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + RepositoryKey = table.Column(type: "int", nullable: false), + Direction = table.Column(type: "int", nullable: false), + PeerUrl = table.Column(type: "varchar(2048)", maxLength: 2048, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PeerRepository = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ProtectedApiKey = table.Column(type: "varchar(2048)", maxLength: 2048, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Enabled = table.Column(type: "tinyint(1)", nullable: false), + OnDeploy = table.Column(type: "tinyint(1)", nullable: false), + ScheduleMinutes = table.Column(type: "int", nullable: true), + PropagateDeletes = table.Column(type: "tinyint(1)", nullable: false), + Conflict = table.Column(type: "int", nullable: false), + ScheduleStart = table.Column(type: "datetime(6)", nullable: true), + LastRun = table.Column(type: "datetime(6)", nullable: true), + LastResult = table.Column(type: "varchar(1024)", maxLength: 1024, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Modified = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationConfigs", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ReplicationItems", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ConfigKey = table.Column(type: "int", nullable: false), + Name = table.Column(type: "varchar(340)", maxLength: 340, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Version = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Part = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Digest = table.Column(type: "varchar(160)", maxLength: 160, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Synced = table.Column(type: "datetime(6)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationItems", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ReplicationRuns", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + ConfigKey = table.Column(type: "int", nullable: false), + Status = table.Column(type: "int", nullable: false), + Trigger = table.Column(type: "varchar(32)", maxLength: 32, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Actor = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + ResumedFrom = table.Column(type: "int", nullable: true), + Started = table.Column(type: "datetime(6)", nullable: false), + Finished = table.Column(type: "datetime(6)", nullable: true), + Examined = table.Column(type: "int", nullable: false), + Transferred = table.Column(type: "int", nullable: false), + Skipped = table.Column(type: "int", nullable: false), + Deleted = table.Column(type: "int", nullable: false), + Conflicts = table.Column(type: "int", nullable: false), + Failures = table.Column(type: "int", nullable: false), + Bytes = table.Column(type: "bigint", nullable: false), + Error = table.Column(type: "varchar(1024)", maxLength: 1024, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Detail = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationRuns", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_Name", + table: "ReplicationConfigs", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationItems_ConfigKey_Name_Version_Part", + table: "ReplicationItems", + columns: new[] { "ConfigKey", "Name", "Version", "Part" }); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationRuns_ConfigKey_Started", + table: "ReplicationRuns", + columns: new[] { "ConfigKey", "Started" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ReplicationConfigs"); + + migrationBuilder.DropTable( + name: "ReplicationItems"); + + migrationBuilder.DropTable( + name: "ReplicationRuns"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261024014436_AddDataProtectionKeys.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261024014436_AddDataProtectionKeys.Designer.cs new file mode 100644 index 000000000..e1b00a2b5 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261024014436_AddDataProtectionKeys.Designer.cs @@ -0,0 +1,2380 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261024014436_AddDataProtectionKeys")] + partial class AddDataProtectionKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Xml") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("tinyint(1)"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("tinyint(1)"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("varchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime(6)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime(6)"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime(6)"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261024014436_AddDataProtectionKeys.cs b/src/BaGet.Database.MySql/Migrations/20261024014436_AddDataProtectionKeys.cs new file mode 100644 index 000000000..0ec861aae --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261024014436_AddDataProtectionKeys.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddDataProtectionKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "DataProtectionKeys", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + FriendlyName = table.Column(type: "varchar(200)", maxLength: 200, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Xml = table.Column(type: "longtext", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4") + }, + constraints: table => + { + table.PrimaryKey("PK_DataProtectionKeys", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DataProtectionKeys"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261025012727_AddUserPendingApproval.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261025012727_AddUserPendingApproval.Designer.cs new file mode 100644 index 000000000..78d92d3a7 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261025012727_AddUserPendingApproval.Designer.cs @@ -0,0 +1,2383 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261025012727_AddUserPendingApproval")] + partial class AddUserPendingApproval + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PendingApproval") + .HasColumnType("tinyint(1)"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Xml") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("tinyint(1)"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("tinyint(1)"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("varchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime(6)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime(6)"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime(6)"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261025012727_AddUserPendingApproval.cs b/src/BaGet.Database.MySql/Migrations/20261025012727_AddUserPendingApproval.cs new file mode 100644 index 000000000..f6d47f446 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261025012727_AddUserPendingApproval.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddUserPendingApproval : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PendingApproval", + table: "AspNetUsers", + type: "tinyint(1)", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PendingApproval", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261025035642_AddOwnershipForeignKeys.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261025035642_AddOwnershipForeignKeys.Designer.cs new file mode 100644 index 000000000..1aacc1069 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261025035642_AddOwnershipForeignKeys.Designer.cs @@ -0,0 +1,2603 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261025035642_AddOwnershipForeignKeys")] + partial class AddOwnershipForeignKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PendingApproval") + .HasColumnType("tinyint(1)"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Xml") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("tinyint(1)"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("tinyint(1)"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("varchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime(6)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime(6)"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime(6)"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261025035642_AddOwnershipForeignKeys.cs b/src/BaGet.Database.MySql/Migrations/20261025035642_AddOwnershipForeignKeys.cs new file mode 100644 index 000000000..2153283fd --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261025035642_AddOwnershipForeignKeys.cs @@ -0,0 +1,367 @@ +using BaGet.Core; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddOwnershipForeignKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // Rows that pointed at nothing are removed first (children before parents), or the constraints below could not be created. + // On SQLite this runs before the table rebuilds that add the foreign keys. + foreach (var sql in OwnershipOrphanCleanup.Statements(OwnershipEngine.MySql)) + { + migrationBuilder.Sql(sql); + } + + migrationBuilder.CreateIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey"); + + migrationBuilder.AddForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags", + column: "ImageKey", + principalTable: "OciRepositories", + principalColumn: "Key"); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages"); + + migrationBuilder.DropForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts"); + + migrationBuilder.DropForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages"); + + migrationBuilder.DropForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs"); + + migrationBuilder.DropForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns"); + + migrationBuilder.DropForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults"); + + migrationBuilder.DropIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261025222409_RenameAspNetTables.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261025222409_RenameAspNetTables.Designer.cs new file mode 100644 index 000000000..a66be2ba0 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261025222409_RenameAspNetTables.Designer.cs @@ -0,0 +1,2603 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261025222409_RenameAspNetTables")] + partial class RenameAspNetTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PendingApproval") + .HasColumnType("tinyint(1)"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Xml") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("tinyint(1)"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("tinyint(1)"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("varchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime(6)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime(6)"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime(6)"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261025222409_RenameAspNetTables.cs b/src/BaGet.Database.MySql/Migrations/20261025222409_RenameAspNetTables.cs new file mode 100644 index 000000000..7f3d292a4 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261025222409_RenameAspNetTables.cs @@ -0,0 +1,456 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class RenameAspNetTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims"); + + migrationBuilder.RenameTable( + name: "AspNetUserTokens", + newName: "UserTokens"); + + migrationBuilder.RenameTable( + name: "AspNetUsers", + newName: "Users"); + + migrationBuilder.RenameTable( + name: "AspNetUserRoles", + newName: "UserRoles"); + + migrationBuilder.RenameTable( + name: "AspNetUserLogins", + newName: "UserLogins"); + + migrationBuilder.RenameTable( + name: "AspNetUserClaims", + newName: "UserClaims"); + + migrationBuilder.RenameTable( + name: "AspNetRoles", + newName: "Roles"); + + migrationBuilder.RenameTable( + name: "AspNetRoleClaims", + newName: "RoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "UserRoles", + newName: "IX_UserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserLogins_UserId", + table: "UserLogins", + newName: "IX_UserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserClaims_UserId", + table: "UserClaims", + newName: "IX_UserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "RoleClaims", + newName: "IX_RoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_Users", + table: "Users", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_Roles", + table: "Roles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Users", + table: "Users"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Roles", + table: "Roles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims"); + + migrationBuilder.RenameTable( + name: "UserTokens", + newName: "AspNetUserTokens"); + + migrationBuilder.RenameTable( + name: "Users", + newName: "AspNetUsers"); + + migrationBuilder.RenameTable( + name: "UserRoles", + newName: "AspNetUserRoles"); + + migrationBuilder.RenameTable( + name: "UserLogins", + newName: "AspNetUserLogins"); + + migrationBuilder.RenameTable( + name: "UserClaims", + newName: "AspNetUserClaims"); + + migrationBuilder.RenameTable( + name: "Roles", + newName: "AspNetRoles"); + + migrationBuilder.RenameTable( + name: "RoleClaims", + newName: "AspNetRoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_UserRoles_RoleId", + table: "AspNetUserRoles", + newName: "IX_AspNetUserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_UserLogins_UserId", + table: "AspNetUserLogins", + newName: "IX_AspNetUserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_UserClaims_UserId", + table: "AspNetUserClaims", + newName: "IX_AspNetUserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_RoleClaims_RoleId", + table: "AspNetRoleClaims", + newName: "IX_AspNetRoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs b/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs index d9a6e93c8..207e12a68 100644 --- a/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs +++ b/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs @@ -3,8 +3,11 @@ using BaGet.Database.MySql; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +#nullable disable + namespace BaGet.Database.MySql.Migrations { [DbContext(typeof(MySqlContext))] @@ -14,223 +17,2582 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "3.1.18") + .HasAnnotation("ProductVersion", "10.0.13") .HasAnnotation("Relational:MaxIdentifierLength", 64); - modelBuilder.Entity("BaGet.Core.Package", b => + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("int"); - b.Property("Authors") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); - - b.Property("Description") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); - b.Property("Downloads") - .HasColumnType("bigint"); + b.Property("Created") + .HasColumnType("datetime(6)"); - b.Property("HasEmbeddedIcon") - .HasColumnType("tinyint(1)"); + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); - b.Property("HasReadme") - .HasColumnType("tinyint(1)"); + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); - b.Property("IconUrl") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); - b.Property("Id") + b.Property("Reason") .IsRequired() - .HasColumnType("varchar(128) CHARACTER SET utf8mb4") - .HasMaxLength(128); + .HasMaxLength(128) + .HasColumnType("varchar(128)"); - b.Property("IsPrerelease") - .HasColumnType("tinyint(1)"); + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); - b.Property("Language") - .HasColumnType("varchar(20) CHARACTER SET utf8mb4") - .HasMaxLength(20); + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); - b.Property("LicenseUrl") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); + b.Property("Resolved") + .HasColumnType("datetime(6)"); - b.Property("Listed") - .HasColumnType("tinyint(1)"); + b.HasKey("Key"); - b.Property("MinClientVersion") - .HasColumnType("varchar(44) CHARACTER SET utf8mb4") - .HasMaxLength(44); + b.HasIndex("RepositoryKey", "PackageId"); - b.Property("NormalizedVersionString") + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Action") .IsRequired() - .HasColumnName("Version") - .HasColumnType("varchar(64) CHARACTER SET utf8mb4") - .HasMaxLength(64); + .HasMaxLength(64) + .HasColumnType("varchar(64)"); - b.Property("OriginalVersionString") - .HasColumnName("OriginalVersion") - .HasColumnType("varchar(64) CHARACTER SET utf8mb4") - .HasMaxLength(64); + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); - b.Property("ProjectUrl") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); + b.Property("Created") + .HasColumnType("datetime(6)"); - b.Property("Published") + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") .HasColumnType("datetime(6)"); - b.Property("ReleaseNotes") - .HasColumnName("ReleaseNotes") - .HasColumnType("longtext CHARACTER SET utf8mb4"); + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); - b.Property("RepositoryType") - .HasColumnType("varchar(100) CHARACTER SET utf8mb4") - .HasMaxLength(100); + b.Property("Expires") + .HasColumnType("datetime(6)"); - b.Property("RepositoryUrl") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); - b.Property("RequireLicenseAcceptance") - .HasColumnType("tinyint(1)"); + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); - b.Property("RowVersion") - .IsConcurrencyToken() - .ValueGeneratedOnAddOrUpdate() - .HasColumnType("timestamp(6)"); + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); - b.Property("SemVerLevel") + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() .HasColumnType("int"); - b.Property("Summary") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); - b.Property("Tags") - .HasColumnType("longtext CHARACTER SET utf8mb4") - .HasMaxLength(4000); + b.Property("ApiKeyKey") + .HasColumnType("int"); - b.Property("Title") - .HasColumnType("varchar(256) CHARACTER SET utf8mb4") - .HasMaxLength(256); + b.Property("RepositoryKey") + .HasColumnType("int"); b.HasKey("Key"); - b.HasIndex("Id"); + b.HasIndex("RepositoryKey"); - b.HasIndex("Id", "NormalizedVersionString") + b.HasIndex("ApiKeyKey", "RepositoryKey") .IsUnique(); - b.ToTable("Packages"); + b.ToTable("ApiKeyRepositories"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("int"); + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { b.Property("Id") - .HasColumnType("varchar(128) CHARACTER SET utf8mb4") - .HasMaxLength(128); + .HasColumnType("varchar(255)"); - b.Property("PackageKey") + b.Property("AccessFailedCount") .HasColumnType("int"); - b.Property("TargetFramework") - .HasColumnType("varchar(256) CHARACTER SET utf8mb4") - .HasMaxLength(256); + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); - b.Property("VersionRange") - .HasColumnType("varchar(256) CHARACTER SET utf8mb4") - .HasMaxLength(256); + b.Property("Created") + .HasColumnType("datetime(6)"); - b.HasKey("Key"); + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); - b.HasIndex("Id"); + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); - b.HasIndex("PackageKey"); + b.Property("IsAdministrator") + .HasColumnType("tinyint(1)"); - b.ToTable("PackageDependencies"); + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PendingApproval") + .HasColumnType("tinyint(1)"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("Users", (string)null); }); - modelBuilder.Entity("BaGet.Core.PackageType", b => + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("int"); - b.Property("Name") - .HasColumnType("varchar(512) CHARACTER SET utf8mb4") - .HasMaxLength(512); + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); - b.Property("PackageKey") + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() .HasColumnType("int"); - b.Property("Version") - .HasColumnType("varchar(64) CHARACTER SET utf8mb4") - .HasMaxLength(64); + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Xml") + .HasColumnType("longtext"); b.HasKey("Key"); - b.HasIndex("Name"); + b.ToTable("DataProtectionKeys"); + }); - b.HasIndex("PackageKey"); + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - b.ToTable("PackageTypes"); + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.GroupMember", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("int"); - b.Property("Moniker") - .HasColumnType("varchar(256) CHARACTER SET utf8mb4") - .HasMaxLength(256); + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); - b.Property("PackageKey") + b.Property("GroupKey") .HasColumnType("int"); + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + b.HasKey("Key"); - b.HasIndex("Moniker"); + b.HasIndex("UserId"); - b.HasIndex("PackageKey"); + b.HasIndex("GroupKey", "UserId") + .IsUnique(); - b.ToTable("TargetFrameworks"); + b.ToTable("GroupMembers"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("Dependencies") - .HasForeignKey("PackageKey"); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)") + .UseCollation("utf8mb4_bin"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); }); - modelBuilder.Entity("BaGet.Core.PackageType", b => + modelBuilder.Entity("BaGet.Core.MavenFile", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("PackageTypes") - .HasForeignKey("PackageKey") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)") + .UseCollation("utf8mb4_bin"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("varchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.MavenVersion", b => { - b.HasOne("BaGet.Core.Package", "Package") + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("varchar(214)") + .UseCollation("utf8mb4_bin"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("longtext"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("varchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("varchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)") + .UseCollation("utf8mb4_bin"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("tinyint(1)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("tinyint(1)"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("tinyint(1)"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("varchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("varchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime(6)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime(6)"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime(6)"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("varchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("tinyint(1)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime(6)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("tinyint(1)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime(6)"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("tinyint(1)"); + + b.Property("Modified") + .HasColumnType("datetime(6)"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime(6)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime(6)"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") .WithMany("TargetFrameworks") .HasForeignKey("PackageKey") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); }); #pragma warning restore 612, 618 } diff --git a/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs b/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs index 2156d90c3..724e438d3 100644 --- a/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs +++ b/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs @@ -1,33 +1,38 @@ -using System; +using System; using BaGet.Core; using BaGet.Database.MySql; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class MySqlApplicationExtensions { - public static class MySqlApplicationExtensions + public static BaGetApplication AddMySqlDatabase(this BaGetApplication app) { - public static BaGetApplication AddMySqlDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("MySql", (provider, options) => { - app.Services.AddBaGetDbContextProvider("MySql", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - options.UseMySql(databaseOptions.Value.ConnectionString); - }); + MySqlDatabaseContextFactory.Configure( + options, + databaseOptions.Value.ConnectionString, + databaseOptions.Value.MySqlServerVersion); + }); - return app; - } + app.Services.TryAddEnumerable( + ServiceDescriptor.Singleton()); - public static BaGetApplication AddMySqlDatabase( - this BaGetApplication app, - Action configure) - { - app.AddMySqlDatabase(); - app.Services.Configure(configure); - return app; - } + return app; + } + + public static BaGetApplication AddMySqlDatabase( + this BaGetApplication app, + Action configure) + { + app.AddMySqlDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.MySql/MySqlContext.cs b/src/BaGet.Database.MySql/MySqlContext.cs index 49bbb65fb..c22a08d63 100644 --- a/src/BaGet.Database.MySql/MySqlContext.cs +++ b/src/BaGet.Database.MySql/MySqlContext.cs @@ -1,30 +1,75 @@ -using BaGet.Core; +using BaGet.Core; using Microsoft.EntityFrameworkCore; -using MySql.Data.MySqlClient; +using MySqlConnector; -namespace BaGet.Database.MySql +namespace BaGet.Database.MySql; + +public class MySqlContext : AbstractContext { - public class MySqlContext : AbstractContext + /// + /// The MySQL Server error code for when a unique constraint is violated. + /// + private const int UniqueConstraintViolationErrorCode = 1062; + + /// The binary collation of the npm identifier columns. + internal const string NpmCollation = "utf8mb4_bin"; + + public MySqlContext(DbContextOptions options) : base(options) + { + } + + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) { - /// - /// The MySQL Server error code for when a unique constraint is violated. - /// - private const int UniqueConstraintViolationErrorCode = 1062; - - public MySqlContext(DbContextOptions options) : base(options) - { - } - - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - return exception.InnerException is MySqlException mysqlException && - mysqlException.Number == UniqueConstraintViolationErrorCode; - } - - /// - /// MySQL does not support LIMIT clauses in subqueries for certain subquery operators. - /// See: https://dev.mysql.com/doc/refman/8.0/en/subquery-restrictions.html - /// - public override bool SupportsLimitInSubqueries => false; + return exception.InnerException is MySqlException mysqlException && + mysqlException.Number == UniqueConstraintViolationErrorCode; + } + + /// + /// MySQL does not support LIMIT clauses in subqueries for certain subquery operators. + /// See: https://dev.mysql.com/doc/refman/8.0/en/subquery-restrictions.html + /// + public override bool SupportsLimitInSubqueries => false; + + /// + /// The long string columns are stored as "longtext" rather than the "varchar(4000)" + /// that a 4000 character maximum length would otherwise map to. + /// + /// + /// This is what the database has had since the schema was created, and it cannot be + /// changed: MySQL limits a row to 65535 bytes, and utf8mb4 needs up to four bytes a + /// character, so a single varchar(4000) column takes 16000 bytes and these eight + /// together are far beyond the limit. Declaring the type here keeps the model and + /// the database in agreement, so a migration for an unrelated change does not try to + /// convert them. + /// + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + var package = builder.Entity(); + + package.Property(p => p.Authors).HasColumnType("longtext"); + package.Property(p => p.Description).HasColumnType("longtext"); + package.Property(p => p.IconUrl).HasColumnType("longtext"); + package.Property(p => p.LicenseUrl).HasColumnType("longtext"); + package.Property(p => p.ProjectUrl).HasColumnType("longtext"); + package.Property(p => p.RepositoryUrl).HasColumnType("longtext"); + package.Property(p => p.Summary).HasColumnType("longtext"); + package.Property(p => p.Tags).HasColumnType("longtext"); + + // npm package names and dist-tags are case-sensitive (legacy names such as JSONStream exist): compared by code point, + // never by the default case-insensitive collation, so an exact lookup and the unique index behave as on SQLite and + // PostgreSQL. + builder.Entity().Property(p => p.Name).UseCollation(NpmCollation); + builder.Entity().Property(t => t.Tag).UseCollation(NpmCollation); + + // Maven coordinates, versions and file names are case-sensitive folders, compared by code point for the same reason. + builder.Entity().Property(a => a.GroupId).UseCollation(NpmCollation); + builder.Entity().Property(a => a.ArtifactId).UseCollation(NpmCollation); + builder.Entity().Property(v => v.Version).UseCollation(NpmCollation); + builder.Entity().Property(f => f.FileName).UseCollation(NpmCollation); + + // Tags are case-sensitive (image names and digests are lower case by rule). + builder.Entity().Property(t => t.Name).UseCollation(NpmCollation); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.MySql/MySqlContextFactory.cs b/src/BaGet.Database.MySql/MySqlContextFactory.cs new file mode 100644 index 000000000..1a80f8885 --- /dev/null +++ b/src/BaGet.Database.MySql/MySqlContextFactory.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace BaGet.Database.MySql; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class MySqlContextFactory : IDesignTimeDbContextFactory +{ + public MySqlContext CreateDbContext(string[] args) + { + // Parse rather than detect: detecting the version connects to the server, which + // would put the design-time tools back off line. + var options = new DbContextOptionsBuilder() + .UseMySql( + "Server=localhost;Database=baget;User=baget", + ServerVersion.Parse("8.0.0-mysql")) + .Options; + + return new MySqlContext(options); + } +} \ No newline at end of file diff --git a/src/BaGet.Database.MySql/MySqlDatabaseContextFactory.cs b/src/BaGet.Database.MySql/MySqlDatabaseContextFactory.cs new file mode 100644 index 000000000..ce3162835 --- /dev/null +++ b/src/BaGet.Database.MySql/MySqlDatabaseContextFactory.cs @@ -0,0 +1,44 @@ +using System; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Database.MySql; + +/// +/// Opens a on any MySql connection string; see . +/// +public class MySqlDatabaseContextFactory : IDatabaseContextFactory +{ + /// + public string DatabaseType => "MySql"; + + /// + public IContext Create( + string connectionString, + DatabaseOptions? options = null, + Action? configure = null) + { + var builder = new DbContextOptionsBuilder(); + + Configure(builder, connectionString, options?.MySqlServerVersion); + configure?.Invoke(builder); + + return new MySqlContext(builder.Options); + } + + /// + /// The one place the provider is configured: used by both this factory and the application's + /// registration, so a second database is configured exactly like the main one. + /// + internal static void Configure(DbContextOptionsBuilder options, string? connectionString, string? mySqlServerVersion) + { + // Detecting the version connects to the server, and these options are also built whenever the + // contexts are enumerated (including by the design-time tools). Prefer the configured version so + // that building options stays offline; otherwise detect it against this connection string. + var serverVersion = string.IsNullOrWhiteSpace(mySqlServerVersion) + ? ServerVersion.AutoDetect(connectionString) + : ServerVersion.Parse(mySqlServerVersion); + + options.UseMySql(connectionString, serverVersion); + } +} diff --git a/src/BaGet.Database.MySql/README.md b/src/BaGet.Database.MySql/README.md new file mode 100644 index 000000000..6aa1a71aa --- /dev/null +++ b/src/BaGet.Database.MySql/README.md @@ -0,0 +1,49 @@ +# Extension.BaGet.Database.MySql + +The MySQL database provider of [BaGet Extension](https://pieroviano.github.io/BaGet/), built on `Microting.EntityFrameworkCore.MySql` (a maintained Pomelo fork). + +```powershell +dotnet add package Extension.BaGet.Database.MySql +``` + +## Usage + +Register it in the `BaGetApplication` callback; it activates when `Database:Type` is `MySql`: + +```csharp +services.AddBaGetWebApplication(app => app.AddMySqlDatabase()); +``` + +| Setting | Value | +|---|---| +| `Database:Type` | `MySql` | +| `Database:ConnectionString` | e.g. `Server=localhost;Database=baget;User=root;Password=...` | +| `Database:MySqlServerVersion` | e.g. `8.0.36-mysql`; empty auto-detects (opens a connection at startup) | + +`AddMySqlDatabase` also registers `MySqlDatabaseContextFactory` (`IDatabaseContextFactory`), which opens a `MySqlContext` on any connection string for the Settings page's database copy. + +## Migrations (contributors) + +The project has its own design-time context factory, so `dotnet ef` needs no startup project and no +running database. The tool version is pinned by `.config/dotnet-tools.json`; run `dotnet tool restore` once. + +From this folder: + +``` +dotnet ef migrations add MigrationName --context MySqlContext --output-dir Migrations +dotnet ef migrations has-pending-model-changes --context MySqlContext +``` + +A model change needs a migration in **all four** `BaGet.Database.*` projects, and each must then report +no pending model changes. Keep schema changes additive (new tables, nullable foreign keys): SQLite cannot +alter a foreign key in place. + +BaGet applies pending migrations itself when it starts. + +- List migrations without a server: `dotnet ef migrations list --context MySqlContext`. +- Never run `dotnet ef migrations remove --no-build`: with a stale assembly it deleted the previous migration. Delete the generated files by hand and restore the model snapshot from `HEAD`. +- Entity Framework is 10.0.13; the MySQL provider is `Microting.EntityFrameworkCore.MySql`; all four providers move together. + +## Schema notes + +- The long text columns of `Packages` (authors, description, summary, URLs, tags) are `longtext`: as `varchar(4000)` they exceed MySQL's 65,535-byte row limit and strict-mode servers refuse the table. diff --git a/src/BaGet.Database.MySql/readme.md b/src/BaGet.Database.MySql/readme.md deleted file mode 100644 index 24413c96f..000000000 --- a/src/BaGet.Database.MySql/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -# BaGet's MySQL Database Provider - -This project contains BaGet's MySQL database provider. - -## Migrations - -Add a migration with: - -``` -dotnet ef migrations add MigrationName --context MySqlContext --output-dir Migrations --startup-project ..\BaGet\BaGet.csproj - -dotnet ef database update --context MySqlContext -``` diff --git a/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj b/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj index afc7a1214..41dc89f19 100644 --- a/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj +++ b/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj @@ -1,18 +1,26 @@ - netstandard2.0 - + net10.0 + latest NuGet - The libraries to host BaGet on PostgreSQL. + The libraries to host BaGet Extension on PostgreSQL. + enable - + + + + + + + + diff --git a/src/BaGet.Database.PostgreSql/Migrations/20190311172227_Initial.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20190311172227_Initial.Designer.cs index 5cc886188..3010a2ac0 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/20190311172227_Initial.Designer.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/20190311172227_Initial.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.PostgreSql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.PostgreSql/Migrations/20190914220105_AddOriginalVersionStringColumn.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20190914220105_AddOriginalVersionStringColumn.Designer.cs index 94526adaa..d534982f0 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/20190914220105_AddOriginalVersionStringColumn.Designer.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/20190914220105_AddOriginalVersionStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.PostgreSql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.PostgreSql/Migrations/20200109085355_AddReleaseNotesStringColumn.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20200109085355_AddReleaseNotesStringColumn.Designer.cs index b3a6aacff..810ebe6b0 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/20200109085355_AddReleaseNotesStringColumn.Designer.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/20200109085355_AddReleaseNotesStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.PostgreSql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.PostgreSql/Migrations/20200208053115_FixVersionCaseSensitivity.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20200208053115_FixVersionCaseSensitivity.Designer.cs index f5c0aaf98..fb0e7a385 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/20200208053115_FixVersionCaseSensitivity.Designer.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/20200208053115_FixVersionCaseSensitivity.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.PostgreSql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.PostgreSql/Migrations/20200210004256_AddHasEmbeddedIconColumn.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20200210004256_AddHasEmbeddedIconColumn.Designer.cs index aa9cfde3e..7a3aeb4a4 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/20200210004256_AddHasEmbeddedIconColumn.Designer.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/20200210004256_AddHasEmbeddedIconColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.PostgreSql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.PostgreSql/Migrations/20210919191649_RemoveReleaseNotesMaxLength.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20210919191649_RemoveReleaseNotesMaxLength.Designer.cs index d90adb861..423350324 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/20210919191649_RemoveReleaseNotesMaxLength.Designer.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/20210919191649_RemoveReleaseNotesMaxLength.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.PostgreSql; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261016060010_AddDeprecationAndVulnerability.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261016060010_AddDeprecationAndVulnerability.Designer.cs new file mode 100644 index 000000000..615250a8d --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261016060010_AddDeprecationAndVulnerability.Designer.cs @@ -0,0 +1,356 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261016060010_AddDeprecationAndVulnerability")] + partial class AddDeprecationAndVulnerability + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261016060010_AddDeprecationAndVulnerability.cs b/src/BaGet.Database.PostgreSql/Migrations/20261016060010_AddDeprecationAndVulnerability.cs new file mode 100644 index 000000000..ffa320db5 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261016060010_AddDeprecationAndVulnerability.cs @@ -0,0 +1,97 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddDeprecationAndVulnerability : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // Published has to become "timestamp with time zone": Npgsql maps a DateTime whose + // Kind is Utc to that type, and Package.Published is always UTC. The conversion is + // written out rather than left to the scaffolded AlterColumn because PostgreSQL + // reads a naive timestamp in the session's time zone when converting, which would + // shift every publish date on a server that is not on UTC. "AT TIME ZONE 'UTC'" + // states that the stored values are already UTC, so the instant is preserved. + migrationBuilder.Sql( + @"ALTER TABLE ""Packages"" " + + @"ALTER COLUMN ""Published"" TYPE timestamp with time zone " + + @"USING ""Published"" AT TIME ZONE 'UTC';"); + + migrationBuilder.CreateTable( + name: "PackageDeprecations", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Reasons = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + Message = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + AlternatePackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + AlternateVersionRange = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + PackageKey = table.Column(type: "integer", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageDeprecations", x => x.Key); + table.ForeignKey( + name: "FK_PackageDeprecations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateTable( + name: "PackageVulnerabilities", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + AdvisoryUrl = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + Severity = table.Column(type: "integer", nullable: false), + VersionRange = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + PackageKey = table.Column(type: "integer", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageVulnerabilities", x => x.Key); + table.ForeignKey( + name: "FK_PackageVulnerabilities_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageDeprecations_PackageKey", + table: "PackageDeprecations", + column: "PackageKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageVulnerabilities_PackageKey", + table: "PackageVulnerabilities", + column: "PackageKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageDeprecations"); + + migrationBuilder.DropTable( + name: "PackageVulnerabilities"); + + // The inverse conversion, again stating that the values are UTC. + migrationBuilder.Sql( + @"ALTER TABLE ""Packages"" " + + @"ALTER COLUMN ""Published"" TYPE timestamp without time zone " + + @"USING ""Published"" AT TIME ZONE 'UTC';"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017011645_AddCatalog.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017011645_AddCatalog.Designer.cs new file mode 100644 index 000000000..c1fa9d8c1 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017011645_AddCatalog.Designer.cs @@ -0,0 +1,395 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261017011645_AddCatalog")] + partial class AddCatalog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017011645_AddCatalog.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017011645_AddCatalog.cs new file mode 100644 index 000000000..df5debcbe --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017011645_AddCatalog.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddCatalog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "CatalogLeafs", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + CommitId = table.Column(type: "character varying(36)", maxLength: 36, nullable: false), + CommitTimestamp = table.Column(type: "timestamp with time zone", nullable: false), + Type = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + PackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_CatalogLeafs", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_CommitId", + table: "CatalogLeafs", + column: "CommitId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "CatalogLeafs"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017012806_AddAccounts.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017012806_AddAccounts.Designer.cs new file mode 100644 index 000000000..86701caa8 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017012806_AddAccounts.Designer.cs @@ -0,0 +1,782 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261017012806_AddAccounts")] + partial class AddAccounts + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017012806_AddAccounts.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017012806_AddAccounts.cs new file mode 100644 index 000000000..55bf580b7 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017012806_AddAccounts.cs @@ -0,0 +1,341 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddAccounts : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeys", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + UserId = table.Column(type: "character varying(450)", maxLength: 450, nullable: false), + Description = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + HashedKey = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Scopes = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + PackageGlobPattern = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Expires = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeys", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoles", + columns: table => new + { + Id = table.Column(type: "text", nullable: false), + Name = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetUsers", + columns: table => new + { + Id = table.Column(type: "text", nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false), + UserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "boolean", nullable: false), + PasswordHash = table.Column(type: "text", nullable: true), + SecurityStamp = table.Column(type: "text", nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true), + PhoneNumber = table.Column(type: "text", nullable: true), + PhoneNumberConfirmed = table.Column(type: "boolean", nullable: false), + TwoFactorEnabled = table.Column(type: "boolean", nullable: false), + LockoutEnd = table.Column(type: "timestamp with time zone", nullable: true), + LockoutEnabled = table.Column(type: "boolean", nullable: false), + AccessFailedCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Organizations", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Organizations", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "PackageOwners", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + PackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + OwnerName = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + IsVerified = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageOwners", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RoleId = table.Column(type: "text", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserClaims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + UserId = table.Column(type: "text", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserLogins", + columns: table => new + { + LoginProvider = table.Column(type: "text", nullable: false), + ProviderKey = table.Column(type: "text", nullable: false), + ProviderDisplayName = table.Column(type: "text", nullable: true), + UserId = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserRoles", + columns: table => new + { + UserId = table.Column(type: "text", nullable: false), + RoleId = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserTokens", + columns: table => new + { + UserId = table.Column(type: "text", nullable: false), + LoginProvider = table.Column(type: "text", nullable: false), + Name = table.Column(type: "text", nullable: false), + Value = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OrganizationMembers", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + OrganizationKey = table.Column(type: "integer", nullable: true), + UserId = table.Column(type: "character varying(450)", maxLength: 450, nullable: false), + IsAdmin = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OrganizationMembers", x => x.Key); + table.ForeignKey( + name: "FK_OrganizationMembers_Organizations_OrganizationKey", + column: x => x.OrganizationKey, + principalTable: "Organizations", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_HashedKey", + table: "ApiKeys", + column: "HashedKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_UserId", + table: "ApiKeys", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "AspNetRoleClaims", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "AspNetRoles", + column: "NormalizedName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserClaims_UserId", + table: "AspNetUserClaims", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserLogins_UserId", + table: "AspNetUserLogins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "AspNetUsers", + column: "NormalizedEmail"); + + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "AspNetUsers", + column: "NormalizedUserName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_OrganizationKey", + table: "OrganizationMembers", + column: "OrganizationKey"); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_UserId", + table: "OrganizationMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Organizations_Name", + table: "Organizations", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_OwnerName", + table: "PackageOwners", + column: "OwnerName"); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeys"); + + migrationBuilder.DropTable( + name: "AspNetRoleClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserLogins"); + + migrationBuilder.DropTable( + name: "AspNetUserRoles"); + + migrationBuilder.DropTable( + name: "AspNetUserTokens"); + + migrationBuilder.DropTable( + name: "OrganizationMembers"); + + migrationBuilder.DropTable( + name: "PackageOwners"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + + migrationBuilder.DropTable( + name: "Organizations"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..73d78e595 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.Designer.cs @@ -0,0 +1,846 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261017014349_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.cs new file mode 100644 index 000000000..d8f0bdf3e --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.cs @@ -0,0 +1,64 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + SubmissionId = table.Column(type: "character varying(36)", maxLength: 36, nullable: false), + PackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + PackageKey = table.Column(type: "integer", nullable: true), + Type = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + State = table.Column(type: "integer", nullable: false), + Message = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Completed = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..2416bcc28 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.Designer.cs @@ -0,0 +1,891 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261017020119_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.cs new file mode 100644 index 000000000..82aa26416 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.cs @@ -0,0 +1,47 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + PackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Reason = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Details = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: false), + ReporterEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Resolved = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261018043337_AddAdministrators.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261018043337_AddAdministrators.Designer.cs new file mode 100644 index 000000000..651c98839 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261018043337_AddAdministrators.Designer.cs @@ -0,0 +1,894 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261018043337_AddAdministrators")] + partial class AddAdministrators + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261018043337_AddAdministrators.cs b/src/BaGet.Database.PostgreSql/Migrations/20261018043337_AddAdministrators.cs new file mode 100644 index 000000000..d3ba37e8c --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261018043337_AddAdministrators.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddAdministrators : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsAdministrator", + table: "AspNetUsers", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsAdministrator", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261020072003_AddRepositories.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261020072003_AddRepositories.Designer.cs new file mode 100644 index 000000000..9f4045971 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261020072003_AddRepositories.Designer.cs @@ -0,0 +1,992 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261020072003_AddRepositories")] + partial class AddRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261020072003_AddRepositories.cs b/src/BaGet.Database.PostgreSql/Migrations/20261020072003_AddRepositories.cs new file mode 100644 index 000000000..ff11a0fb3 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261020072003_AddRepositories.cs @@ -0,0 +1,221 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports"); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageValidations", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "Packages", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageOwners", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "CatalogLeafs", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "AbuseReports", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.CreateTable( + name: "Projects", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + DisplayName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Projects", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "Repositories", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Format = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + Kind = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + ProjectKey = table.Column(type: "integer", nullable: true), + Settings = table.Column(type: "text", nullable: true), + AnonymousRead = table.Column(type: "boolean", nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Repositories", x => x.Key); + }); + + // The default repository (key 1 = RepositoryKey's column default, so every existing row already belongs to + // it). Created here, not only by startup, so that applying migrations without RunMigrationsAtStartup + // (dotnet ef database update, an SQL script) cannot leave a new repository to take key 1. + migrationBuilder.InsertData( + table: "Repositories", + columns: new[] { "Key", "Name", "Format", "Kind", "AnonymousRead", "Created" }, + values: new object[] { 1, "default", "NuGet", "Local", true, DateTime.UtcNow }); + + // An explicit key does not advance an identity sequence: make the next generated key 2. + migrationBuilder.Sql("SELECT setval(pg_get_serial_sequence('\"Repositories\"', 'Key'), 1);"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages", + columns: new[] { "RepositoryKey", "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Projects_Name", + table: "Projects", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Repositories_Name", + table: "Repositories", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Projects"); + + migrationBuilder.DropTable( + name: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "Packages"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_Packages_Id_Version", + table: "Packages", + columns: new[] { "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021035316_AddPackageSymbols.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021035316_AddPackageSymbols.Designer.cs new file mode 100644 index 000000000..c0cd83703 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021035316_AddPackageSymbols.Designer.cs @@ -0,0 +1,1037 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261021035316_AddPackageSymbols")] + partial class AddPackageSymbols + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021035316_AddPackageSymbols.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021035316_AddPackageSymbols.cs new file mode 100644 index 000000000..a7fdc0a7d --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021035316_AddPackageSymbols.cs @@ -0,0 +1,51 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddPackageSymbols : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageSymbols", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + PackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + FileName = table.Column(type: "character varying(255)", maxLength: 255, nullable: false), + SymbolKey = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageSymbols", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_FileName_SymbolKey", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "FileName", "SymbolKey" }); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_PackageId_PackageVersion", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "PackageId", "PackageVersion" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageSymbols"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021040429_AddAccessControl.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021040429_AddAccessControl.Designer.cs new file mode 100644 index 000000000..9fc28d9e9 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021040429_AddAccessControl.Designer.cs @@ -0,0 +1,1225 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261021040429_AddAccessControl")] + partial class AddAccessControl + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021040429_AddAccessControl.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021040429_AddAccessControl.cs new file mode 100644 index 000000000..58883c149 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021040429_AddAccessControl.cs @@ -0,0 +1,232 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddAccessControl : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AccessAuditEntries", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Actor = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Action = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Subject = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Details = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AccessAuditEntries", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "Groups", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Description = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + IsBuiltIn = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Groups", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "PermissionTargets", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + RepositoryPatterns = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + IncludePatterns = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + ExcludePatterns = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + ProjectKey = table.Column(type: "integer", nullable: true), + IsBuiltIn = table.Column(type: "boolean", nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionTargets", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ProjectMembers", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ProjectKey = table.Column(type: "integer", nullable: false), + PrincipalType = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + PrincipalId = table.Column(type: "character varying(450)", maxLength: 450, nullable: false), + Role = table.Column(type: "character varying(16)", maxLength: 16, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ProjectMembers", x => x.Key); + table.ForeignKey( + name: "FK_ProjectMembers_Projects_ProjectKey", + column: x => x.ProjectKey, + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "GroupMembers", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + GroupKey = table.Column(type: "integer", nullable: false), + UserId = table.Column(type: "character varying(450)", maxLength: 450, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_GroupMembers", x => x.Key); + table.ForeignKey( + name: "FK_GroupMembers_Groups_GroupKey", + column: x => x.GroupKey, + principalTable: "Groups", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PermissionGrants", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + TargetKey = table.Column(type: "integer", nullable: false), + PrincipalType = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + PrincipalId = table.Column(type: "character varying(450)", maxLength: 450, nullable: false), + Actions = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionGrants", x => x.Key); + table.ForeignKey( + name: "FK_PermissionGrants_PermissionTargets_TargetKey", + column: x => x.TargetKey, + principalTable: "PermissionTargets", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + // The upgrade defaults: what the server did before the access model existed. Everyone reads every + // repository; every authenticated caller deploys, annotates, deletes and manages (package ownership is + // still applied inside those actions). Explicit keys, so the grants below can name them. + var seeded = DateTime.UtcNow; + + migrationBuilder.InsertData( + table: "Groups", + columns: new[] { "Key", "Name", "Description", "Created", "IsBuiltIn" }, + values: new object[,] + { + { 1, "Everyone", "Every caller, anonymous ones included.", seeded, true }, + { 2, "Authenticated", "Every caller that presented valid credentials.", seeded, true }, + }); + + migrationBuilder.InsertData( + table: "PermissionTargets", + columns: new[] { "Key", "Name", "RepositoryPatterns", "IncludePatterns", "ExcludePatterns", "IsBuiltIn", "Created" }, + values: new object[,] + { + { 1, "Anyone reads every repository", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + { 2, "Authenticated users deploy", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + }); + + // Actions: Read = 1; Annotate | Deploy | Delete | Manage = 2 + 4 + 8 + 16 = 30. + migrationBuilder.InsertData( + table: "PermissionGrants", + columns: new[] { "Key", "TargetKey", "PrincipalType", "PrincipalId", "Actions" }, + values: new object[,] + { + { 1, 1, "Group", "1", 1 }, + { 2, 2, "Group", "2", 30 }, + }); + + // Explicit keys do not advance an identity sequence: make the next generated key of each table 3. + migrationBuilder.Sql("SELECT setval(pg_get_serial_sequence('\"Groups\"', 'Key'), 2);"); + migrationBuilder.Sql("SELECT setval(pg_get_serial_sequence('\"PermissionTargets\"', 'Key'), 2);"); + migrationBuilder.Sql("SELECT setval(pg_get_serial_sequence('\"PermissionGrants\"', 'Key'), 2);"); + + migrationBuilder.CreateIndex( + name: "IX_AccessAuditEntries_Created", + table: "AccessAuditEntries", + column: "Created"); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_GroupKey_UserId", + table: "GroupMembers", + columns: new[] { "GroupKey", "UserId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_UserId", + table: "GroupMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Groups_Name", + table: "Groups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionGrants_TargetKey_PrincipalType_PrincipalId", + table: "PermissionGrants", + columns: new[] { "TargetKey", "PrincipalType", "PrincipalId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_Name", + table: "PermissionTargets", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ProjectMembers_ProjectKey_PrincipalType_PrincipalId", + table: "ProjectMembers", + columns: new[] { "ProjectKey", "PrincipalType", "PrincipalId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AccessAuditEntries"); + + migrationBuilder.DropTable( + name: "GroupMembers"); + + migrationBuilder.DropTable( + name: "PermissionGrants"); + + migrationBuilder.DropTable( + name: "ProjectMembers"); + + migrationBuilder.DropTable( + name: "Groups"); + + migrationBuilder.DropTable( + name: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021055042_AddApiKeyRepositories.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021055042_AddApiKeyRepositories.Designer.cs new file mode 100644 index 000000000..a7a7a8b6b --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021055042_AddApiKeyRepositories.Designer.cs @@ -0,0 +1,1305 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261021055042_AddApiKeyRepositories")] + partial class AddApiKeyRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021055042_AddApiKeyRepositories.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021055042_AddApiKeyRepositories.cs new file mode 100644 index 000000000..69b06a053 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021055042_AddApiKeyRepositories.cs @@ -0,0 +1,53 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddApiKeyRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeyRepositories", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ApiKeyKey = table.Column(type: "integer", nullable: false), + RepositoryKey = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeyRepositories", x => x.Key); + table.ForeignKey( + name: "FK_ApiKeyRepositories_ApiKeys_ApiKeyKey", + column: x => x.ApiKeyKey, + principalTable: "ApiKeys", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_ApiKeyKey_RepositoryKey", + table: "ApiKeyRepositories", + columns: new[] { "ApiKeyKey", "RepositoryKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeyRepositories"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021155637_AddNpmTables.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021155637_AddNpmTables.Designer.cs new file mode 100644 index 000000000..caceeb42b --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021155637_AddNpmTables.Designer.cs @@ -0,0 +1,1431 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261021155637_AddNpmTables")] + partial class AddNpmTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261021155637_AddNpmTables.cs b/src/BaGet.Database.PostgreSql/Migrations/20261021155637_AddNpmTables.cs new file mode 100644 index 000000000..256e95224 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261021155637_AddNpmTables.cs @@ -0,0 +1,110 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddNpmTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "NpmPackages", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + Name = table.Column(type: "character varying(214)", maxLength: 214, nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Modified = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmPackages", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "NpmDistTags", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + PackageKey = table.Column(type: "integer", nullable: false), + Tag = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Version = table.Column(type: "character varying(256)", maxLength: 256, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmDistTags", x => x.Key); + table.ForeignKey( + name: "FK_NpmDistTags_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "NpmVersions", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + PackageKey = table.Column(type: "integer", nullable: false), + Version = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + Integrity = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + Shasum = table.Column(type: "character varying(40)", maxLength: 40, nullable: false), + TarballSize = table.Column(type: "bigint", nullable: false), + Manifest = table.Column(type: "text", nullable: false), + Deprecated = table.Column(type: "text", nullable: true), + Published = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmVersions", x => x.Key); + table.ForeignKey( + name: "FK_NpmVersions_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_NpmDistTags_PackageKey_Tag", + table: "NpmDistTags", + columns: new[] { "PackageKey", "Tag" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmPackages_RepositoryKey_Name", + table: "NpmPackages", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmVersions_PackageKey_Version", + table: "NpmVersions", + columns: new[] { "PackageKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "NpmDistTags"); + + migrationBuilder.DropTable( + name: "NpmVersions"); + + migrationBuilder.DropTable( + name: "NpmPackages"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261022010649_AddMavenTables.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261022010649_AddMavenTables.Designer.cs new file mode 100644 index 000000000..eae9b3b6f --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261022010649_AddMavenTables.Designer.cs @@ -0,0 +1,1597 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261022010649_AddMavenTables")] + partial class AddMavenTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261022010649_AddMavenTables.cs b/src/BaGet.Database.PostgreSql/Migrations/20261022010649_AddMavenTables.cs new file mode 100644 index 000000000..a019b89b9 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261022010649_AddMavenTables.cs @@ -0,0 +1,120 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddMavenTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MavenArtifacts", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + GroupId = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + ArtifactId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Modified = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenArtifacts", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "MavenVersions", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ArtifactKey = table.Column(type: "integer", nullable: false), + Version = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + IsSnapshot = table.Column(type: "boolean", nullable: false), + Name = table.Column(type: "character varying(512)", maxLength: 512, nullable: true), + Description = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + Packaging = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Modified = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenVersions", x => x.Key); + table.ForeignKey( + name: "FK_MavenVersions_MavenArtifacts_ArtifactKey", + column: x => x.ArtifactKey, + principalTable: "MavenArtifacts", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "MavenFiles", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + VersionKey = table.Column(type: "integer", nullable: false), + FileName = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + Classifier = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), + Extension = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + SnapshotTimestamp = table.Column(type: "character varying(15)", maxLength: 15, nullable: true), + SnapshotBuild = table.Column(type: "integer", nullable: false), + Size = table.Column(type: "bigint", nullable: false), + Sha1 = table.Column(type: "character varying(40)", maxLength: 40, nullable: false), + Md5 = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + Sha256 = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Sha512 = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenFiles", x => x.Key); + table.ForeignKey( + name: "FK_MavenFiles_MavenVersions_VersionKey", + column: x => x.VersionKey, + principalTable: "MavenVersions", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_MavenArtifacts_RepositoryKey_GroupId_ArtifactId", + table: "MavenArtifacts", + columns: new[] { "RepositoryKey", "GroupId", "ArtifactId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenFiles_VersionKey_FileName", + table: "MavenFiles", + columns: new[] { "VersionKey", "FileName" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenVersions_ArtifactKey_Version", + table: "MavenVersions", + columns: new[] { "ArtifactKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MavenFiles"); + + migrationBuilder.DropTable( + name: "MavenVersions"); + + migrationBuilder.DropTable( + name: "MavenArtifacts"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261022062049_AddOciTables.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261022062049_AddOciTables.Designer.cs new file mode 100644 index 000000000..f1029eada --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261022062049_AddOciTables.Designer.cs @@ -0,0 +1,1854 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261022062049_AddOciTables")] + partial class AddOciTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261022062049_AddOciTables.cs b/src/BaGet.Database.PostgreSql/Migrations/20261022062049_AddOciTables.cs new file mode 100644 index 000000000..4d022927c --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261022062049_AddOciTables.cs @@ -0,0 +1,226 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddOciTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "OciBlobs", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + Digest = table.Column(type: "character varying(140)", maxLength: 140, nullable: false), + Size = table.Column(type: "bigint", nullable: false), + RefCount = table.Column(type: "integer", nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobs", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "OciRepositories", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + Name = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Modified = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciRepositories", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "OciBlobLinks", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ImageKey = table.Column(type: "integer", nullable: false), + BlobKey = table.Column(type: "integer", nullable: false), + Manifests = table.Column(type: "integer", nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobLinks", x => x.Key); + table.ForeignKey( + name: "FK_OciBlobLinks_OciBlobs_BlobKey", + column: x => x.BlobKey, + principalTable: "OciBlobs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_OciBlobLinks_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciManifests", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ImageKey = table.Column(type: "integer", nullable: false), + Digest = table.Column(type: "character varying(140)", maxLength: 140, nullable: false), + MediaType = table.Column(type: "character varying(255)", maxLength: 255, nullable: false), + ArtifactType = table.Column(type: "character varying(255)", maxLength: 255, nullable: true), + SubjectDigest = table.Column(type: "character varying(140)", maxLength: 140, nullable: true), + Size = table.Column(type: "bigint", nullable: false), + Content = table.Column(type: "text", nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciManifests", x => x.Key); + table.ForeignKey( + name: "FK_OciManifests_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciUploads", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ImageKey = table.Column(type: "integer", nullable: false), + Reference = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + StorageUploadId = table.Column(type: "character varying(512)", maxLength: 512, nullable: false), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Updated = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciUploads", x => x.Key); + table.ForeignKey( + name: "FK_OciUploads_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciTags", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ImageKey = table.Column(type: "integer", nullable: false), + Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + ManifestKey = table.Column(type: "integer", nullable: false), + Updated = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciTags", x => x.Key); + table.ForeignKey( + name: "FK_OciTags_OciManifests_ManifestKey", + column: x => x.ManifestKey, + principalTable: "OciManifests", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_BlobKey", + table: "OciBlobLinks", + column: "BlobKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_ImageKey_BlobKey", + table: "OciBlobLinks", + columns: new[] { "ImageKey", "BlobKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobs_RepositoryKey_Digest", + table: "OciBlobs", + columns: new[] { "RepositoryKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_Digest", + table: "OciManifests", + columns: new[] { "ImageKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_SubjectDigest", + table: "OciManifests", + columns: new[] { "ImageKey", "SubjectDigest" }); + + migrationBuilder.CreateIndex( + name: "IX_OciRepositories_RepositoryKey_Name", + table: "OciRepositories", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ImageKey_Name", + table: "OciTags", + columns: new[] { "ImageKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ManifestKey", + table: "OciTags", + column: "ManifestKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_ImageKey", + table: "OciUploads", + column: "ImageKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_Reference", + table: "OciUploads", + column: "Reference", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OciBlobLinks"); + + migrationBuilder.DropTable( + name: "OciTags"); + + migrationBuilder.DropTable( + name: "OciUploads"); + + migrationBuilder.DropTable( + name: "OciBlobs"); + + migrationBuilder.DropTable( + name: "OciManifests"); + + migrationBuilder.DropTable( + name: "OciRepositories"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261023010843_AddRetention.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261023010843_AddRetention.Designer.cs new file mode 100644 index 000000000..a52b77c2c --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261023010843_AddRetention.Designer.cs @@ -0,0 +1,2008 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261023010843_AddRetention")] + partial class AddRetention + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261023010843_AddRetention.cs b/src/BaGet.Database.PostgreSql/Migrations/20261023010843_AddRetention.cs new file mode 100644 index 000000000..448f8c695 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261023010843_AddRetention.cs @@ -0,0 +1,121 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddRetention : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ArtifactUsages", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + Name = table.Column(type: "character varying(340)", maxLength: 340, nullable: false), + Version = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + LastUsed = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtifactUsages", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "RetentionHolds", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + Name = table.Column(type: "character varying(340)", maxLength: 340, nullable: false), + Version = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Reason = table.Column(type: "character varying(512)", maxLength: 512, nullable: true), + CreatedBy = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionHolds", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "RetentionPolicies", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + RepositoryKey = table.Column(type: "integer", nullable: true), + ProjectKey = table.Column(type: "integer", nullable: true), + Enabled = table.Column(type: "boolean", nullable: false), + NamePatterns = table.Column(type: "character varying(1024)", maxLength: 1024, nullable: true), + KeepLast = table.Column(type: "integer", nullable: true), + OlderThanDays = table.Column(type: "integer", nullable: true), + UnusedDays = table.Column(type: "integer", nullable: true), + PrereleaseOnly = table.Column(type: "boolean", nullable: false), + CacheLimitBytes = table.Column(type: "bigint", nullable: true), + UntaggedAfterDays = table.Column(type: "integer", nullable: true), + CollectGarbage = table.Column(type: "boolean", nullable: false), + ScheduleHours = table.Column(type: "integer", nullable: true), + ScheduleStart = table.Column(type: "timestamp with time zone", nullable: true), + LastRun = table.Column(type: "timestamp with time zone", nullable: true), + LastResult = table.Column(type: "character varying(1024)", maxLength: 1024, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Modified = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionPolicies", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_ArtifactUsages_RepositoryKey_Name_Version", + table: "ArtifactUsages", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionHolds_RepositoryKey_Name_Version", + table: "RetentionHolds", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_Name", + table: "RetentionPolicies", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ArtifactUsages"); + + migrationBuilder.DropTable( + name: "RetentionHolds"); + + migrationBuilder.DropTable( + name: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261023021747_AddScanning.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261023021747_AddScanning.Designer.cs new file mode 100644 index 000000000..71ef002ba --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261023021747_AddScanning.Designer.cs @@ -0,0 +1,2170 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261023021747_AddScanning")] + partial class AddScanning + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261023021747_AddScanning.cs b/src/BaGet.Database.PostgreSql/Migrations/20261023021747_AddScanning.cs new file mode 100644 index 000000000..9d14c9cde --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261023021747_AddScanning.cs @@ -0,0 +1,130 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddScanning : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Source", + table: "PackageVulnerabilities", + type: "character varying(32)", + maxLength: 32, + nullable: true); + + migrationBuilder.CreateTable( + name: "ScanPolicies", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: true), + ProjectKey = table.Column(type: "integer", nullable: true), + WarnSeverity = table.Column(type: "integer", nullable: true), + BlockDownloadSeverity = table.Column(type: "integer", nullable: true), + BlockDeploySeverity = table.Column(type: "integer", nullable: true), + BlockUnscanned = table.Column(type: "boolean", nullable: false), + Modified = table.Column(type: "timestamp with time zone", nullable: false), + ModifiedBy = table.Column(type: "character varying(256)", maxLength: 256, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanPolicies", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ScanResults", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RepositoryKey = table.Column(type: "integer", nullable: false, defaultValue: 1), + Name = table.Column(type: "character varying(400)", maxLength: 400, nullable: false), + Version = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Scanner = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + ScannedAt = table.Column(type: "timestamp with time zone", nullable: true), + Attempted = table.Column(type: "timestamp with time zone", nullable: false), + Error = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + Highest = table.Column(type: "integer", nullable: false), + FindingCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanResults", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ScanFindings", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ResultKey = table.Column(type: "integer", nullable: false), + VulnerabilityId = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Component = table.Column(type: "character varying(400)", maxLength: 400, nullable: false), + ComponentVersion = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Severity = table.Column(type: "integer", nullable: false), + Summary = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + AdvisoryUrl = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + FixedVersion = table.Column(type: "character varying(200)", maxLength: 200, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanFindings", x => x.Key); + table.ForeignKey( + name: "FK_ScanFindings_ScanResults_ResultKey", + column: x => x.ResultKey, + principalTable: "ScanResults", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScanFindings_ResultKey", + table: "ScanFindings", + column: "ResultKey"); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScanResults_RepositoryKey_Name_Version", + table: "ScanResults", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScanFindings"); + + migrationBuilder.DropTable( + name: "ScanPolicies"); + + migrationBuilder.DropTable( + name: "ScanResults"); + + migrationBuilder.DropColumn( + name: "Source", + table: "PackageVulnerabilities"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261023050022_AddRetentionUnusedSince.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261023050022_AddRetentionUnusedSince.Designer.cs new file mode 100644 index 000000000..712da3043 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261023050022_AddRetentionUnusedSince.Designer.cs @@ -0,0 +1,2173 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261023050022_AddRetentionUnusedSince")] + partial class AddRetentionUnusedSince + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.Property("UnusedSince") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261023050022_AddRetentionUnusedSince.cs b/src/BaGet.Database.PostgreSql/Migrations/20261023050022_AddRetentionUnusedSince.cs new file mode 100644 index 000000000..e6fcea8c3 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261023050022_AddRetentionUnusedSince.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddRetentionUnusedSince : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "UnusedSince", + table: "RetentionPolicies", + type: "timestamp with time zone", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "UnusedSince", + table: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261024001429_AddReplication.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261024001429_AddReplication.Designer.cs new file mode 100644 index 000000000..8d23ac5cf --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261024001429_AddReplication.Designer.cs @@ -0,0 +1,2354 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261024001429_AddReplication")] + partial class AddReplication + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Direction") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OnDeploy") + .HasColumnType("boolean"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("boolean"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleMinutes") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Synced") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Conflicts") + .HasColumnType("integer"); + + b.Property("Deleted") + .HasColumnType("integer"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Examined") + .HasColumnType("integer"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("Finished") + .HasColumnType("timestamp with time zone"); + + b.Property("ResumedFrom") + .HasColumnType("integer"); + + b.Property("Skipped") + .HasColumnType("integer"); + + b.Property("Started") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Transferred") + .HasColumnType("integer"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.Property("UnusedSince") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261024001429_AddReplication.cs b/src/BaGet.Database.PostgreSql/Migrations/20261024001429_AddReplication.cs new file mode 100644 index 000000000..91948ca1a --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261024001429_AddReplication.cs @@ -0,0 +1,124 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddReplication : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ReplicationConfigs", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + RepositoryKey = table.Column(type: "integer", nullable: false), + Direction = table.Column(type: "integer", nullable: false), + PeerUrl = table.Column(type: "character varying(2048)", maxLength: 2048, nullable: false), + PeerRepository = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + ProtectedApiKey = table.Column(type: "character varying(2048)", maxLength: 2048, nullable: true), + Enabled = table.Column(type: "boolean", nullable: false), + OnDeploy = table.Column(type: "boolean", nullable: false), + ScheduleMinutes = table.Column(type: "integer", nullable: true), + PropagateDeletes = table.Column(type: "boolean", nullable: false), + Conflict = table.Column(type: "integer", nullable: false), + ScheduleStart = table.Column(type: "timestamp with time zone", nullable: true), + LastRun = table.Column(type: "timestamp with time zone", nullable: true), + LastResult = table.Column(type: "character varying(1024)", maxLength: 1024, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Modified = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationConfigs", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ReplicationItems", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ConfigKey = table.Column(type: "integer", nullable: false), + Name = table.Column(type: "character varying(340)", maxLength: 340, nullable: false), + Version = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Part = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + Digest = table.Column(type: "character varying(160)", maxLength: 160, nullable: true), + Synced = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationItems", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ReplicationRuns", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ConfigKey = table.Column(type: "integer", nullable: false), + Status = table.Column(type: "integer", nullable: false), + Trigger = table.Column(type: "character varying(32)", maxLength: 32, nullable: true), + Actor = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + ResumedFrom = table.Column(type: "integer", nullable: true), + Started = table.Column(type: "timestamp with time zone", nullable: false), + Finished = table.Column(type: "timestamp with time zone", nullable: true), + Examined = table.Column(type: "integer", nullable: false), + Transferred = table.Column(type: "integer", nullable: false), + Skipped = table.Column(type: "integer", nullable: false), + Deleted = table.Column(type: "integer", nullable: false), + Conflicts = table.Column(type: "integer", nullable: false), + Failures = table.Column(type: "integer", nullable: false), + Bytes = table.Column(type: "bigint", nullable: false), + Error = table.Column(type: "character varying(1024)", maxLength: 1024, nullable: true), + Detail = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationRuns", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_Name", + table: "ReplicationConfigs", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationItems_ConfigKey_Name_Version_Part", + table: "ReplicationItems", + columns: new[] { "ConfigKey", "Name", "Version", "Part" }); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationRuns_ConfigKey_Started", + table: "ReplicationRuns", + columns: new[] { "ConfigKey", "Started" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ReplicationConfigs"); + + migrationBuilder.DropTable( + name: "ReplicationItems"); + + migrationBuilder.DropTable( + name: "ReplicationRuns"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261024014428_AddDataProtectionKeys.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261024014428_AddDataProtectionKeys.Designer.cs new file mode 100644 index 000000000..465662e02 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261024014428_AddDataProtectionKeys.Designer.cs @@ -0,0 +1,2374 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261024014428_AddDataProtectionKeys")] + partial class AddDataProtectionKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Direction") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OnDeploy") + .HasColumnType("boolean"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("boolean"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleMinutes") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Synced") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Conflicts") + .HasColumnType("integer"); + + b.Property("Deleted") + .HasColumnType("integer"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Examined") + .HasColumnType("integer"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("Finished") + .HasColumnType("timestamp with time zone"); + + b.Property("ResumedFrom") + .HasColumnType("integer"); + + b.Property("Skipped") + .HasColumnType("integer"); + + b.Property("Started") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Transferred") + .HasColumnType("integer"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.Property("UnusedSince") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261024014428_AddDataProtectionKeys.cs b/src/BaGet.Database.PostgreSql/Migrations/20261024014428_AddDataProtectionKeys.cs new file mode 100644 index 000000000..e7f8d9c3e --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261024014428_AddDataProtectionKeys.cs @@ -0,0 +1,36 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddDataProtectionKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "DataProtectionKeys", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + FriendlyName = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + Xml = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DataProtectionKeys", x => x.Key); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DataProtectionKeys"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261025012719_AddUserPendingApproval.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261025012719_AddUserPendingApproval.Designer.cs new file mode 100644 index 000000000..52567f41c --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261025012719_AddUserPendingApproval.Designer.cs @@ -0,0 +1,2377 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261025012719_AddUserPendingApproval")] + partial class AddUserPendingApproval + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PendingApproval") + .HasColumnType("boolean"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Direction") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OnDeploy") + .HasColumnType("boolean"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("boolean"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleMinutes") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Synced") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Conflicts") + .HasColumnType("integer"); + + b.Property("Deleted") + .HasColumnType("integer"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Examined") + .HasColumnType("integer"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("Finished") + .HasColumnType("timestamp with time zone"); + + b.Property("ResumedFrom") + .HasColumnType("integer"); + + b.Property("Skipped") + .HasColumnType("integer"); + + b.Property("Started") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Transferred") + .HasColumnType("integer"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.Property("UnusedSince") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261025012719_AddUserPendingApproval.cs b/src/BaGet.Database.PostgreSql/Migrations/20261025012719_AddUserPendingApproval.cs new file mode 100644 index 000000000..66d058fae --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261025012719_AddUserPendingApproval.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddUserPendingApproval : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PendingApproval", + table: "AspNetUsers", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PendingApproval", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261025035628_AddOwnershipForeignKeys.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261025035628_AddOwnershipForeignKeys.Designer.cs new file mode 100644 index 000000000..faab22d2e --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261025035628_AddOwnershipForeignKeys.Designer.cs @@ -0,0 +1,2597 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261025035628_AddOwnershipForeignKeys")] + partial class AddOwnershipForeignKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PendingApproval") + .HasColumnType("boolean"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Direction") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OnDeploy") + .HasColumnType("boolean"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("boolean"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleMinutes") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Synced") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Conflicts") + .HasColumnType("integer"); + + b.Property("Deleted") + .HasColumnType("integer"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Examined") + .HasColumnType("integer"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("Finished") + .HasColumnType("timestamp with time zone"); + + b.Property("ResumedFrom") + .HasColumnType("integer"); + + b.Property("Skipped") + .HasColumnType("integer"); + + b.Property("Started") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Transferred") + .HasColumnType("integer"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.Property("UnusedSince") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261025035628_AddOwnershipForeignKeys.cs b/src/BaGet.Database.PostgreSql/Migrations/20261025035628_AddOwnershipForeignKeys.cs new file mode 100644 index 000000000..48860eaa7 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261025035628_AddOwnershipForeignKeys.cs @@ -0,0 +1,367 @@ +using BaGet.Core; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddOwnershipForeignKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // Rows that pointed at nothing are removed first (children before parents), or the constraints below could not be created. + // On SQLite this runs before the table rebuilds that add the foreign keys. + foreach (var sql in OwnershipOrphanCleanup.Statements(OwnershipEngine.PostgreSql)) + { + migrationBuilder.Sql(sql); + } + + migrationBuilder.CreateIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey"); + + migrationBuilder.AddForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags", + column: "ImageKey", + principalTable: "OciRepositories", + principalColumn: "Key"); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages"); + + migrationBuilder.DropForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts"); + + migrationBuilder.DropForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages"); + + migrationBuilder.DropForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs"); + + migrationBuilder.DropForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns"); + + migrationBuilder.DropForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults"); + + migrationBuilder.DropIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261025222359_RenameAspNetTables.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261025222359_RenameAspNetTables.Designer.cs new file mode 100644 index 000000000..98023a5c6 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261025222359_RenameAspNetTables.Designer.cs @@ -0,0 +1,2597 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261025222359_RenameAspNetTables")] + partial class RenameAspNetTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("IsAdministrator") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PendingApproval") + .HasColumnType("boolean"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Direction") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OnDeploy") + .HasColumnType("boolean"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("boolean"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleMinutes") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Synced") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Conflicts") + .HasColumnType("integer"); + + b.Property("Deleted") + .HasColumnType("integer"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Examined") + .HasColumnType("integer"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("Finished") + .HasColumnType("timestamp with time zone"); + + b.Property("ResumedFrom") + .HasColumnType("integer"); + + b.Property("Skipped") + .HasColumnType("integer"); + + b.Property("Started") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Transferred") + .HasColumnType("integer"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.Property("UnusedSince") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261025222359_RenameAspNetTables.cs b/src/BaGet.Database.PostgreSql/Migrations/20261025222359_RenameAspNetTables.cs new file mode 100644 index 000000000..648ef2333 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261025222359_RenameAspNetTables.cs @@ -0,0 +1,456 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class RenameAspNetTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims"); + + migrationBuilder.RenameTable( + name: "AspNetUserTokens", + newName: "UserTokens"); + + migrationBuilder.RenameTable( + name: "AspNetUsers", + newName: "Users"); + + migrationBuilder.RenameTable( + name: "AspNetUserRoles", + newName: "UserRoles"); + + migrationBuilder.RenameTable( + name: "AspNetUserLogins", + newName: "UserLogins"); + + migrationBuilder.RenameTable( + name: "AspNetUserClaims", + newName: "UserClaims"); + + migrationBuilder.RenameTable( + name: "AspNetRoles", + newName: "Roles"); + + migrationBuilder.RenameTable( + name: "AspNetRoleClaims", + newName: "RoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "UserRoles", + newName: "IX_UserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserLogins_UserId", + table: "UserLogins", + newName: "IX_UserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserClaims_UserId", + table: "UserClaims", + newName: "IX_UserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "RoleClaims", + newName: "IX_RoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_Users", + table: "Users", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_Roles", + table: "Roles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Users", + table: "Users"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Roles", + table: "Roles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims"); + + migrationBuilder.RenameTable( + name: "UserTokens", + newName: "AspNetUserTokens"); + + migrationBuilder.RenameTable( + name: "Users", + newName: "AspNetUsers"); + + migrationBuilder.RenameTable( + name: "UserRoles", + newName: "AspNetUserRoles"); + + migrationBuilder.RenameTable( + name: "UserLogins", + newName: "AspNetUserLogins"); + + migrationBuilder.RenameTable( + name: "UserClaims", + newName: "AspNetUserClaims"); + + migrationBuilder.RenameTable( + name: "Roles", + newName: "AspNetRoles"); + + migrationBuilder.RenameTable( + name: "RoleClaims", + newName: "AspNetRoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_UserRoles_RoleId", + table: "AspNetUserRoles", + newName: "IX_AspNetUserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_UserLogins_UserId", + table: "AspNetUserLogins", + newName: "IX_AspNetUserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_UserClaims_UserId", + table: "AspNetUserClaims", + newName: "IX_AspNetUserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_RoleClaims_RoleId", + table: "AspNetRoleClaims", + newName: "IX_AspNetRoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs b/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs index 873f69770..dc3f40336 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs @@ -6,6 +6,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +#nullable disable + namespace BaGet.Database.PostgreSql.Migrations { [DbContext(typeof(PostgreSqlContext))] @@ -15,229 +17,2576 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("Npgsql:PostgresExtension:citext", ",,") - .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) - .HasAnnotation("ProductVersion", "3.1.18") + .HasAnnotation("ProductVersion", "10.0.13") .HasAnnotation("Relational:MaxIdentifierLength", 63); - modelBuilder.Entity("BaGet.Core.Package", b => + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => { b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("RepositoryKey") .ValueGeneratedOnAdd() .HasColumnType("integer") - .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + .HasDefaultValue(1); - b.Property("Authors") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); - b.Property("Description") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + b.HasKey("Key"); - b.Property("Downloads") - .HasColumnType("bigint"); + b.HasIndex("RepositoryKey", "PackageId"); - b.Property("HasEmbeddedIcon") - .HasColumnType("boolean"); + b.ToTable("AbuseReports"); + }); - b.Property("HasReadme") - .HasColumnType("boolean"); + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); - b.Property("IconUrl") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); - b.Property("Id") + b.Property("Action") .IsRequired() - .HasColumnType("citext") - .HasMaxLength(128); + .HasMaxLength(64) + .HasColumnType("character varying(64)"); - b.Property("IsPrerelease") - .HasColumnType("boolean"); + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); - b.Property("Language") - .HasColumnType("character varying(20)") - .HasMaxLength(20); + b.Property("Created") + .HasColumnType("timestamp with time zone"); - b.Property("LicenseUrl") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); - b.Property("Listed") - .HasColumnType("boolean"); + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); - b.Property("MinClientVersion") - .HasColumnType("character varying(44)") - .HasMaxLength(44); + b.HasKey("Key"); - b.Property("NormalizedVersionString") - .IsRequired() - .HasColumnName("Version") - .HasColumnType("citext") - .HasMaxLength(64); + b.HasIndex("Created"); - b.Property("OriginalVersionString") - .HasColumnName("OriginalVersion") - .HasColumnType("character varying(64)") - .HasMaxLength(64); + b.ToTable("AccessAuditEntries"); + }); - b.Property("ProjectUrl") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); - b.Property("Published") - .HasColumnType("timestamp without time zone"); + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); - b.Property("ReleaseNotes") - .HasColumnName("ReleaseNotes") - .HasColumnType("text"); + b.Property("Created") + .HasColumnType("timestamp with time zone"); - b.Property("RepositoryType") - .HasColumnType("character varying(100)") - .HasMaxLength(100); + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); - b.Property("RepositoryUrl") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + b.Property("Expires") + .HasColumnType("timestamp with time zone"); - b.Property("RequireLicenseAcceptance") - .HasColumnType("boolean"); + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); - b.Property("RowVersion") - .IsConcurrencyToken() - .ValueGeneratedOnAddOrUpdate() - .HasColumnType("bytea"); + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); - b.Property("SemVerLevel") + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() .HasColumnType("integer"); - b.Property("Summary") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); - b.Property("Tags") - .HasColumnType("character varying(4000)") - .HasMaxLength(4000); + b.Property("ApiKeyKey") + .HasColumnType("integer"); - b.Property("Title") - .HasColumnType("character varying(256)") - .HasMaxLength(256); + b.Property("RepositoryKey") + .HasColumnType("integer"); b.HasKey("Key"); - b.HasIndex("Id"); + b.HasIndex("RepositoryKey"); - b.HasIndex("Id", "NormalizedVersionString") + b.HasIndex("ApiKeyKey", "RepositoryKey") .IsUnique(); - b.ToTable("Packages"); + b.ToTable("ApiKeyRepositories"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => { b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("RepositoryKey") .ValueGeneratedOnAdd() .HasColumnType("integer") - .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + .HasDefaultValue(1); + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { b.Property("Id") - .HasColumnType("citext") - .HasMaxLength(128); + .HasColumnType("text"); - b.Property("PackageKey") + b.Property("AccessFailedCount") .HasColumnType("integer"); - b.Property("TargetFramework") - .HasColumnType("character varying(256)") - .HasMaxLength(256); + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); - b.Property("VersionRange") - .HasColumnType("character varying(256)") - .HasMaxLength(256); + b.Property("Created") + .HasColumnType("timestamp with time zone"); - b.HasKey("Key"); + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); - b.HasIndex("Id"); + b.Property("EmailConfirmed") + .HasColumnType("boolean"); - b.HasIndex("PackageKey"); + b.Property("IsAdministrator") + .HasColumnType("boolean"); - b.ToTable("PackageDependencies"); + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PendingApproval") + .HasColumnType("boolean"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("Users", (string)null); }); - modelBuilder.Entity("BaGet.Core.PackageType", b => + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => { b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") .ValueGeneratedOnAdd() .HasColumnType("integer") - .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + .HasDefaultValue(1); - b.Property("Name") - .HasColumnType("citext") - .HasMaxLength(512); + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); - b.Property("PackageKey") + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() .HasColumnType("integer"); - b.Property("Version") - .HasColumnType("character varying(64)") - .HasMaxLength(64); + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Xml") + .HasColumnType("text"); b.HasKey("Key"); - b.HasIndex("Name"); + b.ToTable("DataProtectionKeys"); + }); - b.HasIndex("PackageKey"); + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); - b.ToTable("PackageTypes"); + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.GroupMember", b => { b.Property("Key") .ValueGeneratedOnAdd() - .HasColumnType("integer") - .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + .HasColumnType("integer"); - b.Property("Moniker") - .HasColumnType("citext") - .HasMaxLength(256); + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); - b.Property("PackageKey") + b.Property("GroupKey") .HasColumnType("integer"); + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + b.HasKey("Key"); - b.HasIndex("Moniker"); + b.HasIndex("UserId"); - b.HasIndex("PackageKey"); + b.HasIndex("GroupKey", "UserId") + .IsUnique(); - b.ToTable("TargetFrameworks"); + b.ToTable("GroupMembers"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("Dependencies") - .HasForeignKey("PackageKey"); - }); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); - modelBuilder.Entity("BaGet.Core.PackageType", b => - { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("PackageTypes") - .HasForeignKey("PackageKey") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.MavenFile", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("TargetFrameworks") - .HasForeignKey("PackageKey") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("integer"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("character varying(15)"); + + b.Property("VersionKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("character varying(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("text"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("text"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("RefCount") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Manifests") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("character varying(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("ManifestKey") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ImageKey") + .HasColumnType("integer"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("integer"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Direction") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OnDeploy") + .HasColumnType("boolean"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("boolean"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleMinutes") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Synced") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("integer"); + + b.Property("Conflicts") + .HasColumnType("integer"); + + b.Property("Deleted") + .HasColumnType("integer"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Examined") + .HasColumnType("integer"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("Finished") + .HasColumnType("timestamp with time zone"); + + b.Property("ResumedFrom") + .HasColumnType("integer"); + + b.Property("Skipped") + .HasColumnType("integer"); + + b.Property("Started") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Transferred") + .HasColumnType("integer"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("Settings") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("character varying(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("boolean"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("KeepLast") + .HasColumnType("integer"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("LastRun") + .HasColumnType("timestamp with time zone"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("integer"); + + b.Property("PrereleaseOnly") + .HasColumnType("boolean"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("ScheduleHours") + .HasColumnType("integer"); + + b.Property("ScheduleStart") + .HasColumnType("timestamp with time zone"); + + b.Property("UntaggedAfterDays") + .HasColumnType("integer"); + + b.Property("UnusedDays") + .HasColumnType("integer"); + + b.Property("UnusedSince") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ResultKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("integer"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("integer"); + + b.Property("BlockUnscanned") + .HasColumnType("boolean"); + + b.Property("Modified") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectKey") + .HasColumnType("integer"); + + b.Property("RepositoryKey") + .HasColumnType("integer"); + + b.Property("WarnSeverity") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FindingCount") + .HasColumnType("integer"); + + b.Property("Highest") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); }); #pragma warning restore 612, 618 } diff --git a/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs b/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs index 9268d3af6..52a21f925 100644 --- a/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs +++ b/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs @@ -1,33 +1,38 @@ using System; using BaGet.Core; using BaGet.Database.PostgreSql; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class PostgreSqlApplicationExtensions { - public static class PostgreSqlApplicationExtensions + public static BaGetApplication AddPostgreSqlDatabase(this BaGetApplication app) { - public static BaGetApplication AddPostgreSqlDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("PostgreSql", (provider, options) => { - app.Services.AddBaGetDbContextProvider("PostgreSql", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - options.UseNpgsql(databaseOptions.Value.ConnectionString); - }); + PostgreSqlDatabaseContextFactory.Configure( + options, + databaseOptions.Value.ConnectionString, + databaseOptions.Value.MySqlServerVersion); + }); - return app; - } + app.Services.TryAddEnumerable( + ServiceDescriptor.Singleton()); - public static BaGetApplication AddPostgreSqlDatabase( - this BaGetApplication app, - Action configure) - { - app.AddPostgreSqlDatabase(); - app.Services.Configure(configure); - return app; - } + return app; + } + + public static BaGetApplication AddPostgreSqlDatabase( + this BaGetApplication app, + Action configure) + { + app.AddPostgreSqlDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs b/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs index c008e6cce..2e0c59740 100644 --- a/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs +++ b/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs @@ -1,72 +1,133 @@ +using System.Linq; using System.Threading; using System.Threading.Tasks; using BaGet.Core; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; using Npgsql; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; -namespace BaGet.Database.PostgreSql +namespace BaGet.Database.PostgreSql; + +public class PostgreSqlContext : AbstractContext { - public class PostgreSqlContext : AbstractContext + /// + /// The PostgreSql error code for when a unique constraint is violated. + /// See: https://www.postgresql.org/docs/9.6/errcodes-appendix.html + /// + private const int UniqueConstraintViolationErrorCode = 23505; + + public PostgreSqlContext(DbContextOptions options) + : base(options) { - /// - /// The PostgreSql error code for when a unique constraint is violated. - /// See: https://www.postgresql.org/docs/9.6/errcodes-appendix.html - /// - private const int UniqueConstraintViolationErrorCode = 23505; - - public PostgreSqlContext(DbContextOptions options) - : base(options) - { - } + } - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - return exception.InnerException is PostgresException postgresException && - int.TryParse(postgresException.SqlState, out var code) && - code == UniqueConstraintViolationErrorCode; - } + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) + { + return exception.InnerException is PostgresException postgresException && + int.TryParse(postgresException.SqlState, out var code) && + code == UniqueConstraintViolationErrorCode; + } + + public override async Task RunMigrationsAsync(CancellationToken cancellationToken) + { + await base.RunMigrationsAsync(cancellationToken); - public override async Task RunMigrationsAsync(CancellationToken cancellationToken) + // Npgsql caches the database's type information on the initial connection. + // This causes issues when BaGet creates the database as it may add the citext + // extension to support case insensitive columns. + // See: https://github.com/loic-sharma/BaGet/issues/442 + // See: https://github.com/npgsql/efcore.pg/issues/170#issuecomment-303417225 + if (Database.GetDbConnection() is NpgsqlConnection connection) { - await base.RunMigrationsAsync(cancellationToken); - - // Npgsql caches the database's type information on the initial connection. - // This causes issues when BaGet creates the database as it may add the citext - // extension to support case insensitive columns. - // See: https://github.com/loic-sharma/BaGet/issues/442 - // See: https://github.com/npgsql/efcore.pg/issues/170#issuecomment-303417225 - if (Database.GetDbConnection() is NpgsqlConnection connection) + // Migrations may run more than once on one context (a data copy checks the target, then migrates + // it), and the first run can leave the connection open: open it only when it is closed. + if (connection.State != System.Data.ConnectionState.Open) { await connection.OpenAsync(cancellationToken); - connection.ReloadTypes(); } + + connection.ReloadTypes(); } + } - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); - builder.HasPostgresExtension("citext"); + builder.HasPostgresExtension("citext"); - builder.Entity() - .Property(p => p.Id) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.Id) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.NormalizedVersionString) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.NormalizedVersionString) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.Id) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.Id) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.Name) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.Name) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.Moniker) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.Moniker) + .HasColumnType("citext"); + } + + /// + /// Moves each serial/identity sequence of the table past the highest key that was inserted explicitly. + /// + /// + /// Explicit keys do not advance a PostgreSQL sequence, so without this the next generated key would + /// collide with a copied row. Tables with no serial/identity key (such as Identity's string-keyed + /// ones) are left alone. + /// + public override async Task EndKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken) + { + foreach (var sql in BuildSetValSql(table)) + { + await Database.ExecuteSqlRawAsync(sql, cancellationToken); } } -} + + /// + /// The setval statements for the table's serial/identity columns; empty when it has none. + /// An empty table leaves the sequence at its start (is_called false), otherwise the next value is MAX + 1. + /// + internal static string[] BuildSetValSql(IEntityType table) + { + var name = table.GetTableName(); + if (name == null) + { + return System.Array.Empty(); + } + + var schema = table.GetSchema(); + var store = StoreObjectIdentifier.Table(name, schema); + var qualified = schema == null ? Quote(name) : $"{Quote(schema)}.{Quote(name)}"; + + return table.GetProperties() + .Where(p => p.GetValueGenerationStrategy(store) is + NpgsqlValueGenerationStrategy.SerialColumn or + NpgsqlValueGenerationStrategy.IdentityByDefaultColumn or + NpgsqlValueGenerationStrategy.IdentityAlwaysColumn) + .Select(p => + { + var column = p.GetColumnName(store)!; + + // pg_get_serial_sequence parses its table argument as an identifier (so it is quoted + // inside the literal) but takes the column name verbatim. + return $"SELECT setval(pg_get_serial_sequence('{Literal(qualified)}', '{Literal(column)}'), " + + $"COALESCE(MAX({Quote(column)}), 1), MAX({Quote(column)}) IS NOT NULL) FROM {qualified}"; + }) + .ToArray(); + } + + private static string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\""; + + private static string Literal(string text) => text.Replace("'", "''"); +} \ No newline at end of file diff --git a/src/BaGet.Database.PostgreSql/PostgreSqlContextFactory.cs b/src/BaGet.Database.PostgreSql/PostgreSqlContextFactory.cs new file mode 100644 index 000000000..63d4c2341 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/PostgreSqlContextFactory.cs @@ -0,0 +1,25 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace BaGet.Database.PostgreSql; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class PostgreSqlContextFactory : IDesignTimeDbContextFactory +{ + public PostgreSqlContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseNpgsql("Host=localhost;Database=baget;Username=baget") + .Options; + + return new PostgreSqlContext(options); + } +} \ No newline at end of file diff --git a/src/BaGet.Database.PostgreSql/PostgreSqlDatabaseContextFactory.cs b/src/BaGet.Database.PostgreSql/PostgreSqlDatabaseContextFactory.cs new file mode 100644 index 000000000..e830d38c2 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/PostgreSqlDatabaseContextFactory.cs @@ -0,0 +1,37 @@ +using System; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Database.PostgreSql; + +/// +/// Opens a on any PostgreSql connection string; see . +/// +public class PostgreSqlDatabaseContextFactory : IDatabaseContextFactory +{ + /// + public string DatabaseType => "PostgreSql"; + + /// + public IContext Create( + string connectionString, + DatabaseOptions? options = null, + Action? configure = null) + { + var builder = new DbContextOptionsBuilder(); + + Configure(builder, connectionString, options?.MySqlServerVersion); + configure?.Invoke(builder); + + return new PostgreSqlContext(builder.Options); + } + + /// + /// The one place the provider is configured: used by both this factory and the application's + /// registration, so a second database is configured exactly like the main one. + /// + internal static void Configure(DbContextOptionsBuilder options, string? connectionString, string? mySqlServerVersion) + { + options.UseNpgsql(connectionString); + } +} diff --git a/src/BaGet.Database.PostgreSql/README.md b/src/BaGet.Database.PostgreSql/README.md new file mode 100644 index 000000000..d1b9b4ffc --- /dev/null +++ b/src/BaGet.Database.PostgreSql/README.md @@ -0,0 +1,44 @@ +# Extension.BaGet.Database.PostgreSql + +The PostgreSQL database provider of [BaGet Extension](https://pieroviano.github.io/BaGet/), built on `Npgsql.EntityFrameworkCore.PostgreSQL`. + +```powershell +dotnet add package Extension.BaGet.Database.PostgreSql +``` + +## Usage + +Register it in the `BaGetApplication` callback; it activates when `Database:Type` is `PostgreSql`: + +```csharp +services.AddBaGetWebApplication(app => app.AddPostgreSqlDatabase()); +``` + +| Setting | Value | +|---|---| +| `Database:Type` | `PostgreSql` | +| `Database:ConnectionString` | e.g. `Host=localhost;Database=baget;Username=baget;Password=...` | + +`AddPostgreSqlDatabase` also registers `PostgreSqlDatabaseContextFactory` (`IDatabaseContextFactory`), which opens a `PostgreSqlContext` on any connection string for the Settings page's database copy. PostgreSQL `End` `setval`s the serial/identity sequence past the highest key. + +## Migrations (contributors) + +The project has its own design-time context factory, so `dotnet ef` needs no startup project and no +running database. The tool version is pinned by `.config/dotnet-tools.json`; run `dotnet tool restore` once. + +From this folder: + +``` +dotnet ef migrations add MigrationName --context PostgreSqlContext --output-dir Migrations +dotnet ef migrations has-pending-model-changes --context PostgreSqlContext +``` + +A model change needs a migration in **all four** `BaGet.Database.*` projects, and each must then report +no pending model changes. Keep schema changes additive (new tables, nullable foreign keys): SQLite cannot +alter a foreign key in place. + +BaGet applies pending migrations itself when it starts. + +- List migrations without a server: `dotnet ef migrations list --context PostgreSqlContext`. +- Never run `dotnet ef migrations remove --no-build`: with a stale assembly it deleted the previous migration. Delete the generated files by hand and restore the model snapshot from `HEAD`. +- Entity Framework is 10.0.13; the MySQL provider is `Microting.EntityFrameworkCore.MySql`; all four providers move together. diff --git a/src/BaGet.Database.PostgreSql/readme.md b/src/BaGet.Database.PostgreSql/readme.md deleted file mode 100644 index 7d6bf1b10..000000000 --- a/src/BaGet.Database.PostgreSql/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -# BaGet's PostgreSql Database Provider - -This project contains BaGet's PostgreSql database provider. - -## Migrations - -Add a migration with: - -``` -dotnet ef migrations add MigrationName --context PostgreSqlContext --output-dir Migrations --startup-project ..\BaGet\BaGet.csproj - -dotnet ef database update --context PostgreSqlContext -``` diff --git a/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj b/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj index c6720e41b..8b2aef195 100644 --- a/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj +++ b/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj @@ -1,18 +1,30 @@ - netstandard2.0 - + net10.0 + latest NuGet - The libraries to host BaGet on SQL Server. + The libraries to host BaGet Extension on SQL Server. + enable + + + + + + + + + + + diff --git a/src/BaGet.Database.SqlServer/Migrations/20180804082816_Initial.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20180804082816_Initial.Designer.cs index 2b9028536..bfdf0e468 100644 --- a/src/BaGet.Database.SqlServer/Migrations/20180804082816_Initial.Designer.cs +++ b/src/BaGet.Database.SqlServer/Migrations/20180804082816_Initial.Designer.cs @@ -1,3 +1,4 @@ +#nullable disable // using System; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.SqlServer/Migrations/20190303071621_AddSearchDimensions.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20190303071621_AddSearchDimensions.Designer.cs index 153c78e3b..b0a5f8005 100644 --- a/src/BaGet.Database.SqlServer/Migrations/20190303071621_AddSearchDimensions.Designer.cs +++ b/src/BaGet.Database.SqlServer/Migrations/20190303071621_AddSearchDimensions.Designer.cs @@ -1,3 +1,4 @@ +#nullable disable // using System; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.SqlServer/Migrations/20190914215959_AddOriginalVersionStringColumn.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20190914215959_AddOriginalVersionStringColumn.Designer.cs index 9838c279f..1a52c0f9e 100644 --- a/src/BaGet.Database.SqlServer/Migrations/20190914215959_AddOriginalVersionStringColumn.Designer.cs +++ b/src/BaGet.Database.SqlServer/Migrations/20190914215959_AddOriginalVersionStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.SqlServer; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.SqlServer/Migrations/20200109085508_AddReleaseNotesStringColumn.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20200109085508_AddReleaseNotesStringColumn.Designer.cs index acf227e70..294117e47 100644 --- a/src/BaGet.Database.SqlServer/Migrations/20200109085508_AddReleaseNotesStringColumn.Designer.cs +++ b/src/BaGet.Database.SqlServer/Migrations/20200109085508_AddReleaseNotesStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.SqlServer; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.SqlServer/Migrations/20200210004408_AddHasEmbeddedIconColumn.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20200210004408_AddHasEmbeddedIconColumn.Designer.cs index 2bdbefa7a..2982235ad 100644 --- a/src/BaGet.Database.SqlServer/Migrations/20200210004408_AddHasEmbeddedIconColumn.Designer.cs +++ b/src/BaGet.Database.SqlServer/Migrations/20200210004408_AddHasEmbeddedIconColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.SqlServer; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.SqlServer/Migrations/20210919191928_RemoveReleaseNotesMaxLength.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20210919191928_RemoveReleaseNotesMaxLength.Designer.cs index 7db50ee59..996ab0306 100644 --- a/src/BaGet.Database.SqlServer/Migrations/20210919191928_RemoveReleaseNotesMaxLength.Designer.cs +++ b/src/BaGet.Database.SqlServer/Migrations/20210919191928_RemoveReleaseNotesMaxLength.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.SqlServer; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.SqlServer/Migrations/20261016053011_AddDeprecationAndVulnerability.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261016053011_AddDeprecationAndVulnerability.Designer.cs new file mode 100644 index 000000000..2c3e11884 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261016053011_AddDeprecationAndVulnerability.Designer.cs @@ -0,0 +1,356 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261016053011_AddDeprecationAndVulnerability")] + partial class AddDeprecationAndVulnerability + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261016053011_AddDeprecationAndVulnerability.cs b/src/BaGet.Database.SqlServer/Migrations/20261016053011_AddDeprecationAndVulnerability.cs new file mode 100644 index 000000000..1a92c6d40 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261016053011_AddDeprecationAndVulnerability.cs @@ -0,0 +1,79 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddDeprecationAndVulnerability : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageDeprecations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Reasons = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + Message = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + AlternatePackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: true), + AlternateVersionRange = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + PackageKey = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageDeprecations", x => x.Key); + table.ForeignKey( + name: "FK_PackageDeprecations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateTable( + name: "PackageVulnerabilities", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + AdvisoryUrl = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + Severity = table.Column(type: "int", nullable: false), + VersionRange = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + PackageKey = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageVulnerabilities", x => x.Key); + table.ForeignKey( + name: "FK_PackageVulnerabilities_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageDeprecations_PackageKey", + table: "PackageDeprecations", + column: "PackageKey", + unique: true, + filter: "[PackageKey] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_PackageVulnerabilities_PackageKey", + table: "PackageVulnerabilities", + column: "PackageKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageDeprecations"); + + migrationBuilder.DropTable( + name: "PackageVulnerabilities"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017011642_AddCatalog.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261017011642_AddCatalog.Designer.cs new file mode 100644 index 000000000..825d5618f --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017011642_AddCatalog.Designer.cs @@ -0,0 +1,395 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261017011642_AddCatalog")] + partial class AddCatalog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017011642_AddCatalog.cs b/src/BaGet.Database.SqlServer/Migrations/20261017011642_AddCatalog.cs new file mode 100644 index 000000000..88a9f9e35 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017011642_AddCatalog.cs @@ -0,0 +1,45 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddCatalog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "CatalogLeafs", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + CommitId = table.Column(type: "nvarchar(36)", maxLength: 36, nullable: false), + CommitTimestamp = table.Column(type: "datetime2", nullable: false), + Type = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + PackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_CatalogLeafs", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_CommitId", + table: "CatalogLeafs", + column: "CommitId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "CatalogLeafs"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017012804_AddAccounts.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261017012804_AddAccounts.Designer.cs new file mode 100644 index 000000000..40ed4024b --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017012804_AddAccounts.Designer.cs @@ -0,0 +1,784 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261017012804_AddAccounts")] + partial class AddAccounts + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017012804_AddAccounts.cs b/src/BaGet.Database.SqlServer/Migrations/20261017012804_AddAccounts.cs new file mode 100644 index 000000000..bbc0bbc65 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017012804_AddAccounts.cs @@ -0,0 +1,342 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddAccounts : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeys", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "nvarchar(450)", maxLength: 450, nullable: false), + Description = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + HashedKey = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Scopes = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + PackageGlobPattern = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Expires = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeys", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoles", + columns: table => new + { + Id = table.Column(type: "nvarchar(450)", nullable: false), + Name = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + NormalizedName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetUsers", + columns: table => new + { + Id = table.Column(type: "nvarchar(450)", nullable: false), + Created = table.Column(type: "datetime2", nullable: false), + UserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Email = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "bit", nullable: false), + PasswordHash = table.Column(type: "nvarchar(max)", nullable: true), + SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true), + ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), + PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true), + PhoneNumberConfirmed = table.Column(type: "bit", nullable: false), + TwoFactorEnabled = table.Column(type: "bit", nullable: false), + LockoutEnd = table.Column(type: "datetimeoffset", nullable: true), + LockoutEnabled = table.Column(type: "bit", nullable: false), + AccessFailedCount = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Organizations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Organizations", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "PackageOwners", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + OwnerName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false), + IsVerified = table.Column(type: "bit", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageOwners", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RoleId = table.Column(type: "nvarchar(450)", nullable: false), + ClaimType = table.Column(type: "nvarchar(max)", nullable: true), + ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserClaims", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "nvarchar(450)", nullable: false), + ClaimType = table.Column(type: "nvarchar(max)", nullable: true), + ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserLogins", + columns: table => new + { + LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), + ProviderKey = table.Column(type: "nvarchar(450)", nullable: false), + ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true), + UserId = table.Column(type: "nvarchar(450)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserRoles", + columns: table => new + { + UserId = table.Column(type: "nvarchar(450)", nullable: false), + RoleId = table.Column(type: "nvarchar(450)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserTokens", + columns: table => new + { + UserId = table.Column(type: "nvarchar(450)", nullable: false), + LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), + Name = table.Column(type: "nvarchar(450)", nullable: false), + Value = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OrganizationMembers", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + OrganizationKey = table.Column(type: "int", nullable: true), + UserId = table.Column(type: "nvarchar(450)", maxLength: 450, nullable: false), + IsAdmin = table.Column(type: "bit", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OrganizationMembers", x => x.Key); + table.ForeignKey( + name: "FK_OrganizationMembers_Organizations_OrganizationKey", + column: x => x.OrganizationKey, + principalTable: "Organizations", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_HashedKey", + table: "ApiKeys", + column: "HashedKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_UserId", + table: "ApiKeys", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "AspNetRoleClaims", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "AspNetRoles", + column: "NormalizedName", + unique: true, + filter: "[NormalizedName] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserClaims_UserId", + table: "AspNetUserClaims", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserLogins_UserId", + table: "AspNetUserLogins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "AspNetUsers", + column: "NormalizedEmail"); + + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "AspNetUsers", + column: "NormalizedUserName", + unique: true, + filter: "[NormalizedUserName] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_OrganizationKey", + table: "OrganizationMembers", + column: "OrganizationKey"); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_UserId", + table: "OrganizationMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Organizations_Name", + table: "Organizations", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_OwnerName", + table: "PackageOwners", + column: "OwnerName"); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeys"); + + migrationBuilder.DropTable( + name: "AspNetRoleClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserLogins"); + + migrationBuilder.DropTable( + name: "AspNetUserRoles"); + + migrationBuilder.DropTable( + name: "AspNetUserTokens"); + + migrationBuilder.DropTable( + name: "OrganizationMembers"); + + migrationBuilder.DropTable( + name: "PackageOwners"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + + migrationBuilder.DropTable( + name: "Organizations"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..94ab371c3 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.Designer.cs @@ -0,0 +1,848 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261017014346_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.cs b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.cs new file mode 100644 index 000000000..0d7037462 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.cs @@ -0,0 +1,63 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + SubmissionId = table.Column(type: "nvarchar(36)", maxLength: 36, nullable: false), + PackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + PackageKey = table.Column(type: "int", nullable: true), + Type = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + State = table.Column(type: "int", nullable: false), + Message = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Completed = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..1f747cf94 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.Designer.cs @@ -0,0 +1,893 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261017020116_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.cs b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.cs new file mode 100644 index 000000000..511caca4d --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Reason = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Details = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: false), + ReporterEmail = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Resolved = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261018043331_AddAdministrators.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261018043331_AddAdministrators.Designer.cs new file mode 100644 index 000000000..a57a60f73 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261018043331_AddAdministrators.Designer.cs @@ -0,0 +1,896 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261018043331_AddAdministrators")] + partial class AddAdministrators + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261018043331_AddAdministrators.cs b/src/BaGet.Database.SqlServer/Migrations/20261018043331_AddAdministrators.cs new file mode 100644 index 000000000..3a9b48f9f --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261018043331_AddAdministrators.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddAdministrators : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsAdministrator", + table: "AspNetUsers", + type: "bit", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsAdministrator", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261020071956_AddRepositories.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261020071956_AddRepositories.Designer.cs new file mode 100644 index 000000000..34c4db0a4 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261020071956_AddRepositories.Designer.cs @@ -0,0 +1,994 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261020071956_AddRepositories")] + partial class AddRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261020071956_AddRepositories.cs b/src/BaGet.Database.SqlServer/Migrations/20261020071956_AddRepositories.cs new file mode 100644 index 000000000..5a6fcbd36 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261020071956_AddRepositories.cs @@ -0,0 +1,217 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports"); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageValidations", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "Packages", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageOwners", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "CatalogLeafs", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "AbuseReports", + type: "int", + nullable: false, + defaultValue: 1); + + migrationBuilder.CreateTable( + name: "Projects", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + DisplayName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Projects", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "Repositories", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Format = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + Kind = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + ProjectKey = table.Column(type: "int", nullable: true), + Settings = table.Column(type: "nvarchar(max)", nullable: true), + AnonymousRead = table.Column(type: "bit", nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Repositories", x => x.Key); + }); + + // The default repository (key 1 = RepositoryKey's column default, so every existing row already belongs to + // it). Created here, not only by startup, so that applying migrations without RunMigrationsAtStartup + // (dotnet ef database update, an SQL script) cannot leave a new repository to take key 1. + migrationBuilder.InsertData( + table: "Repositories", + columns: new[] { "Key", "Name", "Format", "Kind", "AnonymousRead", "Created" }, + values: new object[] { 1, "default", "NuGet", "Local", true, DateTime.UtcNow }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages", + columns: new[] { "RepositoryKey", "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Projects_Name", + table: "Projects", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Repositories_Name", + table: "Repositories", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Projects"); + + migrationBuilder.DropTable( + name: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "Packages"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_Packages_Id_Version", + table: "Packages", + columns: new[] { "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021035306_AddPackageSymbols.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261021035306_AddPackageSymbols.Designer.cs new file mode 100644 index 000000000..89cf51da5 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021035306_AddPackageSymbols.Designer.cs @@ -0,0 +1,1039 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261021035306_AddPackageSymbols")] + partial class AddPackageSymbols + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021035306_AddPackageSymbols.cs b/src/BaGet.Database.SqlServer/Migrations/20261021035306_AddPackageSymbols.cs new file mode 100644 index 000000000..0387cd104 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021035306_AddPackageSymbols.cs @@ -0,0 +1,50 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddPackageSymbols : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageSymbols", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + PackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + FileName = table.Column(type: "nvarchar(255)", maxLength: 255, nullable: false), + SymbolKey = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageSymbols", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_FileName_SymbolKey", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "FileName", "SymbolKey" }); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_PackageId_PackageVersion", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "PackageId", "PackageVersion" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageSymbols"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021040421_AddAccessControl.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261021040421_AddAccessControl.Designer.cs new file mode 100644 index 000000000..24ec6e114 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021040421_AddAccessControl.Designer.cs @@ -0,0 +1,1227 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261021040421_AddAccessControl")] + partial class AddAccessControl + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021040421_AddAccessControl.cs b/src/BaGet.Database.SqlServer/Migrations/20261021040421_AddAccessControl.cs new file mode 100644 index 000000000..c9eb8a89f --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021040421_AddAccessControl.cs @@ -0,0 +1,226 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddAccessControl : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AccessAuditEntries", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Created = table.Column(type: "datetime2", nullable: false), + Actor = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Action = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Subject = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Details = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AccessAuditEntries", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "Groups", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Description = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + IsBuiltIn = table.Column(type: "bit", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Groups", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "PermissionTargets", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + RepositoryPatterns = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + IncludePatterns = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + ExcludePatterns = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + ProjectKey = table.Column(type: "int", nullable: true), + IsBuiltIn = table.Column(type: "bit", nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionTargets", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ProjectMembers", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ProjectKey = table.Column(type: "int", nullable: false), + PrincipalType = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + PrincipalId = table.Column(type: "nvarchar(450)", maxLength: 450, nullable: false), + Role = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ProjectMembers", x => x.Key); + table.ForeignKey( + name: "FK_ProjectMembers_Projects_ProjectKey", + column: x => x.ProjectKey, + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "GroupMembers", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + GroupKey = table.Column(type: "int", nullable: false), + UserId = table.Column(type: "nvarchar(450)", maxLength: 450, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_GroupMembers", x => x.Key); + table.ForeignKey( + name: "FK_GroupMembers_Groups_GroupKey", + column: x => x.GroupKey, + principalTable: "Groups", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PermissionGrants", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + TargetKey = table.Column(type: "int", nullable: false), + PrincipalType = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + PrincipalId = table.Column(type: "nvarchar(450)", maxLength: 450, nullable: false), + Actions = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionGrants", x => x.Key); + table.ForeignKey( + name: "FK_PermissionGrants_PermissionTargets_TargetKey", + column: x => x.TargetKey, + principalTable: "PermissionTargets", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + // The upgrade defaults: what the server did before the access model existed. Everyone reads every + // repository; every authenticated caller deploys, annotates, deletes and manages (package ownership is + // still applied inside those actions). Explicit keys, so the grants below can name them. + var seeded = DateTime.UtcNow; + + migrationBuilder.InsertData( + table: "Groups", + columns: new[] { "Key", "Name", "Description", "Created", "IsBuiltIn" }, + values: new object[,] + { + { 1, "Everyone", "Every caller, anonymous ones included.", seeded, true }, + { 2, "Authenticated", "Every caller that presented valid credentials.", seeded, true }, + }); + + migrationBuilder.InsertData( + table: "PermissionTargets", + columns: new[] { "Key", "Name", "RepositoryPatterns", "IncludePatterns", "ExcludePatterns", "IsBuiltIn", "Created" }, + values: new object[,] + { + { 1, "Anyone reads every repository", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + { 2, "Authenticated users deploy", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + }); + + // Actions: Read = 1; Annotate | Deploy | Delete | Manage = 2 + 4 + 8 + 16 = 30. + migrationBuilder.InsertData( + table: "PermissionGrants", + columns: new[] { "Key", "TargetKey", "PrincipalType", "PrincipalId", "Actions" }, + values: new object[,] + { + { 1, 1, "Group", "1", 1 }, + { 2, 2, "Group", "2", 30 }, + }); + + migrationBuilder.CreateIndex( + name: "IX_AccessAuditEntries_Created", + table: "AccessAuditEntries", + column: "Created"); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_GroupKey_UserId", + table: "GroupMembers", + columns: new[] { "GroupKey", "UserId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_UserId", + table: "GroupMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Groups_Name", + table: "Groups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionGrants_TargetKey_PrincipalType_PrincipalId", + table: "PermissionGrants", + columns: new[] { "TargetKey", "PrincipalType", "PrincipalId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_Name", + table: "PermissionTargets", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ProjectMembers_ProjectKey_PrincipalType_PrincipalId", + table: "ProjectMembers", + columns: new[] { "ProjectKey", "PrincipalType", "PrincipalId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AccessAuditEntries"); + + migrationBuilder.DropTable( + name: "GroupMembers"); + + migrationBuilder.DropTable( + name: "PermissionGrants"); + + migrationBuilder.DropTable( + name: "ProjectMembers"); + + migrationBuilder.DropTable( + name: "Groups"); + + migrationBuilder.DropTable( + name: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021055034_AddApiKeyRepositories.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261021055034_AddApiKeyRepositories.Designer.cs new file mode 100644 index 000000000..d4ac27244 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021055034_AddApiKeyRepositories.Designer.cs @@ -0,0 +1,1307 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261021055034_AddApiKeyRepositories")] + partial class AddApiKeyRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021055034_AddApiKeyRepositories.cs b/src/BaGet.Database.SqlServer/Migrations/20261021055034_AddApiKeyRepositories.cs new file mode 100644 index 000000000..052e5075d --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021055034_AddApiKeyRepositories.cs @@ -0,0 +1,52 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddApiKeyRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeyRepositories", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ApiKeyKey = table.Column(type: "int", nullable: false), + RepositoryKey = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeyRepositories", x => x.Key); + table.ForeignKey( + name: "FK_ApiKeyRepositories_ApiKeys_ApiKeyKey", + column: x => x.ApiKeyKey, + principalTable: "ApiKeys", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_ApiKeyKey_RepositoryKey", + table: "ApiKeyRepositories", + columns: new[] { "ApiKeyKey", "RepositoryKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeyRepositories"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021155629_AddNpmTables.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261021155629_AddNpmTables.Designer.cs new file mode 100644 index 000000000..bc2f89fad --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021155629_AddNpmTables.Designer.cs @@ -0,0 +1,1433 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261021155629_AddNpmTables")] + partial class AddNpmTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021155629_AddNpmTables.cs b/src/BaGet.Database.SqlServer/Migrations/20261021155629_AddNpmTables.cs new file mode 100644 index 000000000..236637428 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021155629_AddNpmTables.cs @@ -0,0 +1,109 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddNpmTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "NpmPackages", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "nvarchar(214)", maxLength: 214, nullable: false), + Created = table.Column(type: "datetime2", nullable: false), + Modified = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmPackages", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "NpmDistTags", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PackageKey = table.Column(type: "int", nullable: false), + Tag = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Version = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmDistTags", x => x.Key); + table.ForeignKey( + name: "FK_NpmDistTags_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "NpmVersions", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PackageKey = table.Column(type: "int", nullable: false), + Version = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false), + Integrity = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false), + Shasum = table.Column(type: "nvarchar(40)", maxLength: 40, nullable: false), + TarballSize = table.Column(type: "bigint", nullable: false), + Manifest = table.Column(type: "nvarchar(max)", nullable: false), + Deprecated = table.Column(type: "nvarchar(max)", nullable: true), + Published = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmVersions", x => x.Key); + table.ForeignKey( + name: "FK_NpmVersions_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_NpmDistTags_PackageKey_Tag", + table: "NpmDistTags", + columns: new[] { "PackageKey", "Tag" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmPackages_RepositoryKey_Name", + table: "NpmPackages", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmVersions_PackageKey_Version", + table: "NpmVersions", + columns: new[] { "PackageKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "NpmDistTags"); + + migrationBuilder.DropTable( + name: "NpmVersions"); + + migrationBuilder.DropTable( + name: "NpmPackages"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021234347_NpmCaseSensitiveNames.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261021234347_NpmCaseSensitiveNames.Designer.cs new file mode 100644 index 000000000..62f6be518 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021234347_NpmCaseSensitiveNames.Designer.cs @@ -0,0 +1,1435 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261021234347_NpmCaseSensitiveNames")] + partial class NpmCaseSensitiveNames + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261021234347_NpmCaseSensitiveNames.cs b/src/BaGet.Database.SqlServer/Migrations/20261021234347_NpmCaseSensitiveNames.cs new file mode 100644 index 000000000..87f2014a4 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261021234347_NpmCaseSensitiveNames.cs @@ -0,0 +1,62 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class NpmCaseSensitiveNames : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Name", + table: "NpmPackages", + type: "nvarchar(214)", + maxLength: 214, + nullable: false, + collation: "Latin1_General_100_BIN2", + oldClrType: typeof(string), + oldType: "nvarchar(214)", + oldMaxLength: 214); + + migrationBuilder.AlterColumn( + name: "Tag", + table: "NpmDistTags", + type: "nvarchar(128)", + maxLength: 128, + nullable: false, + collation: "Latin1_General_100_BIN2", + oldClrType: typeof(string), + oldType: "nvarchar(128)", + oldMaxLength: 128); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Name", + table: "NpmPackages", + type: "nvarchar(214)", + maxLength: 214, + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(214)", + oldMaxLength: 214, + oldCollation: "Latin1_General_100_BIN2"); + + migrationBuilder.AlterColumn( + name: "Tag", + table: "NpmDistTags", + type: "nvarchar(128)", + maxLength: 128, + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(128)", + oldMaxLength: 128, + oldCollation: "Latin1_General_100_BIN2"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261022010641_AddMavenTables.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261022010641_AddMavenTables.Designer.cs new file mode 100644 index 000000000..fa06c877e --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261022010641_AddMavenTables.Designer.cs @@ -0,0 +1,1605 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261022010641_AddMavenTables")] + partial class AddMavenTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261022010641_AddMavenTables.cs b/src/BaGet.Database.SqlServer/Migrations/20261022010641_AddMavenTables.cs new file mode 100644 index 000000000..2047f99b5 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261022010641_AddMavenTables.cs @@ -0,0 +1,119 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddMavenTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MavenArtifacts", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + GroupId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false, collation: "Latin1_General_100_BIN2"), + ArtifactId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false, collation: "Latin1_General_100_BIN2"), + Created = table.Column(type: "datetime2", nullable: false), + Modified = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenArtifacts", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "MavenVersions", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ArtifactKey = table.Column(type: "int", nullable: false), + Version = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false, collation: "Latin1_General_100_BIN2"), + IsSnapshot = table.Column(type: "bit", nullable: false), + Name = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: true), + Description = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + Packaging = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Modified = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenVersions", x => x.Key); + table.ForeignKey( + name: "FK_MavenVersions_MavenArtifacts_ArtifactKey", + column: x => x.ArtifactKey, + principalTable: "MavenArtifacts", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "MavenFiles", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + VersionKey = table.Column(type: "int", nullable: false), + FileName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false, collation: "Latin1_General_100_BIN2"), + Classifier = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + Extension = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + SnapshotTimestamp = table.Column(type: "nvarchar(15)", maxLength: 15, nullable: true), + SnapshotBuild = table.Column(type: "int", nullable: false), + Size = table.Column(type: "bigint", nullable: false), + Sha1 = table.Column(type: "nvarchar(40)", maxLength: 40, nullable: false), + Md5 = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + Sha256 = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Sha512 = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenFiles", x => x.Key); + table.ForeignKey( + name: "FK_MavenFiles_MavenVersions_VersionKey", + column: x => x.VersionKey, + principalTable: "MavenVersions", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_MavenArtifacts_RepositoryKey_GroupId_ArtifactId", + table: "MavenArtifacts", + columns: new[] { "RepositoryKey", "GroupId", "ArtifactId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenFiles_VersionKey_FileName", + table: "MavenFiles", + columns: new[] { "VersionKey", "FileName" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenVersions_ArtifactKey_Version", + table: "MavenVersions", + columns: new[] { "ArtifactKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MavenFiles"); + + migrationBuilder.DropTable( + name: "MavenVersions"); + + migrationBuilder.DropTable( + name: "MavenArtifacts"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261022062042_AddOciTables.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261022062042_AddOciTables.Designer.cs new file mode 100644 index 000000000..56bc46bca --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261022062042_AddOciTables.Designer.cs @@ -0,0 +1,1863 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261022062042_AddOciTables")] + partial class AddOciTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261022062042_AddOciTables.cs b/src/BaGet.Database.SqlServer/Migrations/20261022062042_AddOciTables.cs new file mode 100644 index 000000000..a9a9e0886 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261022062042_AddOciTables.cs @@ -0,0 +1,225 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddOciTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "OciBlobs", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Digest = table.Column(type: "nvarchar(140)", maxLength: 140, nullable: false), + Size = table.Column(type: "bigint", nullable: false), + RefCount = table.Column(type: "int", nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobs", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "OciRepositories", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), + Created = table.Column(type: "datetime2", nullable: false), + Modified = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciRepositories", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "OciBlobLinks", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImageKey = table.Column(type: "int", nullable: false), + BlobKey = table.Column(type: "int", nullable: false), + Manifests = table.Column(type: "int", nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobLinks", x => x.Key); + table.ForeignKey( + name: "FK_OciBlobLinks_OciBlobs_BlobKey", + column: x => x.BlobKey, + principalTable: "OciBlobs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_OciBlobLinks_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciManifests", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImageKey = table.Column(type: "int", nullable: false), + Digest = table.Column(type: "nvarchar(140)", maxLength: 140, nullable: false), + MediaType = table.Column(type: "nvarchar(255)", maxLength: 255, nullable: false), + ArtifactType = table.Column(type: "nvarchar(255)", maxLength: 255, nullable: true), + SubjectDigest = table.Column(type: "nvarchar(140)", maxLength: 140, nullable: true), + Size = table.Column(type: "bigint", nullable: false), + Content = table.Column(type: "nvarchar(max)", nullable: false), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciManifests", x => x.Key); + table.ForeignKey( + name: "FK_OciManifests_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciUploads", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImageKey = table.Column(type: "int", nullable: false), + Reference = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + StorageUploadId = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: false), + Created = table.Column(type: "datetime2", nullable: false), + Updated = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciUploads", x => x.Key); + table.ForeignKey( + name: "FK_OciUploads_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciTags", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImageKey = table.Column(type: "int", nullable: false), + Name = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false, collation: "Latin1_General_100_BIN2"), + ManifestKey = table.Column(type: "int", nullable: false), + Updated = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciTags", x => x.Key); + table.ForeignKey( + name: "FK_OciTags_OciManifests_ManifestKey", + column: x => x.ManifestKey, + principalTable: "OciManifests", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_BlobKey", + table: "OciBlobLinks", + column: "BlobKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_ImageKey_BlobKey", + table: "OciBlobLinks", + columns: new[] { "ImageKey", "BlobKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobs_RepositoryKey_Digest", + table: "OciBlobs", + columns: new[] { "RepositoryKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_Digest", + table: "OciManifests", + columns: new[] { "ImageKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_SubjectDigest", + table: "OciManifests", + columns: new[] { "ImageKey", "SubjectDigest" }); + + migrationBuilder.CreateIndex( + name: "IX_OciRepositories_RepositoryKey_Name", + table: "OciRepositories", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ImageKey_Name", + table: "OciTags", + columns: new[] { "ImageKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ManifestKey", + table: "OciTags", + column: "ManifestKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_ImageKey", + table: "OciUploads", + column: "ImageKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_Reference", + table: "OciUploads", + column: "Reference", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OciBlobLinks"); + + migrationBuilder.DropTable( + name: "OciTags"); + + migrationBuilder.DropTable( + name: "OciUploads"); + + migrationBuilder.DropTable( + name: "OciBlobs"); + + migrationBuilder.DropTable( + name: "OciManifests"); + + migrationBuilder.DropTable( + name: "OciRepositories"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261023010834_AddRetention.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261023010834_AddRetention.Designer.cs new file mode 100644 index 000000000..09cadb581 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261023010834_AddRetention.Designer.cs @@ -0,0 +1,2017 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261023010834_AddRetention")] + partial class AddRetention + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261023010834_AddRetention.cs b/src/BaGet.Database.SqlServer/Migrations/20261023010834_AddRetention.cs new file mode 100644 index 000000000..0611316db --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261023010834_AddRetention.cs @@ -0,0 +1,120 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddRetention : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ArtifactUsages", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "nvarchar(340)", maxLength: 340, nullable: false), + Version = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + LastUsed = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtifactUsages", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "RetentionHolds", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "nvarchar(340)", maxLength: 340, nullable: false), + Version = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Reason = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: true), + CreatedBy = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionHolds", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "RetentionPolicies", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + RepositoryKey = table.Column(type: "int", nullable: true), + ProjectKey = table.Column(type: "int", nullable: true), + Enabled = table.Column(type: "bit", nullable: false), + NamePatterns = table.Column(type: "nvarchar(1024)", maxLength: 1024, nullable: true), + KeepLast = table.Column(type: "int", nullable: true), + OlderThanDays = table.Column(type: "int", nullable: true), + UnusedDays = table.Column(type: "int", nullable: true), + PrereleaseOnly = table.Column(type: "bit", nullable: false), + CacheLimitBytes = table.Column(type: "bigint", nullable: true), + UntaggedAfterDays = table.Column(type: "int", nullable: true), + CollectGarbage = table.Column(type: "bit", nullable: false), + ScheduleHours = table.Column(type: "int", nullable: true), + ScheduleStart = table.Column(type: "datetime2", nullable: true), + LastRun = table.Column(type: "datetime2", nullable: true), + LastResult = table.Column(type: "nvarchar(1024)", maxLength: 1024, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Modified = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionPolicies", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_ArtifactUsages_RepositoryKey_Name_Version", + table: "ArtifactUsages", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionHolds_RepositoryKey_Name_Version", + table: "RetentionHolds", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_Name", + table: "RetentionPolicies", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ArtifactUsages"); + + migrationBuilder.DropTable( + name: "RetentionHolds"); + + migrationBuilder.DropTable( + name: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261023021739_AddScanning.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261023021739_AddScanning.Designer.cs new file mode 100644 index 000000000..c2d8a4f97 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261023021739_AddScanning.Designer.cs @@ -0,0 +1,2181 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261023021739_AddScanning")] + partial class AddScanning + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261023021739_AddScanning.cs b/src/BaGet.Database.SqlServer/Migrations/20261023021739_AddScanning.cs new file mode 100644 index 000000000..f227ad0c6 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261023021739_AddScanning.cs @@ -0,0 +1,131 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddScanning : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Source", + table: "PackageVulnerabilities", + type: "nvarchar(32)", + maxLength: 32, + nullable: true); + + migrationBuilder.CreateTable( + name: "ScanPolicies", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: true), + ProjectKey = table.Column(type: "int", nullable: true), + WarnSeverity = table.Column(type: "int", nullable: true), + BlockDownloadSeverity = table.Column(type: "int", nullable: true), + BlockDeploySeverity = table.Column(type: "int", nullable: true), + BlockUnscanned = table.Column(type: "bit", nullable: false), + Modified = table.Column(type: "datetime2", nullable: false), + ModifiedBy = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanPolicies", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ScanResults", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepositoryKey = table.Column(type: "int", nullable: false, defaultValue: 1), + Name = table.Column(type: "nvarchar(400)", maxLength: 400, nullable: false), + Version = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), + Scanner = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + ScannedAt = table.Column(type: "datetime2", nullable: true), + Attempted = table.Column(type: "datetime2", nullable: false), + Error = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), + Highest = table.Column(type: "int", nullable: false), + FindingCount = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanResults", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ScanFindings", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ResultKey = table.Column(type: "int", nullable: false), + VulnerabilityId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), + Component = table.Column(type: "nvarchar(400)", maxLength: 400, nullable: false), + ComponentVersion = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), + Severity = table.Column(type: "int", nullable: false), + Summary = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), + AdvisoryUrl = table.Column(type: "nvarchar(1000)", maxLength: 1000, nullable: true), + FixedVersion = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanFindings", x => x.Key); + table.ForeignKey( + name: "FK_ScanFindings_ScanResults_ResultKey", + column: x => x.ResultKey, + principalTable: "ScanResults", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScanFindings_ResultKey", + table: "ScanFindings", + column: "ResultKey"); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + unique: true, + filter: "[ProjectKey] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + unique: true, + filter: "[RepositoryKey] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_ScanResults_RepositoryKey_Name_Version", + table: "ScanResults", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScanFindings"); + + migrationBuilder.DropTable( + name: "ScanPolicies"); + + migrationBuilder.DropTable( + name: "ScanResults"); + + migrationBuilder.DropColumn( + name: "Source", + table: "PackageVulnerabilities"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261023050015_AddRetentionUnusedSince.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261023050015_AddRetentionUnusedSince.Designer.cs new file mode 100644 index 000000000..11f5afb95 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261023050015_AddRetentionUnusedSince.Designer.cs @@ -0,0 +1,2184 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261023050015_AddRetentionUnusedSince")] + partial class AddRetentionUnusedSince + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261023050015_AddRetentionUnusedSince.cs b/src/BaGet.Database.SqlServer/Migrations/20261023050015_AddRetentionUnusedSince.cs new file mode 100644 index 000000000..49141468c --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261023050015_AddRetentionUnusedSince.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddRetentionUnusedSince : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "UnusedSince", + table: "RetentionPolicies", + type: "datetime2", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "UnusedSince", + table: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261024001409_AddReplication.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261024001409_AddReplication.Designer.cs new file mode 100644 index 000000000..011601f69 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261024001409_AddReplication.Designer.cs @@ -0,0 +1,2365 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261024001409_AddReplication")] + partial class AddReplication + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("bit"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("bit"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("nvarchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime2"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261024001409_AddReplication.cs b/src/BaGet.Database.SqlServer/Migrations/20261024001409_AddReplication.cs new file mode 100644 index 000000000..3c27119d4 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261024001409_AddReplication.cs @@ -0,0 +1,123 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddReplication : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ReplicationConfigs", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + RepositoryKey = table.Column(type: "int", nullable: false), + Direction = table.Column(type: "int", nullable: false), + PeerUrl = table.Column(type: "nvarchar(2048)", maxLength: 2048, nullable: false), + PeerRepository = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false), + ProtectedApiKey = table.Column(type: "nvarchar(2048)", maxLength: 2048, nullable: true), + Enabled = table.Column(type: "bit", nullable: false), + OnDeploy = table.Column(type: "bit", nullable: false), + ScheduleMinutes = table.Column(type: "int", nullable: true), + PropagateDeletes = table.Column(type: "bit", nullable: false), + Conflict = table.Column(type: "int", nullable: false), + ScheduleStart = table.Column(type: "datetime2", nullable: true), + LastRun = table.Column(type: "datetime2", nullable: true), + LastResult = table.Column(type: "nvarchar(1024)", maxLength: 1024, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Modified = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationConfigs", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ReplicationItems", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ConfigKey = table.Column(type: "int", nullable: false), + Name = table.Column(type: "nvarchar(340)", maxLength: 340, nullable: false), + Version = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Part = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: false), + Digest = table.Column(type: "nvarchar(160)", maxLength: 160, nullable: true), + Synced = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationItems", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ReplicationRuns", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ConfigKey = table.Column(type: "int", nullable: false), + Status = table.Column(type: "int", nullable: false), + Trigger = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: true), + Actor = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + ResumedFrom = table.Column(type: "int", nullable: true), + Started = table.Column(type: "datetime2", nullable: false), + Finished = table.Column(type: "datetime2", nullable: true), + Examined = table.Column(type: "int", nullable: false), + Transferred = table.Column(type: "int", nullable: false), + Skipped = table.Column(type: "int", nullable: false), + Deleted = table.Column(type: "int", nullable: false), + Conflicts = table.Column(type: "int", nullable: false), + Failures = table.Column(type: "int", nullable: false), + Bytes = table.Column(type: "bigint", nullable: false), + Error = table.Column(type: "nvarchar(1024)", maxLength: 1024, nullable: true), + Detail = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationRuns", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_Name", + table: "ReplicationConfigs", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationItems_ConfigKey_Name_Version_Part", + table: "ReplicationItems", + columns: new[] { "ConfigKey", "Name", "Version", "Part" }); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationRuns_ConfigKey_Started", + table: "ReplicationRuns", + columns: new[] { "ConfigKey", "Started" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ReplicationConfigs"); + + migrationBuilder.DropTable( + name: "ReplicationItems"); + + migrationBuilder.DropTable( + name: "ReplicationRuns"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261024014420_AddDataProtectionKeys.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261024014420_AddDataProtectionKeys.Designer.cs new file mode 100644 index 000000000..a3a4cac8c --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261024014420_AddDataProtectionKeys.Designer.cs @@ -0,0 +1,2385 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261024014420_AddDataProtectionKeys")] + partial class AddDataProtectionKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("bit"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("bit"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("nvarchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime2"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261024014420_AddDataProtectionKeys.cs b/src/BaGet.Database.SqlServer/Migrations/20261024014420_AddDataProtectionKeys.cs new file mode 100644 index 000000000..73bfcfe32 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261024014420_AddDataProtectionKeys.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddDataProtectionKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "DataProtectionKeys", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + FriendlyName = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), + Xml = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DataProtectionKeys", x => x.Key); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DataProtectionKeys"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261025012711_AddUserPendingApproval.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261025012711_AddUserPendingApproval.Designer.cs new file mode 100644 index 000000000..0c9dbae01 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261025012711_AddUserPendingApproval.Designer.cs @@ -0,0 +1,2388 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261025012711_AddUserPendingApproval")] + partial class AddUserPendingApproval + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PendingApproval") + .HasColumnType("bit"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("bit"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("bit"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("nvarchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime2"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261025012711_AddUserPendingApproval.cs b/src/BaGet.Database.SqlServer/Migrations/20261025012711_AddUserPendingApproval.cs new file mode 100644 index 000000000..2969210eb --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261025012711_AddUserPendingApproval.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddUserPendingApproval : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PendingApproval", + table: "AspNetUsers", + type: "bit", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PendingApproval", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261025035617_AddOwnershipForeignKeys.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261025035617_AddOwnershipForeignKeys.Designer.cs new file mode 100644 index 000000000..17413eff9 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261025035617_AddOwnershipForeignKeys.Designer.cs @@ -0,0 +1,2608 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261025035617_AddOwnershipForeignKeys")] + partial class AddOwnershipForeignKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PendingApproval") + .HasColumnType("bit"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("bit"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("bit"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("nvarchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime2"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261025035617_AddOwnershipForeignKeys.cs b/src/BaGet.Database.SqlServer/Migrations/20261025035617_AddOwnershipForeignKeys.cs new file mode 100644 index 000000000..827f59e9b --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261025035617_AddOwnershipForeignKeys.cs @@ -0,0 +1,367 @@ +using BaGet.Core; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddOwnershipForeignKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // Rows that pointed at nothing are removed first (children before parents), or the constraints below could not be created. + // On SQLite this runs before the table rebuilds that add the foreign keys. + foreach (var sql in OwnershipOrphanCleanup.Statements(OwnershipEngine.SqlServer)) + { + migrationBuilder.Sql(sql); + } + + migrationBuilder.CreateIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey"); + + migrationBuilder.AddForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags", + column: "ImageKey", + principalTable: "OciRepositories", + principalColumn: "Key"); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages"); + + migrationBuilder.DropForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts"); + + migrationBuilder.DropForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages"); + + migrationBuilder.DropForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs"); + + migrationBuilder.DropForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns"); + + migrationBuilder.DropForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults"); + + migrationBuilder.DropIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261025222349_RenameAspNetTables.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261025222349_RenameAspNetTables.Designer.cs new file mode 100644 index 000000000..a6fb7fa73 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261025222349_RenameAspNetTables.Designer.cs @@ -0,0 +1,2608 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261025222349_RenameAspNetTables")] + partial class RenameAspNetTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ApiKeyKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("IsAdministrator") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PendingApproval") + .HasColumnType("bit"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("GroupKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("bit"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("bit"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("nvarchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime2"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261025222349_RenameAspNetTables.cs b/src/BaGet.Database.SqlServer/Migrations/20261025222349_RenameAspNetTables.cs new file mode 100644 index 000000000..505f4068e --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261025222349_RenameAspNetTables.cs @@ -0,0 +1,456 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class RenameAspNetTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims"); + + migrationBuilder.RenameTable( + name: "AspNetUserTokens", + newName: "UserTokens"); + + migrationBuilder.RenameTable( + name: "AspNetUsers", + newName: "Users"); + + migrationBuilder.RenameTable( + name: "AspNetUserRoles", + newName: "UserRoles"); + + migrationBuilder.RenameTable( + name: "AspNetUserLogins", + newName: "UserLogins"); + + migrationBuilder.RenameTable( + name: "AspNetUserClaims", + newName: "UserClaims"); + + migrationBuilder.RenameTable( + name: "AspNetRoles", + newName: "Roles"); + + migrationBuilder.RenameTable( + name: "AspNetRoleClaims", + newName: "RoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "UserRoles", + newName: "IX_UserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserLogins_UserId", + table: "UserLogins", + newName: "IX_UserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserClaims_UserId", + table: "UserClaims", + newName: "IX_UserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "RoleClaims", + newName: "IX_RoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_Users", + table: "Users", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_Roles", + table: "Roles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Users", + table: "Users"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Roles", + table: "Roles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims"); + + migrationBuilder.RenameTable( + name: "UserTokens", + newName: "AspNetUserTokens"); + + migrationBuilder.RenameTable( + name: "Users", + newName: "AspNetUsers"); + + migrationBuilder.RenameTable( + name: "UserRoles", + newName: "AspNetUserRoles"); + + migrationBuilder.RenameTable( + name: "UserLogins", + newName: "AspNetUserLogins"); + + migrationBuilder.RenameTable( + name: "UserClaims", + newName: "AspNetUserClaims"); + + migrationBuilder.RenameTable( + name: "Roles", + newName: "AspNetRoles"); + + migrationBuilder.RenameTable( + name: "RoleClaims", + newName: "AspNetRoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_UserRoles_RoleId", + table: "AspNetUserRoles", + newName: "IX_AspNetUserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_UserLogins_UserId", + table: "AspNetUserLogins", + newName: "IX_AspNetUserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_UserClaims_UserId", + table: "AspNetUserClaims", + newName: "IX_AspNetUserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_RoleClaims_RoleId", + table: "AspNetRoleClaims", + newName: "IX_AspNetRoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs b/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs index 331afcb78..d9a01f28f 100644 --- a/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs +++ b/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs @@ -6,6 +6,8 @@ using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +#nullable disable + namespace BaGet.Database.SqlServer.Migrations { [DbContext(typeof(SqlServerContext))] @@ -15,228 +17,2587 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "3.1.18") - .HasAnnotation("Relational:MaxIdentifierLength", 128) - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); - modelBuilder.Entity("BaGet.Core.Package", b => + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => { b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RepositoryKey") .ValueGeneratedOnAdd() .HasColumnType("int") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + .HasDefaultValue(1); - b.Property("Authors") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + b.Property("Resolved") + .HasColumnType("datetime2"); - b.Property("Description") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + b.HasKey("Key"); - b.Property("Downloads") - .HasColumnType("bigint"); + b.HasIndex("RepositoryKey", "PackageId"); - b.Property("HasEmbeddedIcon") - .HasColumnType("bit"); + b.ToTable("AbuseReports"); + }); - b.Property("HasReadme") - .HasColumnType("bit"); + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - b.Property("IconUrl") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); - b.Property("Id") + b.Property("Action") .IsRequired() - .HasColumnType("nvarchar(128)") - .HasMaxLength(128); + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); - b.Property("IsPrerelease") - .HasColumnType("bit"); + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); - b.Property("Language") - .HasColumnType("nvarchar(20)") - .HasMaxLength(20); + b.Property("Created") + .HasColumnType("datetime2"); - b.Property("LicenseUrl") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); - b.Property("Listed") - .HasColumnType("bit"); + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); - b.Property("MinClientVersion") - .HasColumnType("nvarchar(44)") - .HasMaxLength(44); + b.HasKey("Key"); - b.Property("NormalizedVersionString") - .IsRequired() - .HasColumnName("Version") - .HasColumnType("nvarchar(64)") - .HasMaxLength(64); + b.HasIndex("Created"); - b.Property("OriginalVersionString") - .HasColumnName("OriginalVersion") - .HasColumnType("nvarchar(64)") - .HasMaxLength(64); + b.ToTable("AccessAuditEntries"); + }); - b.Property("ProjectUrl") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - b.Property("Published") + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") .HasColumnType("datetime2"); - b.Property("ReleaseNotes") - .HasColumnName("ReleaseNotes") - .HasColumnType("nvarchar(max)"); + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); - b.Property("RepositoryType") - .HasColumnType("nvarchar(100)") - .HasMaxLength(100); + b.Property("Expires") + .HasColumnType("datetime2"); - b.Property("RepositoryUrl") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); - b.Property("RequireLicenseAcceptance") - .HasColumnType("bit"); + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); - b.Property("RowVersion") - .IsConcurrencyToken() - .ValueGeneratedOnAddOrUpdate() - .HasColumnType("rowversion"); + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); - b.Property("SemVerLevel") + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() .HasColumnType("int"); - b.Property("Summary") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); - b.Property("Tags") - .HasColumnType("nvarchar(4000)") - .HasMaxLength(4000); + b.Property("ApiKeyKey") + .HasColumnType("int"); - b.Property("Title") - .HasColumnType("nvarchar(256)") - .HasMaxLength(256); + b.Property("RepositoryKey") + .HasColumnType("int"); b.HasKey("Key"); - b.HasIndex("Id"); + b.HasIndex("RepositoryKey"); - b.HasIndex("Id", "NormalizedVersionString") + b.HasIndex("ApiKeyKey", "RepositoryKey") .IsUnique(); - b.ToTable("Packages"); + b.ToTable("ApiKeyRepositories"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => { b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("LastUsed") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("RepositoryKey") .ValueGeneratedOnAdd() .HasColumnType("int") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { b.Property("Id") - .HasColumnType("nvarchar(128)") - .HasMaxLength(128); + .HasColumnType("nvarchar(450)"); - b.Property("PackageKey") + b.Property("AccessFailedCount") .HasColumnType("int"); - b.Property("TargetFramework") - .HasColumnType("nvarchar(256)") - .HasMaxLength(256); + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); - b.Property("VersionRange") - .HasColumnType("nvarchar(256)") - .HasMaxLength(256); + b.Property("Created") + .HasColumnType("datetime2"); - b.HasKey("Key"); + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); - b.HasIndex("Id"); + b.Property("EmailConfirmed") + .HasColumnType("bit"); - b.HasIndex("PackageKey"); + b.Property("IsAdministrator") + .HasColumnType("bit"); - b.ToTable("PackageDependencies"); + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PendingApproval") + .HasColumnType("bit"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("Users", (string)null); }); - modelBuilder.Entity("BaGet.Core.PackageType", b => + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => { b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") .ValueGeneratedOnAdd() .HasColumnType("int") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + .HasDefaultValue(1); - b.Property("Name") - .HasColumnType("nvarchar(512)") - .HasMaxLength(512); + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); - b.Property("PackageKey") + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() .HasColumnType("int"); - b.Property("Version") - .HasColumnType("nvarchar(64)") - .HasMaxLength(64); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); b.HasKey("Key"); - b.HasIndex("Name"); + b.ToTable("DataProtectionKeys"); + }); - b.HasIndex("PackageKey"); + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - b.ToTable("PackageTypes"); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.GroupMember", b => { b.Property("Key") .ValueGeneratedOnAdd() - .HasColumnType("int") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + .HasColumnType("int"); - b.Property("Moniker") - .HasColumnType("nvarchar(256)") - .HasMaxLength(256); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); - b.Property("PackageKey") + b.Property("GroupKey") .HasColumnType("int"); + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + b.HasKey("Key"); - b.HasIndex("Moniker"); + b.HasIndex("UserId"); - b.HasIndex("PackageKey"); + b.HasIndex("GroupKey", "UserId") + .IsUnique(); - b.ToTable("TargetFrameworks"); + b.ToTable("GroupMembers"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("Dependencies") - .HasForeignKey("PackageKey"); - }); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - modelBuilder.Entity("BaGet.Core.PackageType", b => - { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("PackageTypes") - .HasForeignKey("PackageKey") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.MavenFile", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("TargetFrameworks") - .HasForeignKey("PackageKey") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SnapshotBuild") + .HasColumnType("int"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("nvarchar(15)"); + + b.Property("VersionKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsSnapshot") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("nvarchar(214)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Deprecated") + .HasColumnType("nvarchar(max)"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("TarballSize") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("RefCount") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlobKey") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Manifests") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("nvarchar(140)"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("ManifestKey") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)") + .UseCollation("Latin1_General_100_BIN2"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ImageKey") + .HasColumnType("int"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Updated") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actions") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("IsBuiltIn") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Conflict") + .HasColumnType("int"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("OnDeploy") + .HasColumnType("bit"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("PropagateDeletes") + .HasColumnType("bit"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleMinutes") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("nvarchar(160)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Synced") + .HasColumnType("datetime2"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("ConfigKey") + .HasColumnType("int"); + + b.Property("Conflicts") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("int"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Examined") + .HasColumnType("int"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("Finished") + .HasColumnType("datetime2"); + + b.Property("ResumedFrom") + .HasColumnType("int"); + + b.Property("Skipped") + .HasColumnType("int"); + + b.Property("Started") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Transferred") + .HasColumnType("int"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AnonymousRead") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("Settings") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("nvarchar(340)"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CacheLimitBytes") + .HasColumnType("bigint"); + + b.Property("CollectGarbage") + .HasColumnType("bit"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("KeepLast") + .HasColumnType("int"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("LastRun") + .HasColumnType("datetime2"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("OlderThanDays") + .HasColumnType("int"); + + b.Property("PrereleaseOnly") + .HasColumnType("bit"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("ScheduleHours") + .HasColumnType("int"); + + b.Property("ScheduleStart") + .HasColumnType("datetime2"); + + b.Property("UntaggedAfterDays") + .HasColumnType("int"); + + b.Property("UnusedDays") + .HasColumnType("int"); + + b.Property("UnusedSince") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ResultKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("BlockDeploySeverity") + .HasColumnType("int"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("int"); + + b.Property("BlockUnscanned") + .HasColumnType("bit"); + + b.Property("Modified") + .HasColumnType("datetime2"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ProjectKey") + .HasColumnType("int"); + + b.Property("RepositoryKey") + .HasColumnType("int"); + + b.Property("WarnSeverity") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique() + .HasFilter("[ProjectKey] IS NOT NULL"); + + b.HasIndex("RepositoryKey") + .IsUnique() + .HasFilter("[RepositoryKey] IS NOT NULL"); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Attempted") + .HasColumnType("datetime2"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("FindingCount") + .HasColumnType("int"); + + b.Property("Highest") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("datetime2"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); }); #pragma warning restore 612, 618 } diff --git a/src/BaGet.Database.SqlServer/README.md b/src/BaGet.Database.SqlServer/README.md new file mode 100644 index 000000000..84d1ca379 --- /dev/null +++ b/src/BaGet.Database.SqlServer/README.md @@ -0,0 +1,44 @@ +# Extension.BaGet.Database.SqlServer + +The SQL Server database provider of [BaGet Extension](https://pieroviano.github.io/BaGet/), built on `Microsoft.EntityFrameworkCore.SqlServer`. + +```powershell +dotnet add package Extension.BaGet.Database.SqlServer +``` + +## Usage + +Register it in the `BaGetApplication` callback; it activates when `Database:Type` is `SqlServer`: + +```csharp +services.AddBaGetWebApplication(app => app.AddSqlServerDatabase()); +``` + +| Setting | Value | +|---|---| +| `Database:Type` | `SqlServer` | +| `Database:ConnectionString` | e.g. `Server=.;Database=BaGet;Trusted_Connection=True;TrustServerCertificate=True` | + +`AddSqlServerDatabase` also registers `SqlServerDatabaseContextFactory` (`IDatabaseContextFactory`), which opens a `SqlServerContext` on any connection string for the Settings page's database copy. SQL Server wraps explicit-key inserts in `SET IDENTITY_INSERT` (connection kept open). + +## Migrations (contributors) + +The project has its own design-time context factory, so `dotnet ef` needs no startup project and no +running database. The tool version is pinned by `.config/dotnet-tools.json`; run `dotnet tool restore` once. + +From this folder: + +``` +dotnet ef migrations add MigrationName --context SqlServerContext --output-dir Migrations +dotnet ef migrations has-pending-model-changes --context SqlServerContext +``` + +A model change needs a migration in **all four** `BaGet.Database.*` projects, and each must then report +no pending model changes. Keep schema changes additive (new tables, nullable foreign keys): SQLite cannot +alter a foreign key in place. + +BaGet applies pending migrations itself when it starts. + +- List migrations without a server: `dotnet ef migrations list --context SqlServerContext`. +- Never run `dotnet ef migrations remove --no-build`: with a stale assembly it deleted the previous migration. Delete the generated files by hand and restore the model snapshot from `HEAD`. +- Entity Framework is 10.0.13; the MySQL provider is `Microting.EntityFrameworkCore.MySql`; all four providers move together. diff --git a/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs b/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs index b2292e08e..ddee701d6 100644 --- a/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs +++ b/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs @@ -1,33 +1,38 @@ using System; using BaGet.Core; using BaGet.Database.SqlServer; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class SqlServerApplicationExtensions { - public static class SqlServerApplicationExtensions + public static BaGetApplication AddSqlServerDatabase(this BaGetApplication app) { - public static BaGetApplication AddSqlServerDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("SqlServer", (provider, options) => { - app.Services.AddBaGetDbContextProvider("SqlServer", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - options.UseSqlServer(databaseOptions.Value.ConnectionString); - }); + SqlServerDatabaseContextFactory.Configure( + options, + databaseOptions.Value.ConnectionString, + databaseOptions.Value.MySqlServerVersion); + }); - return app; - } + app.Services.TryAddEnumerable( + ServiceDescriptor.Singleton()); - public static BaGetApplication AddSqlServerDatabase( - this BaGetApplication app, - Action configure) - { - app.AddSqlServerDatabase(); - app.Services.Configure(configure); - return app; - } + return app; + } + + public static BaGetApplication AddSqlServerDatabase( + this BaGetApplication app, + Action configure) + { + app.AddSqlServerDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.SqlServer/SqlServerContext.cs b/src/BaGet.Database.SqlServer/SqlServerContext.cs index 3639b8cad..befed82ec 100644 --- a/src/BaGet.Database.SqlServer/SqlServerContext.cs +++ b/src/BaGet.Database.SqlServer/SqlServerContext.cs @@ -1,36 +1,149 @@ using System.Linq; +using System.Threading; +using System.Threading.Tasks; using BaGet.Core; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; -namespace BaGet.Database.SqlServer +namespace BaGet.Database.SqlServer; + +public class SqlServerContext : AbstractContext { - public class SqlServerContext : AbstractContext + /// + /// The SQL Server error code for a violated UNIQUE or PRIMARY KEY constraint. + /// + private const int UniqueConstraintViolationErrorCode = 2627; + + /// + /// The SQL Server error code for a violated unique index. EF Core creates unique indexes (not constraints) for + /// HasIndex(...).IsUnique(), such as the one on a package's repository, ID and version, so this is the code a + /// duplicate package raises. + /// + private const int UniqueIndexViolationErrorCode = 2601; + + public SqlServerContext(DbContextOptions options) + : base(options) + { } + + /// + /// npm package names and dist-tags are case-sensitive (legacy names such as JSONStream still exist), so they are + /// compared by code point, never by the database's default case-insensitive collation: an exact lookup, and the unique + /// index, then behave as on SQLite and PostgreSQL. + /// + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + builder.Entity().Property(p => p.Name).UseCollation(NpmCollation); + builder.Entity().Property(t => t.Tag).UseCollation(NpmCollation); + + // Maven coordinates, versions and file names are case-sensitive folders, compared by code point for the same reason. + builder.Entity().Property(a => a.GroupId).UseCollation(NpmCollation); + builder.Entity().Property(a => a.ArtifactId).UseCollation(NpmCollation); + builder.Entity().Property(v => v.Version).UseCollation(NpmCollation); + builder.Entity().Property(f => f.FileName).UseCollation(NpmCollation); + + // Tags are case-sensitive (image names and digests are lower case by rule). + builder.Entity().Property(t => t.Name).UseCollation(NpmCollation); + } + + /// The binary collation of the npm identifier columns. + internal const string NpmCollation = "Latin1_General_100_BIN2"; + + /// + /// Check whether a is due to a SQL unique constraint violation. + /// + /// The exception to inspect. + /// Whether the exception was caused to SQL unique constraint violation. + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) + { + if (exception.GetBaseException() is SqlException sqlException) + { + return sqlException.Errors + .OfType() + .Any(error => error.Number == UniqueConstraintViolationErrorCode || error.Number == UniqueIndexViolationErrorCode); + } + + return false; + } + + /// + /// Turns IDENTITY_INSERT on for the table, so explicit key values can be inserted. + /// + /// + /// The setting belongs to the connection, so this opens the context's connection and keeps it open + /// (EF reference-counts it, so SaveChanges reuses the same session) until + /// . Only one table per session can have it on. Tables without an + /// identity column (such as Identity's string-keyed ones) are left alone. + /// + public override async Task BeginKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken) + { + var sql = BuildIdentityInsertSql(table, on: true); + if (sql == null) + { + return; + } + + await Database.OpenConnectionAsync(cancellationToken); + try + { + await Database.ExecuteSqlRawAsync(sql, cancellationToken); + } + catch + { + await Database.CloseConnectionAsync(); + throw; + } + } + + /// + /// Turns IDENTITY_INSERT off again and releases the connection opened by + /// . SQL Server continues the identity after the highest inserted value itself. + /// + public override async Task EndKeyedInsertAsync(IEntityType table, CancellationToken cancellationToken) + { + var sql = BuildIdentityInsertSql(table, on: false); + if (sql == null) + { + return; + } + + try + { + await Database.ExecuteSqlRawAsync(sql, cancellationToken); + } + finally + { + await Database.CloseConnectionAsync(); + } + } + + /// + /// The SET IDENTITY_INSERT statement for the table, or when none of its + /// columns is an identity column. + /// + internal static string? BuildIdentityInsertSql(IEntityType table, bool on) { - /// - /// The SQL Server error code for when a unique contraint is violated. - /// - private const int UniqueConstraintViolationErrorCode = 2627; - - public SqlServerContext(DbContextOptions options) - : base(options) - { } - - /// - /// Check whether a is due to a SQL unique constraint violation. - /// - /// The exception to inspect. - /// Whether the exception was caused to SQL unique constraint violation. - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - if (exception.GetBaseException() is SqlException sqlException) - { - return sqlException.Errors - .OfType() - .Any(error => error.Number == UniqueConstraintViolationErrorCode); - } - - return false; + var name = table.GetTableName(); + if (name == null) + { + return null; } + + var schema = table.GetSchema(); + var store = StoreObjectIdentifier.Table(name, schema); + var hasIdentity = table.GetProperties().Any(p => + p.GetValueGenerationStrategy(store) == SqlServerValueGenerationStrategy.IdentityColumn); + + if (!hasIdentity) + { + return null; + } + + var qualified = schema == null ? Quote(name) : $"{Quote(schema)}.{Quote(name)}"; + return $"SET IDENTITY_INSERT {qualified} {(on ? "ON" : "OFF")}"; } -} + + private static string Quote(string identifier) => "[" + identifier.Replace("]", "]]") + "]"; +} \ No newline at end of file diff --git a/src/BaGet.Database.SqlServer/SqlServerContextFactory.cs b/src/BaGet.Database.SqlServer/SqlServerContextFactory.cs new file mode 100644 index 000000000..13cf560b4 --- /dev/null +++ b/src/BaGet.Database.SqlServer/SqlServerContextFactory.cs @@ -0,0 +1,25 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace BaGet.Database.SqlServer; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class SqlServerContextFactory : IDesignTimeDbContextFactory +{ + public SqlServerContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=BaGet") + .Options; + + return new SqlServerContext(options); + } +} \ No newline at end of file diff --git a/src/BaGet.Database.SqlServer/SqlServerDatabaseContextFactory.cs b/src/BaGet.Database.SqlServer/SqlServerDatabaseContextFactory.cs new file mode 100644 index 000000000..80264d0e8 --- /dev/null +++ b/src/BaGet.Database.SqlServer/SqlServerDatabaseContextFactory.cs @@ -0,0 +1,37 @@ +using System; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Database.SqlServer; + +/// +/// Opens a on any SqlServer connection string; see . +/// +public class SqlServerDatabaseContextFactory : IDatabaseContextFactory +{ + /// + public string DatabaseType => "SqlServer"; + + /// + public IContext Create( + string connectionString, + DatabaseOptions? options = null, + Action? configure = null) + { + var builder = new DbContextOptionsBuilder(); + + Configure(builder, connectionString, options?.MySqlServerVersion); + configure?.Invoke(builder); + + return new SqlServerContext(builder.Options); + } + + /// + /// The one place the provider is configured: used by both this factory and the application's + /// registration, so a second database is configured exactly like the main one. + /// + internal static void Configure(DbContextOptionsBuilder options, string? connectionString, string? mySqlServerVersion) + { + options.UseSqlServer(connectionString); + } +} diff --git a/src/BaGet.Database.SqlServer/readme.md b/src/BaGet.Database.SqlServer/readme.md deleted file mode 100644 index 13a058dd7..000000000 --- a/src/BaGet.Database.SqlServer/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -# BaGet's SQL Server Database Provider - -This project contains BaGet's Microsoft SQL Server database provider. - -## Migrations - -Add a migration with: - -``` -dotnet ef migrations add MigrationName --context SqlServerContext --output-dir Migrations --startup-project ..\BaGet\BaGet.csproj - -dotnet ef database update --context SqlServerContext -``` diff --git a/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj b/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj index c7515daac..8ea86de17 100644 --- a/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj +++ b/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj @@ -1,18 +1,26 @@ - netstandard2.0 - + net10.0 + latest NuGet - The libraries to host BaGet on SQLite. + The libraries to host BaGet Extension on SQLite. + enable + + + + + + + diff --git a/src/BaGet.Database.Sqlite/Migrations/20180804082808_Initial.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20180804082808_Initial.Designer.cs index f560e7e01..2d580a14a 100644 --- a/src/BaGet.Database.Sqlite/Migrations/20180804082808_Initial.Designer.cs +++ b/src/BaGet.Database.Sqlite/Migrations/20180804082808_Initial.Designer.cs @@ -1,3 +1,4 @@ +#nullable disable // using System; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.Sqlite/Migrations/20190303072658_AddSearchDimensions.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20190303072658_AddSearchDimensions.Designer.cs index b61698391..82b92d2fd 100644 --- a/src/BaGet.Database.Sqlite/Migrations/20190303072658_AddSearchDimensions.Designer.cs +++ b/src/BaGet.Database.Sqlite/Migrations/20190303072658_AddSearchDimensions.Designer.cs @@ -1,3 +1,4 @@ +#nullable disable // using System; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.Sqlite/Migrations/20190914215110_AddOriginalVersionStringColumn.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20190914215110_AddOriginalVersionStringColumn.Designer.cs index b3a7f03d1..d30a40f76 100644 --- a/src/BaGet.Database.Sqlite/Migrations/20190914215110_AddOriginalVersionStringColumn.Designer.cs +++ b/src/BaGet.Database.Sqlite/Migrations/20190914215110_AddOriginalVersionStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.Sqlite; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.Sqlite/Migrations/20200109071618_AddReleaseNotesStringColumn.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20200109071618_AddReleaseNotesStringColumn.Designer.cs index ea480a1b9..0bec219eb 100644 --- a/src/BaGet.Database.Sqlite/Migrations/20200109071618_AddReleaseNotesStringColumn.Designer.cs +++ b/src/BaGet.Database.Sqlite/Migrations/20200109071618_AddReleaseNotesStringColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.Sqlite; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.Sqlite/Migrations/20200208044959_FixVersionCaseSensitivity.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20200208044959_FixVersionCaseSensitivity.Designer.cs index 17057197d..09a4dc3c2 100644 --- a/src/BaGet.Database.Sqlite/Migrations/20200208044959_FixVersionCaseSensitivity.Designer.cs +++ b/src/BaGet.Database.Sqlite/Migrations/20200208044959_FixVersionCaseSensitivity.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.Sqlite; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.Sqlite/Migrations/20200210004344_AddHasEmbeddedIconColumn.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20200210004344_AddHasEmbeddedIconColumn.Designer.cs index 4dde2f2ea..158b3c7a2 100644 --- a/src/BaGet.Database.Sqlite/Migrations/20200210004344_AddHasEmbeddedIconColumn.Designer.cs +++ b/src/BaGet.Database.Sqlite/Migrations/20200210004344_AddHasEmbeddedIconColumn.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.Sqlite; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.Sqlite/Migrations/20210919190849_RemoveReleaseNotesMaxLength.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20210919190849_RemoveReleaseNotesMaxLength.Designer.cs index 6d54a7128..62ce3ee2f 100644 --- a/src/BaGet.Database.Sqlite/Migrations/20210919190849_RemoveReleaseNotesMaxLength.Designer.cs +++ b/src/BaGet.Database.Sqlite/Migrations/20210919190849_RemoveReleaseNotesMaxLength.Designer.cs @@ -1,4 +1,5 @@ -// +#nullable disable +// using System; using BaGet.Database.Sqlite; using Microsoft.EntityFrameworkCore; diff --git a/src/BaGet.Database.Sqlite/Migrations/20261016053007_AddDeprecationAndVulnerability.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261016053007_AddDeprecationAndVulnerability.Designer.cs new file mode 100644 index 000000000..6629f17f9 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261016053007_AddDeprecationAndVulnerability.Designer.cs @@ -0,0 +1,338 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261016053007_AddDeprecationAndVulnerability")] + partial class AddDeprecationAndVulnerability + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261016053007_AddDeprecationAndVulnerability.cs b/src/BaGet.Database.Sqlite/Migrations/20261016053007_AddDeprecationAndVulnerability.cs new file mode 100644 index 000000000..228310e1d --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261016053007_AddDeprecationAndVulnerability.cs @@ -0,0 +1,78 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddDeprecationAndVulnerability : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageDeprecations", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Reasons = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + Message = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + AlternatePackageId = table.Column(type: "TEXT", maxLength: 128, nullable: true), + AlternateVersionRange = table.Column(type: "TEXT", maxLength: 256, nullable: true), + PackageKey = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageDeprecations", x => x.Key); + table.ForeignKey( + name: "FK_PackageDeprecations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateTable( + name: "PackageVulnerabilities", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + AdvisoryUrl = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + Severity = table.Column(type: "INTEGER", nullable: false), + VersionRange = table.Column(type: "TEXT", maxLength: 256, nullable: true), + PackageKey = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageVulnerabilities", x => x.Key); + table.ForeignKey( + name: "FK_PackageVulnerabilities_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageDeprecations_PackageKey", + table: "PackageDeprecations", + column: "PackageKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageVulnerabilities_PackageKey", + table: "PackageVulnerabilities", + column: "PackageKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageDeprecations"); + + migrationBuilder.DropTable( + name: "PackageVulnerabilities"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017011639_AddCatalog.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261017011639_AddCatalog.Designer.cs new file mode 100644 index 000000000..4bc2f5c87 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017011639_AddCatalog.Designer.cs @@ -0,0 +1,375 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261017011639_AddCatalog")] + partial class AddCatalog + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017011639_AddCatalog.cs b/src/BaGet.Database.Sqlite/Migrations/20261017011639_AddCatalog.cs new file mode 100644 index 000000000..68c97b26e --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017011639_AddCatalog.cs @@ -0,0 +1,45 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddCatalog : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "CatalogLeafs", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + CommitId = table.Column(type: "TEXT", maxLength: 36, nullable: false), + CommitTimestamp = table.Column(type: "TEXT", nullable: false), + Type = table.Column(type: "TEXT", maxLength: 32, nullable: false), + PackageId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "TEXT", maxLength: 64, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_CatalogLeafs", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_CommitId", + table: "CatalogLeafs", + column: "CommitId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "CatalogLeafs"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017012801_AddAccounts.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261017012801_AddAccounts.Designer.cs new file mode 100644 index 000000000..46689c3ac --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017012801_AddAccounts.Designer.cs @@ -0,0 +1,750 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261017012801_AddAccounts")] + partial class AddAccounts + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017012801_AddAccounts.cs b/src/BaGet.Database.Sqlite/Migrations/20261017012801_AddAccounts.cs new file mode 100644 index 000000000..8cb9a1af4 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017012801_AddAccounts.cs @@ -0,0 +1,340 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddAccounts : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeys", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "TEXT", maxLength: 450, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 256, nullable: true), + HashedKey = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Scopes = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + PackageGlobPattern = table.Column(type: "TEXT", maxLength: 128, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Expires = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeys", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoles", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 256, nullable: true), + NormalizedName = table.Column(type: "TEXT", maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetUsers", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "TEXT", nullable: false), + UserName = table.Column(type: "TEXT", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Email = table.Column(type: "TEXT", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "TEXT", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "INTEGER", nullable: false), + PasswordHash = table.Column(type: "TEXT", nullable: true), + SecurityStamp = table.Column(type: "TEXT", nullable: true), + ConcurrencyStamp = table.Column(type: "TEXT", nullable: true), + PhoneNumber = table.Column(type: "TEXT", nullable: true), + PhoneNumberConfirmed = table.Column(type: "INTEGER", nullable: false), + TwoFactorEnabled = table.Column(type: "INTEGER", nullable: false), + LockoutEnd = table.Column(type: "TEXT", nullable: true), + LockoutEnabled = table.Column(type: "INTEGER", nullable: false), + AccessFailedCount = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Organizations", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Organizations", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "PackageOwners", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PackageId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + OwnerName = table.Column(type: "TEXT", maxLength: 256, nullable: false), + IsVerified = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageOwners", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RoleId = table.Column(type: "TEXT", nullable: false), + ClaimType = table.Column(type: "TEXT", nullable: true), + ClaimValue = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserClaims", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "TEXT", nullable: false), + ClaimType = table.Column(type: "TEXT", nullable: true), + ClaimValue = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserLogins", + columns: table => new + { + LoginProvider = table.Column(type: "TEXT", nullable: false), + ProviderKey = table.Column(type: "TEXT", nullable: false), + ProviderDisplayName = table.Column(type: "TEXT", nullable: true), + UserId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserRoles", + columns: table => new + { + UserId = table.Column(type: "TEXT", nullable: false), + RoleId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserTokens", + columns: table => new + { + UserId = table.Column(type: "TEXT", nullable: false), + LoginProvider = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + Value = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OrganizationMembers", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + OrganizationKey = table.Column(type: "INTEGER", nullable: true), + UserId = table.Column(type: "TEXT", maxLength: 450, nullable: false), + IsAdmin = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OrganizationMembers", x => x.Key); + table.ForeignKey( + name: "FK_OrganizationMembers_Organizations_OrganizationKey", + column: x => x.OrganizationKey, + principalTable: "Organizations", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_HashedKey", + table: "ApiKeys", + column: "HashedKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeys_UserId", + table: "ApiKeys", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "AspNetRoleClaims", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "AspNetRoles", + column: "NormalizedName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserClaims_UserId", + table: "AspNetUserClaims", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserLogins_UserId", + table: "AspNetUserLogins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "AspNetUsers", + column: "NormalizedEmail"); + + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "AspNetUsers", + column: "NormalizedUserName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_OrganizationKey", + table: "OrganizationMembers", + column: "OrganizationKey"); + + migrationBuilder.CreateIndex( + name: "IX_OrganizationMembers_UserId", + table: "OrganizationMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Organizations_Name", + table: "Organizations", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_OwnerName", + table: "PackageOwners", + column: "OwnerName"); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeys"); + + migrationBuilder.DropTable( + name: "AspNetRoleClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserLogins"); + + migrationBuilder.DropTable( + name: "AspNetUserRoles"); + + migrationBuilder.DropTable( + name: "AspNetUserTokens"); + + migrationBuilder.DropTable( + name: "OrganizationMembers"); + + migrationBuilder.DropTable( + name: "PackageOwners"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + + migrationBuilder.DropTable( + name: "Organizations"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..fdb18f5c0 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.Designer.cs @@ -0,0 +1,812 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261017014343_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.cs b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.cs new file mode 100644 index 000000000..55b5feb25 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.cs @@ -0,0 +1,63 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + SubmissionId = table.Column(type: "TEXT", maxLength: 36, nullable: false), + PackageId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "TEXT", maxLength: 64, nullable: false), + PackageKey = table.Column(type: "INTEGER", nullable: true), + Type = table.Column(type: "TEXT", maxLength: 64, nullable: false), + State = table.Column(type: "INTEGER", nullable: false), + Message = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Completed = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..ed292c480 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.Designer.cs @@ -0,0 +1,855 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261017020112_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.cs b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.cs new file mode 100644 index 000000000..0f5f7db3a --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PackageId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Reason = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Details = table.Column(type: "TEXT", maxLength: 4000, nullable: false), + ReporterEmail = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Resolved = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261018043324_AddAdministrators.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261018043324_AddAdministrators.Designer.cs new file mode 100644 index 000000000..4d8eb5e8d --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261018043324_AddAdministrators.Designer.cs @@ -0,0 +1,858 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261018043324_AddAdministrators")] + partial class AddAdministrators + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261018043324_AddAdministrators.cs b/src/BaGet.Database.Sqlite/Migrations/20261018043324_AddAdministrators.cs new file mode 100644 index 000000000..3c0aff399 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261018043324_AddAdministrators.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddAdministrators : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsAdministrator", + table: "AspNetUsers", + type: "INTEGER", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsAdministrator", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261020071950_AddRepositories.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261020071950_AddRepositories.Designer.cs new file mode 100644 index 000000000..44e28d2d8 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261020071950_AddRepositories.Designer.cs @@ -0,0 +1,952 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261020071950_AddRepositories")] + partial class AddRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261020071950_AddRepositories.cs b/src/BaGet.Database.Sqlite/Migrations/20261020071950_AddRepositories.cs new file mode 100644 index 000000000..a3cfb8b92 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261020071950_AddRepositories.cs @@ -0,0 +1,217 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports"); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageValidations", + type: "INTEGER", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "Packages", + type: "INTEGER", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "PackageOwners", + type: "INTEGER", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "CatalogLeafs", + type: "INTEGER", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "RepositoryKey", + table: "AbuseReports", + type: "INTEGER", + nullable: false, + defaultValue: 1); + + migrationBuilder.CreateTable( + name: "Projects", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + DisplayName = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Projects", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "Repositories", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Format = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Kind = table.Column(type: "TEXT", maxLength: 32, nullable: false), + ProjectKey = table.Column(type: "INTEGER", nullable: true), + Settings = table.Column(type: "TEXT", nullable: true), + AnonymousRead = table.Column(type: "INTEGER", nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Repositories", x => x.Key); + }); + + // The default repository (key 1 = RepositoryKey's column default, so every existing row already belongs to + // it). Created here, not only by startup, so that applying migrations without RunMigrationsAtStartup + // (dotnet ef database update, an SQL script) cannot leave a new repository to take key 1. + migrationBuilder.InsertData( + table: "Repositories", + columns: new[] { "Key", "Name", "Format", "Kind", "AnonymousRead", "Created" }, + values: new object[] { 1, "default", "NuGet", "Local", true, DateTime.UtcNow }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages", + columns: new[] { "RepositoryKey", "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports", + columns: new[] { "RepositoryKey", "PackageId" }); + + migrationBuilder.CreateIndex( + name: "IX_Projects_Name", + table: "Projects", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Repositories_Name", + table: "Repositories", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Projects"); + + migrationBuilder.DropTable( + name: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PackageValidations_RepositoryKey_PackageId", + table: "PackageValidations"); + + migrationBuilder.DropIndex( + name: "IX_Packages_RepositoryKey_Id_Version", + table: "Packages"); + + migrationBuilder.DropIndex( + name: "IX_PackageOwners_RepositoryKey_PackageId", + table: "PackageOwners"); + + migrationBuilder.DropIndex( + name: "IX_CatalogLeafs_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropIndex( + name: "IX_AbuseReports_RepositoryKey_PackageId", + table: "AbuseReports"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "Packages"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropColumn( + name: "RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_Packages_Id_Version", + table: "Packages", + columns: new[] { "Id", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PackageOwners_PackageId", + table: "PackageOwners", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021035258_AddPackageSymbols.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261021035258_AddPackageSymbols.Designer.cs new file mode 100644 index 000000000..c51dcbe4f --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021035258_AddPackageSymbols.Designer.cs @@ -0,0 +1,995 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261021035258_AddPackageSymbols")] + partial class AddPackageSymbols + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021035258_AddPackageSymbols.cs b/src/BaGet.Database.Sqlite/Migrations/20261021035258_AddPackageSymbols.cs new file mode 100644 index 000000000..aef08dd68 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021035258_AddPackageSymbols.cs @@ -0,0 +1,50 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddPackageSymbols : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageSymbols", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + PackageId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "TEXT", maxLength: 64, nullable: false), + FileName = table.Column(type: "TEXT", maxLength: 255, nullable: false), + SymbolKey = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageSymbols", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_FileName_SymbolKey", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "FileName", "SymbolKey" }); + + migrationBuilder.CreateIndex( + name: "IX_PackageSymbols_RepositoryKey_PackageId_PackageVersion", + table: "PackageSymbols", + columns: new[] { "RepositoryKey", "PackageId", "PackageVersion" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageSymbols"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021040413_AddAccessControl.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261021040413_AddAccessControl.Designer.cs new file mode 100644 index 000000000..443e7aeb6 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021040413_AddAccessControl.Designer.cs @@ -0,0 +1,1173 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261021040413_AddAccessControl")] + partial class AddAccessControl + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021040413_AddAccessControl.cs b/src/BaGet.Database.Sqlite/Migrations/20261021040413_AddAccessControl.cs new file mode 100644 index 000000000..758f6b587 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021040413_AddAccessControl.cs @@ -0,0 +1,226 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddAccessControl : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AccessAuditEntries", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Created = table.Column(type: "TEXT", nullable: false), + Actor = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Action = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Subject = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Details = table.Column(type: "TEXT", maxLength: 4000, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AccessAuditEntries", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "Groups", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + IsBuiltIn = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Groups", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "PermissionTargets", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + RepositoryPatterns = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + IncludePatterns = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + ExcludePatterns = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + ProjectKey = table.Column(type: "INTEGER", nullable: true), + IsBuiltIn = table.Column(type: "INTEGER", nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionTargets", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ProjectMembers", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ProjectKey = table.Column(type: "INTEGER", nullable: false), + PrincipalType = table.Column(type: "TEXT", maxLength: 16, nullable: false), + PrincipalId = table.Column(type: "TEXT", maxLength: 450, nullable: false), + Role = table.Column(type: "TEXT", maxLength: 16, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ProjectMembers", x => x.Key); + table.ForeignKey( + name: "FK_ProjectMembers_Projects_ProjectKey", + column: x => x.ProjectKey, + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "GroupMembers", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + GroupKey = table.Column(type: "INTEGER", nullable: false), + UserId = table.Column(type: "TEXT", maxLength: 450, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_GroupMembers", x => x.Key); + table.ForeignKey( + name: "FK_GroupMembers_Groups_GroupKey", + column: x => x.GroupKey, + principalTable: "Groups", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PermissionGrants", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + TargetKey = table.Column(type: "INTEGER", nullable: false), + PrincipalType = table.Column(type: "TEXT", maxLength: 16, nullable: false), + PrincipalId = table.Column(type: "TEXT", maxLength: 450, nullable: false), + Actions = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionGrants", x => x.Key); + table.ForeignKey( + name: "FK_PermissionGrants_PermissionTargets_TargetKey", + column: x => x.TargetKey, + principalTable: "PermissionTargets", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + // The upgrade defaults: what the server did before the access model existed. Everyone reads every + // repository; every authenticated caller deploys, annotates, deletes and manages (package ownership is + // still applied inside those actions). Explicit keys, so the grants below can name them. + var seeded = DateTime.UtcNow; + + migrationBuilder.InsertData( + table: "Groups", + columns: new[] { "Key", "Name", "Description", "Created", "IsBuiltIn" }, + values: new object[,] + { + { 1, "Everyone", "Every caller, anonymous ones included.", seeded, true }, + { 2, "Authenticated", "Every caller that presented valid credentials.", seeded, true }, + }); + + migrationBuilder.InsertData( + table: "PermissionTargets", + columns: new[] { "Key", "Name", "RepositoryPatterns", "IncludePatterns", "ExcludePatterns", "IsBuiltIn", "Created" }, + values: new object[,] + { + { 1, "Anyone reads every repository", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + { 2, "Authenticated users deploy", "[\"*\"]", "[\"*\"]", "[]", true, seeded }, + }); + + // Actions: Read = 1; Annotate | Deploy | Delete | Manage = 2 + 4 + 8 + 16 = 30. + migrationBuilder.InsertData( + table: "PermissionGrants", + columns: new[] { "Key", "TargetKey", "PrincipalType", "PrincipalId", "Actions" }, + values: new object[,] + { + { 1, 1, "Group", "1", 1 }, + { 2, 2, "Group", "2", 30 }, + }); + + migrationBuilder.CreateIndex( + name: "IX_AccessAuditEntries_Created", + table: "AccessAuditEntries", + column: "Created"); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_GroupKey_UserId", + table: "GroupMembers", + columns: new[] { "GroupKey", "UserId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_GroupMembers_UserId", + table: "GroupMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Groups_Name", + table: "Groups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionGrants_TargetKey_PrincipalType_PrincipalId", + table: "PermissionGrants", + columns: new[] { "TargetKey", "PrincipalType", "PrincipalId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_Name", + table: "PermissionTargets", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ProjectMembers_ProjectKey_PrincipalType_PrincipalId", + table: "ProjectMembers", + columns: new[] { "ProjectKey", "PrincipalType", "PrincipalId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AccessAuditEntries"); + + migrationBuilder.DropTable( + name: "GroupMembers"); + + migrationBuilder.DropTable( + name: "PermissionGrants"); + + migrationBuilder.DropTable( + name: "ProjectMembers"); + + migrationBuilder.DropTable( + name: "Groups"); + + migrationBuilder.DropTable( + name: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021055026_AddApiKeyRepositories.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261021055026_AddApiKeyRepositories.Designer.cs new file mode 100644 index 000000000..242bf1733 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021055026_AddApiKeyRepositories.Designer.cs @@ -0,0 +1,1249 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261021055026_AddApiKeyRepositories")] + partial class AddApiKeyRepositories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021055026_AddApiKeyRepositories.cs b/src/BaGet.Database.Sqlite/Migrations/20261021055026_AddApiKeyRepositories.cs new file mode 100644 index 000000000..32b27324d --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021055026_AddApiKeyRepositories.cs @@ -0,0 +1,52 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddApiKeyRepositories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ApiKeyRepositories", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ApiKeyKey = table.Column(type: "INTEGER", nullable: false), + RepositoryKey = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ApiKeyRepositories", x => x.Key); + table.ForeignKey( + name: "FK_ApiKeyRepositories_ApiKeys_ApiKeyKey", + column: x => x.ApiKeyKey, + principalTable: "ApiKeys", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_ApiKeyKey_RepositoryKey", + table: "ApiKeyRepositories", + columns: new[] { "ApiKeyKey", "RepositoryKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ApiKeyRepositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ApiKeyRepositories"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021155622_AddNpmTables.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261021155622_AddNpmTables.Designer.cs new file mode 100644 index 000000000..229ae356f --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021155622_AddNpmTables.Designer.cs @@ -0,0 +1,1369 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261021155622_AddNpmTables")] + partial class AddNpmTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261021155622_AddNpmTables.cs b/src/BaGet.Database.Sqlite/Migrations/20261021155622_AddNpmTables.cs new file mode 100644 index 000000000..5d5140ce5 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261021155622_AddNpmTables.cs @@ -0,0 +1,109 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddNpmTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "NpmPackages", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + Name = table.Column(type: "TEXT", maxLength: 214, nullable: false), + Created = table.Column(type: "TEXT", nullable: false), + Modified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmPackages", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "NpmDistTags", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PackageKey = table.Column(type: "INTEGER", nullable: false), + Tag = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Version = table.Column(type: "TEXT", maxLength: 256, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmDistTags", x => x.Key); + table.ForeignKey( + name: "FK_NpmDistTags_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "NpmVersions", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PackageKey = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Integrity = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Shasum = table.Column(type: "TEXT", maxLength: 40, nullable: false), + TarballSize = table.Column(type: "INTEGER", nullable: false), + Manifest = table.Column(type: "TEXT", nullable: false), + Deprecated = table.Column(type: "TEXT", nullable: true), + Published = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NpmVersions", x => x.Key); + table.ForeignKey( + name: "FK_NpmVersions_NpmPackages_PackageKey", + column: x => x.PackageKey, + principalTable: "NpmPackages", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_NpmDistTags_PackageKey_Tag", + table: "NpmDistTags", + columns: new[] { "PackageKey", "Tag" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmPackages_RepositoryKey_Name", + table: "NpmPackages", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_NpmVersions_PackageKey_Version", + table: "NpmVersions", + columns: new[] { "PackageKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "NpmDistTags"); + + migrationBuilder.DropTable( + name: "NpmVersions"); + + migrationBuilder.DropTable( + name: "NpmPackages"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261022010629_AddMavenTables.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261022010629_AddMavenTables.Designer.cs new file mode 100644 index 000000000..38a94dd40 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261022010629_AddMavenTables.Designer.cs @@ -0,0 +1,1529 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261022010629_AddMavenTables")] + partial class AddMavenTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261022010629_AddMavenTables.cs b/src/BaGet.Database.Sqlite/Migrations/20261022010629_AddMavenTables.cs new file mode 100644 index 000000000..16921fc3c --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261022010629_AddMavenTables.cs @@ -0,0 +1,119 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddMavenTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MavenArtifacts", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + GroupId = table.Column(type: "TEXT", maxLength: 200, nullable: false), + ArtifactId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Created = table.Column(type: "TEXT", nullable: false), + Modified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenArtifacts", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "MavenVersions", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ArtifactKey = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "TEXT", maxLength: 128, nullable: false), + IsSnapshot = table.Column(type: "INTEGER", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 512, nullable: true), + Description = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + Packaging = table.Column(type: "TEXT", maxLength: 64, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Modified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenVersions", x => x.Key); + table.ForeignKey( + name: "FK_MavenVersions_MavenArtifacts_ArtifactKey", + column: x => x.ArtifactKey, + principalTable: "MavenArtifacts", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "MavenFiles", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + VersionKey = table.Column(type: "INTEGER", nullable: false), + FileName = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Classifier = table.Column(type: "TEXT", maxLength: 64, nullable: true), + Extension = table.Column(type: "TEXT", maxLength: 64, nullable: false), + SnapshotTimestamp = table.Column(type: "TEXT", maxLength: 15, nullable: true), + SnapshotBuild = table.Column(type: "INTEGER", nullable: false), + Size = table.Column(type: "INTEGER", nullable: false), + Sha1 = table.Column(type: "TEXT", maxLength: 40, nullable: false), + Md5 = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Sha256 = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Sha512 = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MavenFiles", x => x.Key); + table.ForeignKey( + name: "FK_MavenFiles_MavenVersions_VersionKey", + column: x => x.VersionKey, + principalTable: "MavenVersions", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_MavenArtifacts_RepositoryKey_GroupId_ArtifactId", + table: "MavenArtifacts", + columns: new[] { "RepositoryKey", "GroupId", "ArtifactId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenFiles_VersionKey_FileName", + table: "MavenFiles", + columns: new[] { "VersionKey", "FileName" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MavenVersions_ArtifactKey_Version", + table: "MavenVersions", + columns: new[] { "ArtifactKey", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MavenFiles"); + + migrationBuilder.DropTable( + name: "MavenVersions"); + + migrationBuilder.DropTable( + name: "MavenArtifacts"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261022062035_AddOciTables.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261022062035_AddOciTables.Designer.cs new file mode 100644 index 000000000..385704383 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261022062035_AddOciTables.Designer.cs @@ -0,0 +1,1774 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261022062035_AddOciTables")] + partial class AddOciTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261022062035_AddOciTables.cs b/src/BaGet.Database.Sqlite/Migrations/20261022062035_AddOciTables.cs new file mode 100644 index 000000000..fa040d64e --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261022062035_AddOciTables.cs @@ -0,0 +1,225 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddOciTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "OciBlobs", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + Digest = table.Column(type: "TEXT", maxLength: 140, nullable: false), + Size = table.Column(type: "INTEGER", nullable: false), + RefCount = table.Column(type: "INTEGER", nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobs", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "OciRepositories", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + Name = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Created = table.Column(type: "TEXT", nullable: false), + Modified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciRepositories", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "OciBlobLinks", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ImageKey = table.Column(type: "INTEGER", nullable: false), + BlobKey = table.Column(type: "INTEGER", nullable: false), + Manifests = table.Column(type: "INTEGER", nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciBlobLinks", x => x.Key); + table.ForeignKey( + name: "FK_OciBlobLinks_OciBlobs_BlobKey", + column: x => x.BlobKey, + principalTable: "OciBlobs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_OciBlobLinks_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciManifests", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ImageKey = table.Column(type: "INTEGER", nullable: false), + Digest = table.Column(type: "TEXT", maxLength: 140, nullable: false), + MediaType = table.Column(type: "TEXT", maxLength: 255, nullable: false), + ArtifactType = table.Column(type: "TEXT", maxLength: 255, nullable: true), + SubjectDigest = table.Column(type: "TEXT", maxLength: 140, nullable: true), + Size = table.Column(type: "INTEGER", nullable: false), + Content = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciManifests", x => x.Key); + table.ForeignKey( + name: "FK_OciManifests_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciUploads", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ImageKey = table.Column(type: "INTEGER", nullable: false), + Reference = table.Column(type: "TEXT", maxLength: 128, nullable: false), + StorageUploadId = table.Column(type: "TEXT", maxLength: 512, nullable: false), + Created = table.Column(type: "TEXT", nullable: false), + Updated = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciUploads", x => x.Key); + table.ForeignKey( + name: "FK_OciUploads_OciRepositories_ImageKey", + column: x => x.ImageKey, + principalTable: "OciRepositories", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OciTags", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ImageKey = table.Column(type: "INTEGER", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + ManifestKey = table.Column(type: "INTEGER", nullable: false), + Updated = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OciTags", x => x.Key); + table.ForeignKey( + name: "FK_OciTags_OciManifests_ManifestKey", + column: x => x.ManifestKey, + principalTable: "OciManifests", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_BlobKey", + table: "OciBlobLinks", + column: "BlobKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobLinks_ImageKey_BlobKey", + table: "OciBlobLinks", + columns: new[] { "ImageKey", "BlobKey" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciBlobs_RepositoryKey_Digest", + table: "OciBlobs", + columns: new[] { "RepositoryKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_Digest", + table: "OciManifests", + columns: new[] { "ImageKey", "Digest" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciManifests_ImageKey_SubjectDigest", + table: "OciManifests", + columns: new[] { "ImageKey", "SubjectDigest" }); + + migrationBuilder.CreateIndex( + name: "IX_OciRepositories_RepositoryKey_Name", + table: "OciRepositories", + columns: new[] { "RepositoryKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ImageKey_Name", + table: "OciTags", + columns: new[] { "ImageKey", "Name" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_OciTags_ManifestKey", + table: "OciTags", + column: "ManifestKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_ImageKey", + table: "OciUploads", + column: "ImageKey"); + + migrationBuilder.CreateIndex( + name: "IX_OciUploads_Reference", + table: "OciUploads", + column: "Reference", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OciBlobLinks"); + + migrationBuilder.DropTable( + name: "OciTags"); + + migrationBuilder.DropTable( + name: "OciUploads"); + + migrationBuilder.DropTable( + name: "OciBlobs"); + + migrationBuilder.DropTable( + name: "OciManifests"); + + migrationBuilder.DropTable( + name: "OciRepositories"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261023010826_AddRetention.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261023010826_AddRetention.Designer.cs new file mode 100644 index 000000000..2b59c50f8 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261023010826_AddRetention.Designer.cs @@ -0,0 +1,1922 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261023010826_AddRetention")] + partial class AddRetention + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261023010826_AddRetention.cs b/src/BaGet.Database.Sqlite/Migrations/20261023010826_AddRetention.cs new file mode 100644 index 000000000..e63f1aaf3 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261023010826_AddRetention.cs @@ -0,0 +1,120 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddRetention : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ArtifactUsages", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + Name = table.Column(type: "TEXT", maxLength: 340, nullable: false), + Version = table.Column(type: "TEXT", maxLength: 128, nullable: false), + LastUsed = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ArtifactUsages", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "RetentionHolds", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + Name = table.Column(type: "TEXT", maxLength: 340, nullable: false), + Version = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Reason = table.Column(type: "TEXT", maxLength: 512, nullable: true), + CreatedBy = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Created = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionHolds", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "RetentionPolicies", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + RepositoryKey = table.Column(type: "INTEGER", nullable: true), + ProjectKey = table.Column(type: "INTEGER", nullable: true), + Enabled = table.Column(type: "INTEGER", nullable: false), + NamePatterns = table.Column(type: "TEXT", maxLength: 1024, nullable: true), + KeepLast = table.Column(type: "INTEGER", nullable: true), + OlderThanDays = table.Column(type: "INTEGER", nullable: true), + UnusedDays = table.Column(type: "INTEGER", nullable: true), + PrereleaseOnly = table.Column(type: "INTEGER", nullable: false), + CacheLimitBytes = table.Column(type: "INTEGER", nullable: true), + UntaggedAfterDays = table.Column(type: "INTEGER", nullable: true), + CollectGarbage = table.Column(type: "INTEGER", nullable: false), + ScheduleHours = table.Column(type: "INTEGER", nullable: true), + ScheduleStart = table.Column(type: "TEXT", nullable: true), + LastRun = table.Column(type: "TEXT", nullable: true), + LastResult = table.Column(type: "TEXT", maxLength: 1024, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Modified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RetentionPolicies", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_ArtifactUsages_RepositoryKey_Name_Version", + table: "ArtifactUsages", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionHolds_RepositoryKey_Name_Version", + table: "RetentionHolds", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_Name", + table: "RetentionPolicies", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_RetentionPolicies_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ArtifactUsages"); + + migrationBuilder.DropTable( + name: "RetentionHolds"); + + migrationBuilder.DropTable( + name: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261023021730_AddScanning.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261023021730_AddScanning.Designer.cs new file mode 100644 index 000000000..fafe60c84 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261023021730_AddScanning.Designer.cs @@ -0,0 +1,2078 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261023021730_AddScanning")] + partial class AddScanning + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261023021730_AddScanning.cs b/src/BaGet.Database.Sqlite/Migrations/20261023021730_AddScanning.cs new file mode 100644 index 000000000..75c7c4f5f --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261023021730_AddScanning.cs @@ -0,0 +1,129 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddScanning : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Source", + table: "PackageVulnerabilities", + type: "TEXT", + maxLength: 32, + nullable: true); + + migrationBuilder.CreateTable( + name: "ScanPolicies", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: true), + ProjectKey = table.Column(type: "INTEGER", nullable: true), + WarnSeverity = table.Column(type: "INTEGER", nullable: true), + BlockDownloadSeverity = table.Column(type: "INTEGER", nullable: true), + BlockDeploySeverity = table.Column(type: "INTEGER", nullable: true), + BlockUnscanned = table.Column(type: "INTEGER", nullable: false), + Modified = table.Column(type: "TEXT", nullable: false), + ModifiedBy = table.Column(type: "TEXT", maxLength: 256, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanPolicies", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ScanResults", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RepositoryKey = table.Column(type: "INTEGER", nullable: false, defaultValue: 1), + Name = table.Column(type: "TEXT", maxLength: 400, nullable: false), + Version = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Scanner = table.Column(type: "TEXT", maxLength: 32, nullable: false), + ScannedAt = table.Column(type: "TEXT", nullable: true), + Attempted = table.Column(type: "TEXT", nullable: false), + Error = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + Highest = table.Column(type: "INTEGER", nullable: false), + FindingCount = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanResults", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ScanFindings", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ResultKey = table.Column(type: "INTEGER", nullable: false), + VulnerabilityId = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Component = table.Column(type: "TEXT", maxLength: 400, nullable: false), + ComponentVersion = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Severity = table.Column(type: "INTEGER", nullable: false), + Summary = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + AdvisoryUrl = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + FixedVersion = table.Column(type: "TEXT", maxLength: 200, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScanFindings", x => x.Key); + table.ForeignKey( + name: "FK_ScanFindings_ScanResults_ResultKey", + column: x => x.ResultKey, + principalTable: "ScanResults", + principalColumn: "Key", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScanFindings_ResultKey", + table: "ScanFindings", + column: "ResultKey"); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScanPolicies_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScanResults_RepositoryKey_Name_Version", + table: "ScanResults", + columns: new[] { "RepositoryKey", "Name", "Version" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScanFindings"); + + migrationBuilder.DropTable( + name: "ScanPolicies"); + + migrationBuilder.DropTable( + name: "ScanResults"); + + migrationBuilder.DropColumn( + name: "Source", + table: "PackageVulnerabilities"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261023050008_AddRetentionUnusedSince.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261023050008_AddRetentionUnusedSince.Designer.cs new file mode 100644 index 000000000..a438b6a19 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261023050008_AddRetentionUnusedSince.Designer.cs @@ -0,0 +1,2081 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261023050008_AddRetentionUnusedSince")] + partial class AddRetentionUnusedSince + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedSince") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261023050008_AddRetentionUnusedSince.cs b/src/BaGet.Database.Sqlite/Migrations/20261023050008_AddRetentionUnusedSince.cs new file mode 100644 index 000000000..f227ecd66 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261023050008_AddRetentionUnusedSince.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddRetentionUnusedSince : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "UnusedSince", + table: "RetentionPolicies", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "UnusedSince", + table: "RetentionPolicies"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261024001349_AddReplication.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261024001349_AddReplication.Designer.cs new file mode 100644 index 000000000..e187d2469 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261024001349_AddReplication.Designer.cs @@ -0,0 +1,2256 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261024001349_AddReplication")] + partial class AddReplication + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Conflict") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Direction") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("OnDeploy") + .HasColumnType("INTEGER"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("PropagateDeletes") + .HasColumnType("INTEGER"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleMinutes") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Synced") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Bytes") + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Conflicts") + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Examined") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("Finished") + .HasColumnType("TEXT"); + + b.Property("ResumedFrom") + .HasColumnType("INTEGER"); + + b.Property("Skipped") + .HasColumnType("INTEGER"); + + b.Property("Started") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("Transferred") + .HasColumnType("INTEGER"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedSince") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261024001349_AddReplication.cs b/src/BaGet.Database.Sqlite/Migrations/20261024001349_AddReplication.cs new file mode 100644 index 000000000..9d432d3af --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261024001349_AddReplication.cs @@ -0,0 +1,123 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddReplication : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ReplicationConfigs", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + RepositoryKey = table.Column(type: "INTEGER", nullable: false), + Direction = table.Column(type: "INTEGER", nullable: false), + PeerUrl = table.Column(type: "TEXT", maxLength: 2048, nullable: false), + PeerRepository = table.Column(type: "TEXT", maxLength: 256, nullable: false), + ProtectedApiKey = table.Column(type: "TEXT", maxLength: 2048, nullable: true), + Enabled = table.Column(type: "INTEGER", nullable: false), + OnDeploy = table.Column(type: "INTEGER", nullable: false), + ScheduleMinutes = table.Column(type: "INTEGER", nullable: true), + PropagateDeletes = table.Column(type: "INTEGER", nullable: false), + Conflict = table.Column(type: "INTEGER", nullable: false), + ScheduleStart = table.Column(type: "TEXT", nullable: true), + LastRun = table.Column(type: "TEXT", nullable: true), + LastResult = table.Column(type: "TEXT", maxLength: 1024, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Modified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationConfigs", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ReplicationItems", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ConfigKey = table.Column(type: "INTEGER", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 340, nullable: false), + Version = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Part = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Digest = table.Column(type: "TEXT", maxLength: 160, nullable: true), + Synced = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationItems", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "ReplicationRuns", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ConfigKey = table.Column(type: "INTEGER", nullable: false), + Status = table.Column(type: "INTEGER", nullable: false), + Trigger = table.Column(type: "TEXT", maxLength: 32, nullable: true), + Actor = table.Column(type: "TEXT", maxLength: 256, nullable: true), + ResumedFrom = table.Column(type: "INTEGER", nullable: true), + Started = table.Column(type: "TEXT", nullable: false), + Finished = table.Column(type: "TEXT", nullable: true), + Examined = table.Column(type: "INTEGER", nullable: false), + Transferred = table.Column(type: "INTEGER", nullable: false), + Skipped = table.Column(type: "INTEGER", nullable: false), + Deleted = table.Column(type: "INTEGER", nullable: false), + Conflicts = table.Column(type: "INTEGER", nullable: false), + Failures = table.Column(type: "INTEGER", nullable: false), + Bytes = table.Column(type: "INTEGER", nullable: false), + Error = table.Column(type: "TEXT", maxLength: 1024, nullable: true), + Detail = table.Column(type: "TEXT", maxLength: 4000, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ReplicationRuns", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_Name", + table: "ReplicationConfigs", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationConfigs_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey"); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationItems_ConfigKey_Name_Version_Part", + table: "ReplicationItems", + columns: new[] { "ConfigKey", "Name", "Version", "Part" }); + + migrationBuilder.CreateIndex( + name: "IX_ReplicationRuns_ConfigKey_Started", + table: "ReplicationRuns", + columns: new[] { "ConfigKey", "Started" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ReplicationConfigs"); + + migrationBuilder.DropTable( + name: "ReplicationItems"); + + migrationBuilder.DropTable( + name: "ReplicationRuns"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261024014413_AddDataProtectionKeys.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261024014413_AddDataProtectionKeys.Designer.cs new file mode 100644 index 000000000..92bb77ebb --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261024014413_AddDataProtectionKeys.Designer.cs @@ -0,0 +1,2274 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261024014413_AddDataProtectionKeys")] + partial class AddDataProtectionKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Xml") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Conflict") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Direction") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("OnDeploy") + .HasColumnType("INTEGER"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("PropagateDeletes") + .HasColumnType("INTEGER"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleMinutes") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Synced") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Bytes") + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Conflicts") + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Examined") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("Finished") + .HasColumnType("TEXT"); + + b.Property("ResumedFrom") + .HasColumnType("INTEGER"); + + b.Property("Skipped") + .HasColumnType("INTEGER"); + + b.Property("Started") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("Transferred") + .HasColumnType("INTEGER"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedSince") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261024014413_AddDataProtectionKeys.cs b/src/BaGet.Database.Sqlite/Migrations/20261024014413_AddDataProtectionKeys.cs new file mode 100644 index 000000000..01508b00e --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261024014413_AddDataProtectionKeys.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddDataProtectionKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "DataProtectionKeys", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + FriendlyName = table.Column(type: "TEXT", maxLength: 200, nullable: true), + Xml = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DataProtectionKeys", x => x.Key); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DataProtectionKeys"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261025012659_AddUserPendingApproval.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261025012659_AddUserPendingApproval.Designer.cs new file mode 100644 index 000000000..b6e451b48 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261025012659_AddUserPendingApproval.Designer.cs @@ -0,0 +1,2277 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261025012659_AddUserPendingApproval")] + partial class AddUserPendingApproval + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.13"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PendingApproval") + .HasColumnType("INTEGER"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Xml") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Conflict") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Direction") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("OnDeploy") + .HasColumnType("INTEGER"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("PropagateDeletes") + .HasColumnType("INTEGER"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleMinutes") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Synced") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Bytes") + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Conflicts") + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Examined") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("Finished") + .HasColumnType("TEXT"); + + b.Property("ResumedFrom") + .HasColumnType("INTEGER"); + + b.Property("Skipped") + .HasColumnType("INTEGER"); + + b.Property("Started") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("Transferred") + .HasColumnType("INTEGER"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedSince") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261025012659_AddUserPendingApproval.cs b/src/BaGet.Database.Sqlite/Migrations/20261025012659_AddUserPendingApproval.cs new file mode 100644 index 000000000..438c80882 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261025012659_AddUserPendingApproval.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddUserPendingApproval : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PendingApproval", + table: "AspNetUsers", + type: "INTEGER", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PendingApproval", + table: "AspNetUsers"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261025035609_AddOwnershipForeignKeys.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261025035609_AddOwnershipForeignKeys.Designer.cs new file mode 100644 index 000000000..52cb3d444 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261025035609_AddOwnershipForeignKeys.Designer.cs @@ -0,0 +1,2497 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261025035609_AddOwnershipForeignKeys")] + partial class AddOwnershipForeignKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.13"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PendingApproval") + .HasColumnType("INTEGER"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Xml") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Conflict") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Direction") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("OnDeploy") + .HasColumnType("INTEGER"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("PropagateDeletes") + .HasColumnType("INTEGER"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleMinutes") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Synced") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Bytes") + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Conflicts") + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Examined") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("Finished") + .HasColumnType("TEXT"); + + b.Property("ResumedFrom") + .HasColumnType("INTEGER"); + + b.Property("Skipped") + .HasColumnType("INTEGER"); + + b.Property("Started") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("Transferred") + .HasColumnType("INTEGER"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedSince") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261025035609_AddOwnershipForeignKeys.cs b/src/BaGet.Database.Sqlite/Migrations/20261025035609_AddOwnershipForeignKeys.cs new file mode 100644 index 000000000..b2c18b456 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261025035609_AddOwnershipForeignKeys.cs @@ -0,0 +1,367 @@ +using BaGet.Core; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddOwnershipForeignKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // Rows that pointed at nothing are removed first (children before parents), or the constraints below could not be created. + // On SQLite this runs before the table rebuilds that add the foreign keys. + foreach (var sql in OwnershipOrphanCleanup.Statements(OwnershipEngine.Sqlite)) + { + migrationBuilder.Sql(sql); + } + + migrationBuilder.CreateIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories", + column: "ProjectKey"); + + migrationBuilder.CreateIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey"); + + migrationBuilder.AddForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags", + column: "ImageKey", + principalTable: "OciRepositories", + principalColumn: "Key"); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns", + column: "ConfigKey", + principalTable: "ReplicationConfigs", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies", + column: "ProjectKey", + principalTable: "Projects", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults", + column: "RepositoryKey", + principalTable: "Repositories", + principalColumn: "Key", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_AbuseReports_Repositories_RepositoryKey", + table: "AbuseReports"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeyRepositories_Repositories_RepositoryKey", + table: "ApiKeyRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_ArtifactUsages_Repositories_RepositoryKey", + table: "ArtifactUsages"); + + migrationBuilder.DropForeignKey( + name: "FK_CatalogLeafs_Repositories_RepositoryKey", + table: "CatalogLeafs"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_MavenArtifacts_Repositories_RepositoryKey", + table: "MavenArtifacts"); + + migrationBuilder.DropForeignKey( + name: "FK_NpmPackages_Repositories_RepositoryKey", + table: "NpmPackages"); + + migrationBuilder.DropForeignKey( + name: "FK_OciBlobs_Repositories_RepositoryKey", + table: "OciBlobs"); + + migrationBuilder.DropForeignKey( + name: "FK_OciRepositories_Repositories_RepositoryKey", + table: "OciRepositories"); + + migrationBuilder.DropForeignKey( + name: "FK_OciTags_OciRepositories_ImageKey", + table: "OciTags"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageOwners_Repositories_RepositoryKey", + table: "PackageOwners"); + + migrationBuilder.DropForeignKey( + name: "FK_Packages_Repositories_RepositoryKey", + table: "Packages"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageSymbols_Repositories_RepositoryKey", + table: "PackageSymbols"); + + migrationBuilder.DropForeignKey( + name: "FK_PackageValidations_Repositories_RepositoryKey", + table: "PackageValidations"); + + migrationBuilder.DropForeignKey( + name: "FK_PermissionTargets_Projects_ProjectKey", + table: "PermissionTargets"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationConfigs_Repositories_RepositoryKey", + table: "ReplicationConfigs"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationItems_ReplicationConfigs_ConfigKey", + table: "ReplicationItems"); + + migrationBuilder.DropForeignKey( + name: "FK_ReplicationRuns_ReplicationConfigs_ConfigKey", + table: "ReplicationRuns"); + + migrationBuilder.DropForeignKey( + name: "FK_Repositories_Projects_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionHolds_Repositories_RepositoryKey", + table: "RetentionHolds"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Projects_ProjectKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_RetentionPolicies_Repositories_RepositoryKey", + table: "RetentionPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Projects_ProjectKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanPolicies_Repositories_RepositoryKey", + table: "ScanPolicies"); + + migrationBuilder.DropForeignKey( + name: "FK_ScanResults_Repositories_RepositoryKey", + table: "ScanResults"); + + migrationBuilder.DropIndex( + name: "IX_Repositories_ProjectKey", + table: "Repositories"); + + migrationBuilder.DropIndex( + name: "IX_PermissionTargets_ProjectKey", + table: "PermissionTargets"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261025222337_RenameAspNetTables.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261025222337_RenameAspNetTables.Designer.cs new file mode 100644 index 000000000..ab1a24dae --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261025222337_RenameAspNetTables.Designer.cs @@ -0,0 +1,2497 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261025222337_RenameAspNetTables")] + partial class RenameAspNetTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.13"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Subject") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Created"); + + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ApiKeyKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey"); + + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); + + b.ToTable("ApiKeyRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastUsed") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ArtifactUsages"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PendingApproval") + .HasColumnType("INTEGER"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Xml") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("BaGet.Core.Group", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Conflict") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Direction") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("OnDeploy") + .HasColumnType("INTEGER"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("PropagateDeletes") + .HasColumnType("INTEGER"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleMinutes") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Synced") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Bytes") + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Conflicts") + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Examined") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("Finished") + .HasColumnType("TEXT"); + + b.Property("ResumedFrom") + .HasColumnType("INTEGER"); + + b.Property("Skipped") + .HasColumnType("INTEGER"); + + b.Property("Started") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("Transferred") + .HasColumnType("INTEGER"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedSince") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261025222337_RenameAspNetTables.cs b/src/BaGet.Database.Sqlite/Migrations/20261025222337_RenameAspNetTables.cs new file mode 100644 index 000000000..ac8ba0100 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261025222337_RenameAspNetTables.cs @@ -0,0 +1,456 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class RenameAspNetTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims"); + + migrationBuilder.RenameTable( + name: "AspNetUserTokens", + newName: "UserTokens"); + + migrationBuilder.RenameTable( + name: "AspNetUsers", + newName: "Users"); + + migrationBuilder.RenameTable( + name: "AspNetUserRoles", + newName: "UserRoles"); + + migrationBuilder.RenameTable( + name: "AspNetUserLogins", + newName: "UserLogins"); + + migrationBuilder.RenameTable( + name: "AspNetUserClaims", + newName: "UserClaims"); + + migrationBuilder.RenameTable( + name: "AspNetRoles", + newName: "Roles"); + + migrationBuilder.RenameTable( + name: "AspNetRoleClaims", + newName: "RoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "UserRoles", + newName: "IX_UserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserLogins_UserId", + table: "UserLogins", + newName: "IX_UserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetUserClaims_UserId", + table: "UserClaims", + newName: "IX_UserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "RoleClaims", + newName: "IX_RoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_Users", + table: "Users", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_Roles", + table: "Roles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles", + column: "RoleId", + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens", + column: "UserId", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ApiKeys_Users_UserId", + table: "ApiKeys"); + + migrationBuilder.DropForeignKey( + name: "FK_GroupMembers_Users_UserId", + table: "GroupMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_OrganizationMembers_Users_UserId", + table: "OrganizationMembers"); + + migrationBuilder.DropForeignKey( + name: "FK_RoleClaims_Roles_RoleId", + table: "RoleClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserClaims_Users_UserId", + table: "UserClaims"); + + migrationBuilder.DropForeignKey( + name: "FK_UserLogins_Users_UserId", + table: "UserLogins"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Roles_RoleId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserRoles_Users_UserId", + table: "UserRoles"); + + migrationBuilder.DropForeignKey( + name: "FK_UserTokens_Users_UserId", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserTokens", + table: "UserTokens"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Users", + table: "Users"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserRoles", + table: "UserRoles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserLogins", + table: "UserLogins"); + + migrationBuilder.DropPrimaryKey( + name: "PK_UserClaims", + table: "UserClaims"); + + migrationBuilder.DropPrimaryKey( + name: "PK_Roles", + table: "Roles"); + + migrationBuilder.DropPrimaryKey( + name: "PK_RoleClaims", + table: "RoleClaims"); + + migrationBuilder.RenameTable( + name: "UserTokens", + newName: "AspNetUserTokens"); + + migrationBuilder.RenameTable( + name: "Users", + newName: "AspNetUsers"); + + migrationBuilder.RenameTable( + name: "UserRoles", + newName: "AspNetUserRoles"); + + migrationBuilder.RenameTable( + name: "UserLogins", + newName: "AspNetUserLogins"); + + migrationBuilder.RenameTable( + name: "UserClaims", + newName: "AspNetUserClaims"); + + migrationBuilder.RenameTable( + name: "Roles", + newName: "AspNetRoles"); + + migrationBuilder.RenameTable( + name: "RoleClaims", + newName: "AspNetRoleClaims"); + + migrationBuilder.RenameIndex( + name: "IX_UserRoles_RoleId", + table: "AspNetUserRoles", + newName: "IX_AspNetUserRoles_RoleId"); + + migrationBuilder.RenameIndex( + name: "IX_UserLogins_UserId", + table: "AspNetUserLogins", + newName: "IX_AspNetUserLogins_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_UserClaims_UserId", + table: "AspNetUserClaims", + newName: "IX_AspNetUserClaims_UserId"); + + migrationBuilder.RenameIndex( + name: "IX_RoleClaims_RoleId", + table: "AspNetRoleClaims", + newName: "IX_AspNetRoleClaims_RoleId"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserTokens", + table: "AspNetUserTokens", + columns: new[] { "UserId", "LoginProvider", "Name" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUsers", + table: "AspNetUsers", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserRoles", + table: "AspNetUserRoles", + columns: new[] { "UserId", "RoleId" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserLogins", + table: "AspNetUserLogins", + columns: new[] { "LoginProvider", "ProviderKey" }); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetUserClaims", + table: "AspNetUserClaims", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoles", + table: "AspNetRoles", + column: "Id"); + + migrationBuilder.AddPrimaryKey( + name: "PK_AspNetRoleClaims", + table: "AspNetRoleClaims", + column: "Id"); + + migrationBuilder.AddForeignKey( + name: "FK_ApiKeys_AspNetUsers_UserId", + table: "ApiKeys", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + table: "AspNetRoleClaims", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + table: "AspNetUserClaims", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + table: "AspNetUserLogins", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId", + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + table: "AspNetUserRoles", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + table: "AspNetUserTokens", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_GroupMembers_AspNetUsers_UserId", + table: "GroupMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_OrganizationMembers_AspNetUsers_UserId", + table: "OrganizationMembers", + column: "UserId", + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs b/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs index ddac0c1e6..a36a8f924 100644 --- a/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs +++ b/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs @@ -5,6 +5,8 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +#nullable disable + namespace BaGet.Database.Sqlite.Migrations { [DbContext(typeof(SqliteContext))] @@ -13,223 +15,2478 @@ partial class SqliteContextModelSnapshot : ModelSnapshot protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "3.1.18"); + modelBuilder.HasAnnotation("ProductVersion", "10.0.13"); - modelBuilder.Entity("BaGet.Core.Package", b => + modelBuilder.Entity("BaGet.Core.AbuseReport", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); - b.Property("Authors") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.Property("Created") + .HasColumnType("TEXT"); - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); - b.Property("Downloads") - .HasColumnType("INTEGER"); + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); - b.Property("HasEmbeddedIcon") - .HasColumnType("INTEGER"); + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); - b.Property("HasReadme") - .HasColumnType("INTEGER"); + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); - b.Property("IconUrl") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); - b.Property("Id") - .IsRequired() - .HasColumnType("TEXT COLLATE NOCASE") - .HasMaxLength(128); + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); - b.Property("IsPrerelease") - .HasColumnType("INTEGER"); + b.Property("Resolved") + .HasColumnType("TEXT"); - b.Property("Language") - .HasColumnType("TEXT") - .HasMaxLength(20); + b.HasKey("Key"); - b.Property("LicenseUrl") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.HasIndex("RepositoryKey", "PackageId"); - b.Property("Listed") - .HasColumnType("INTEGER"); + b.ToTable("AbuseReports"); + }); - b.Property("MinClientVersion") - .HasColumnType("TEXT") - .HasMaxLength(44); + modelBuilder.Entity("BaGet.Core.AccessAuditEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); - b.Property("NormalizedVersionString") + b.Property("Action") .IsRequired() - .HasColumnName("Version") - .HasColumnType("TEXT COLLATE NOCASE") - .HasMaxLength(64); + .HasMaxLength(64) + .HasColumnType("TEXT"); - b.Property("OriginalVersionString") - .HasColumnName("OriginalVersion") - .HasColumnType("TEXT") - .HasMaxLength(64); + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); - b.Property("ProjectUrl") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.Property("Created") + .HasColumnType("TEXT"); - b.Property("Published") + b.Property("Details") + .HasMaxLength(4000) .HasColumnType("TEXT"); - b.Property("ReleaseNotes") - .HasColumnName("ReleaseNotes") + b.Property("Subject") + .HasMaxLength(256) .HasColumnType("TEXT"); - b.Property("RepositoryType") - .HasColumnType("TEXT") - .HasMaxLength(100); + b.HasKey("Key"); - b.Property("RepositoryUrl") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.HasIndex("Created"); - b.Property("RequireLicenseAcceptance") + b.ToTable("AccessAuditEntries"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); - b.Property("RowVersion") - .IsConcurrencyToken() - .ValueGeneratedOnAddOrUpdate() - .HasColumnType("BLOB"); + b.Property("Created") + .HasColumnType("TEXT"); - b.Property("SemVerLevel") - .HasColumnType("INTEGER"); + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); - b.Property("Summary") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.Property("Expires") + .HasColumnType("TEXT"); - b.Property("Tags") - .HasColumnType("TEXT") - .HasMaxLength(4000); + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); - b.Property("Title") - .HasColumnType("TEXT") - .HasMaxLength(256); + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); - b.HasKey("Key"); + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); - b.HasIndex("Id"); + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); - b.HasIndex("Id", "NormalizedVersionString") + b.HasIndex("HashedKey") .IsUnique(); - b.ToTable("Packages"); + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); - b.Property("Id") - .HasColumnType("TEXT COLLATE NOCASE") - .HasMaxLength(128); - - b.Property("PackageKey") + b.Property("ApiKeyKey") .HasColumnType("INTEGER"); - b.Property("TargetFramework") - .HasColumnType("TEXT") - .HasMaxLength(256); - - b.Property("VersionRange") - .HasColumnType("TEXT") - .HasMaxLength(256); + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); b.HasKey("Key"); - b.HasIndex("Id"); + b.HasIndex("RepositoryKey"); - b.HasIndex("PackageKey"); + b.HasIndex("ApiKeyKey", "RepositoryKey") + .IsUnique(); - b.ToTable("PackageDependencies"); + b.ToTable("ApiKeyRepositories"); }); - modelBuilder.Entity("BaGet.Core.PackageType", b => + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); + b.Property("LastUsed") + .HasColumnType("TEXT"); + b.Property("Name") - .HasColumnType("TEXT COLLATE NOCASE") - .HasMaxLength(512); + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); - b.Property("PackageKey") - .HasColumnType("INTEGER"); + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); b.Property("Version") - .HasColumnType("TEXT") - .HasMaxLength(64); + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); b.HasKey("Key"); - b.HasIndex("Name"); + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); - b.HasIndex("PackageKey"); + b.ToTable("ArtifactUsages"); + }); - b.ToTable("PackageTypes"); + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("IsAdministrator") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PendingApproval") + .HasColumnType("INTEGER"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("Users", (string)null); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => { b.Property("Key") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); - b.Property("Moniker") - .HasColumnType("TEXT COLLATE NOCASE") - .HasMaxLength(256); + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); - b.Property("PackageKey") - .HasColumnType("INTEGER"); + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); b.HasKey("Key"); - b.HasIndex("Moniker"); + b.HasIndex("CommitId") + .IsUnique(); - b.HasIndex("PackageKey"); + b.HasIndex("RepositoryKey"); - b.ToTable("TargetFrameworks"); + b.ToTable("CatalogLeafs"); }); - modelBuilder.Entity("BaGet.Core.PackageDependency", b => + modelBuilder.Entity("BaGet.Core.DataProtectionKeyEntry", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("Dependencies") - .HasForeignKey("PackageKey"); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("FriendlyName") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Xml") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("DataProtectionKeys"); }); - modelBuilder.Entity("BaGet.Core.PackageType", b => + modelBuilder.Entity("BaGet.Core.Group", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("PackageTypes") - .HasForeignKey("PackageKey") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Groups"); }); - modelBuilder.Entity("BaGet.Core.TargetFramework", b => + modelBuilder.Entity("BaGet.Core.GroupMember", b => { - b.HasOne("BaGet.Core.Package", "Package") - .WithMany("TargetFrameworks") - .HasForeignKey("PackageKey") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("GroupKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("UserId"); + + b.HasIndex("GroupKey", "UserId") + .IsUnique(); + + b.ToTable("GroupMembers"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("GroupId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "GroupId", "ArtifactId") + .IsUnique(); + + b.ToTable("MavenArtifacts"); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Classifier") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Md5") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Sha1") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Sha512") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SnapshotBuild") + .HasColumnType("INTEGER"); + + b.Property("SnapshotTimestamp") + .HasMaxLength(15) + .HasColumnType("TEXT"); + + b.Property("VersionKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("VersionKey", "FileName") + .IsUnique(); + + b.ToTable("MavenFiles"); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsSnapshot") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Packaging") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ArtifactKey", "Version") + .IsUnique(); + + b.ToTable("MavenVersions"); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Tag") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Tag") + .IsUnique(); + + b.ToTable("NpmDistTags"); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(214) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("NpmPackages"); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Deprecated") + .HasColumnType("TEXT"); + + b.Property("Integrity") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Manifest") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("Shasum") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT"); + + b.Property("TarballSize") + .HasColumnType("INTEGER"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey", "Version") + .IsUnique(); + + b.ToTable("NpmVersions"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("RefCount") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Digest") + .IsUnique(); + + b.ToTable("OciBlobs"); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlobKey") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Manifests") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("BlobKey"); + + b.HasIndex("ImageKey", "BlobKey") + .IsUnique(); + + b.ToTable("OciBlobLinks"); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArtifactType") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Digest") + .IsRequired() + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("MediaType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("SubjectDigest") + .HasMaxLength(140) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey", "Digest") + .IsUnique(); + + b.HasIndex("ImageKey", "SubjectDigest"); + + b.ToTable("OciManifests"); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name") + .IsUnique(); + + b.ToTable("OciRepositories"); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("ManifestKey") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ManifestKey"); + + b.HasIndex("ImageKey", "Name") + .IsUnique(); + + b.ToTable("OciTags"); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ImageKey") + .HasColumnType("INTEGER"); + + b.Property("Reference") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("StorageUploadId") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Updated") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ImageKey"); + + b.HasIndex("Reference") + .IsUnique(); + + b.ToTable("OciUploads"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("RepositoryKey", "Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("SymbolKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "FileName", "SymbolKey"); + + b.HasIndex("RepositoryKey", "PackageId", "PackageVersion"); + + b.ToTable("PackageSymbols"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.HasIndex("RepositoryKey", "PackageId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Source") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actions") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("TargetKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("PermissionGrants"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("ExcludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IncludePatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("IsBuiltIn") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryPatterns") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("PermissionTargets"); + }); + + modelBuilder.Entity("BaGet.Core.Project", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Projects"); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalType") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey", "PrincipalType", "PrincipalId") + .IsUnique(); + + b.ToTable("ProjectMembers"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Conflict") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Direction") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("OnDeploy") + .HasColumnType("INTEGER"); + + b.Property("PeerRepository") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PeerUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("PropagateDeletes") + .HasColumnType("INTEGER"); + + b.Property("ProtectedApiKey") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleMinutes") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RepositoryKey"); + + b.ToTable("ReplicationConfigs"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Digest") + .HasMaxLength(160) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Part") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Synced") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Name", "Version", "Part"); + + b.ToTable("ReplicationItems"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Bytes") + .HasColumnType("INTEGER"); + + b.Property("ConfigKey") + .HasColumnType("INTEGER"); + + b.Property("Conflicts") + .HasColumnType("INTEGER"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Examined") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("Finished") + .HasColumnType("TEXT"); + + b.Property("ResumedFrom") + .HasColumnType("INTEGER"); + + b.Property("Skipped") + .HasColumnType("INTEGER"); + + b.Property("Started") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("Transferred") + .HasColumnType("INTEGER"); + + b.Property("Trigger") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ConfigKey", "Started"); + + b.ToTable("ReplicationRuns"); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AnonymousRead") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Format") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("Settings") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.ToTable("Repositories"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(340) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("Version") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("RetentionHolds"); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CacheLimitBytes") + .HasColumnType("INTEGER"); + + b.Property("CollectGarbage") + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("KeepLast") + .HasColumnType("INTEGER"); + + b.Property("LastResult") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("LastRun") + .HasColumnType("TEXT"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NamePatterns") + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("OlderThanDays") + .HasColumnType("INTEGER"); + + b.Property("PrereleaseOnly") + .HasColumnType("INTEGER"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("ScheduleHours") + .HasColumnType("INTEGER"); + + b.Property("ScheduleStart") + .HasColumnType("TEXT"); + + b.Property("UntaggedAfterDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedDays") + .HasColumnType("INTEGER"); + + b.Property("UnusedSince") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("ProjectKey"); + + b.HasIndex("RepositoryKey"); + + b.ToTable("RetentionPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Component") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("ComponentVersion") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("FixedVersion") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("ResultKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("VulnerabilityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("ResultKey"); + + b.ToTable("ScanFindings"); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("BlockDeploySeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockDownloadSeverity") + .HasColumnType("INTEGER"); + + b.Property("BlockUnscanned") + .HasColumnType("INTEGER"); + + b.Property("Modified") + .HasColumnType("TEXT"); + + b.Property("ModifiedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ProjectKey") + .HasColumnType("INTEGER"); + + b.Property("RepositoryKey") + .HasColumnType("INTEGER"); + + b.Property("WarnSeverity") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("ProjectKey") + .IsUnique(); + + b.HasIndex("RepositoryKey") + .IsUnique(); + + b.ToTable("ScanPolicies"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Attempted") + .HasColumnType("TEXT"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("FindingCount") + .HasColumnType("INTEGER"); + + b.Property("Highest") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("RepositoryKey") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(1); + + b.Property("ScannedAt") + .HasColumnType("TEXT"); + + b.Property("Scanner") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("RepositoryKey", "Name", "Version") + .IsUnique(); + + b.ToTable("ScanResults"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ApiKeyRepository", b => + { + b.HasOne("BaGet.Core.ApiKey", "ApiKey") + .WithMany() + .HasForeignKey("ApiKeyKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApiKey"); + }); + + modelBuilder.Entity("BaGet.Core.ArtifactUsage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.GroupMember", b => + { + b.HasOne("BaGet.Core.Group", "Group") + .WithMany() + .HasForeignKey("GroupKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("BaGet.Core.MavenArtifact", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenFile", b => + { + b.HasOne("BaGet.Core.MavenVersion", null) + .WithMany() + .HasForeignKey("VersionKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.MavenVersion", b => + { + b.HasOne("BaGet.Core.MavenArtifact", null) + .WithMany() + .HasForeignKey("ArtifactKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmDistTag", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmPackage", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.NpmVersion", b => + { + b.HasOne("BaGet.Core.NpmPackage", null) + .WithMany() + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlob", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciBlobLink", b => + { + b.HasOne("BaGet.Core.OciBlob", null) + .WithMany() + .HasForeignKey("BlobKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciManifest", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciRepository", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciTag", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("BaGet.Core.OciManifest", null) + .WithMany() + .HasForeignKey("ManifestKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OciUpload", b => + { + b.HasOne("BaGet.Core.OciRepository", null) + .WithMany() + .HasForeignKey("ImageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageSymbol", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionGrant", b => + { + b.HasOne("BaGet.Core.PermissionTarget", "Target") + .WithMany() + .HasForeignKey("TargetKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("BaGet.Core.PermissionTarget", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ProjectMember", b => + { + b.HasOne("BaGet.Core.Project", "Project") + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationConfig", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationItem", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ReplicationRun", b => + { + b.HasOne("BaGet.Core.ReplicationConfig", null) + .WithMany() + .HasForeignKey("ConfigKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Repository", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.RetentionHold", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.RetentionPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanFinding", b => + { + b.HasOne("BaGet.Core.ScanResult", null) + .WithMany("Findings") + .HasForeignKey("ResultKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.ScanPolicy", b => + { + b.HasOne("BaGet.Core.Project", null) + .WithMany() + .HasForeignKey("ProjectKey") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.HasOne("BaGet.Core.Repository", null) + .WithMany() + .HasForeignKey("RepositoryKey") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.ScanResult", b => + { + b.Navigation("Findings"); }); #pragma warning restore 612, 618 } diff --git a/src/BaGet.Database.Sqlite/README.md b/src/BaGet.Database.Sqlite/README.md new file mode 100644 index 000000000..dacdbf205 --- /dev/null +++ b/src/BaGet.Database.Sqlite/README.md @@ -0,0 +1,44 @@ +# Extension.BaGet.Database.Sqlite + +The SQLite database provider of [BaGet Extension](https://pieroviano.github.io/BaGet/), built on `Microsoft.EntityFrameworkCore.Sqlite`. + +```powershell +dotnet add package Extension.BaGet.Database.Sqlite +``` + +## Usage + +Register it in the `BaGetApplication` callback; it activates when `Database:Type` is `Sqlite`: + +```csharp +services.AddBaGetWebApplication(app => app.AddSqliteDatabase()); +``` + +| Setting | Value | +|---|---| +| `Database:Type` | `Sqlite` | +| `Database:ConnectionString` | e.g. `Data Source=baget.db` | + +`AddSqliteDatabase` also registers `SqliteDatabaseContextFactory` (`IDatabaseContextFactory`), which opens a `SqliteContext` on any connection string for the Settings page's database copy. + +## Migrations (contributors) + +The project has its own design-time context factory, so `dotnet ef` needs no startup project and no +running database. The tool version is pinned by `.config/dotnet-tools.json`; run `dotnet tool restore` once. + +From this folder: + +``` +dotnet ef migrations add MigrationName --context SqliteContext --output-dir Migrations +dotnet ef migrations has-pending-model-changes --context SqliteContext +``` + +A model change needs a migration in **all four** `BaGet.Database.*` projects, and each must then report +no pending model changes. Keep schema changes additive (new tables, nullable foreign keys): SQLite cannot +alter a foreign key in place. + +BaGet applies pending migrations itself when it starts. + +- List migrations without a server: `dotnet ef migrations list --context SqliteContext`. +- Never run `dotnet ef migrations remove --no-build`: with a stale assembly it deleted the previous migration. Delete the generated files by hand and restore the model snapshot from `HEAD`. +- Entity Framework is 10.0.13; the MySQL provider is `Microting.EntityFrameworkCore.MySql`; all four providers move together. diff --git a/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs b/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs index 34e3a91e1..f3de21890 100644 --- a/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs +++ b/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs @@ -1,33 +1,38 @@ using System; using BaGet.Core; using BaGet.Database.Sqlite; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class SqliteApplicationExtensions { - public static class SqliteApplicationExtensions + public static BaGetApplication AddSqliteDatabase(this BaGetApplication app) { - public static BaGetApplication AddSqliteDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("Sqlite", (provider, options) => { - app.Services.AddBaGetDbContextProvider("Sqlite", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - options.UseSqlite(databaseOptions.Value.ConnectionString); - }); + SqliteDatabaseContextFactory.Configure( + options, + databaseOptions.Value.ConnectionString, + databaseOptions.Value.MySqlServerVersion); + }); - return app; - } + app.Services.TryAddEnumerable( + ServiceDescriptor.Singleton()); - public static BaGetApplication AddSqliteDatabase( - this BaGetApplication app, - Action configure) - { - app.AddSqliteDatabase(); - app.Services.Configure(configure); - return app; - } + return app; + } + + public static BaGetApplication AddSqliteDatabase( + this BaGetApplication app, + Action configure) + { + app.AddSqliteDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.Sqlite/SqliteContext.cs b/src/BaGet.Database.Sqlite/SqliteContext.cs index 974ae587b..5d622c4b5 100644 --- a/src/BaGet.Database.Sqlite/SqliteContext.cs +++ b/src/BaGet.Database.Sqlite/SqliteContext.cs @@ -2,48 +2,50 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; -namespace BaGet.Database.Sqlite +namespace BaGet.Database.Sqlite; + +public class SqliteContext : AbstractContext { - public class SqliteContext : AbstractContext + /// + /// The Sqlite error code for when a unique constraint is violated. + /// + // The extended result codes: the primary code 19 (SQLITE_CONSTRAINT) also covers foreign key and NOT NULL violations, + // which are not "already exists". + private const int SqliteConstraintUnique = 2067; + private const int SqliteConstraintPrimaryKey = 1555; + + public SqliteContext(DbContextOptions options) + : base(options) + { } + + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) { - /// - /// The Sqlite error code for when a unique constraint is violated. - /// - private const int SqliteUniqueConstraintViolationErrorCode = 19; - - public SqliteContext(DbContextOptions options) - : base(options) - { } - - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - return exception.InnerException is SqliteException sqliteException && - sqliteException.SqliteErrorCode == SqliteUniqueConstraintViolationErrorCode; - } - - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - builder.Entity() - .Property(p => p.Id) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(p => p.NormalizedVersionString) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(d => d.Id) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(t => t.Name) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(f => f.Moniker) - .HasColumnType("TEXT COLLATE NOCASE"); - } + return exception.InnerException is SqliteException sqliteException && + sqliteException.SqliteExtendedErrorCode is SqliteConstraintUnique or SqliteConstraintPrimaryKey; + } + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + builder.Entity() + .Property(p => p.Id) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(p => p.NormalizedVersionString) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(d => d.Id) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(t => t.Name) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(f => f.Moniker) + .HasColumnType("TEXT COLLATE NOCASE"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.Sqlite/SqliteContextFactory.cs b/src/BaGet.Database.Sqlite/SqliteContextFactory.cs new file mode 100644 index 000000000..27624618c --- /dev/null +++ b/src/BaGet.Database.Sqlite/SqliteContextFactory.cs @@ -0,0 +1,25 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace BaGet.Database.Sqlite; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class SqliteContextFactory : IDesignTimeDbContextFactory +{ + public SqliteContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseSqlite("Data Source=baget.db") + .Options; + + return new SqliteContext(options); + } +} \ No newline at end of file diff --git a/src/BaGet.Database.Sqlite/SqliteDatabaseContextFactory.cs b/src/BaGet.Database.Sqlite/SqliteDatabaseContextFactory.cs new file mode 100644 index 000000000..6bdf752d8 --- /dev/null +++ b/src/BaGet.Database.Sqlite/SqliteDatabaseContextFactory.cs @@ -0,0 +1,37 @@ +using System; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Database.Sqlite; + +/// +/// Opens a on any Sqlite connection string; see . +/// +public class SqliteDatabaseContextFactory : IDatabaseContextFactory +{ + /// + public string DatabaseType => "Sqlite"; + + /// + public IContext Create( + string connectionString, + DatabaseOptions? options = null, + Action? configure = null) + { + var builder = new DbContextOptionsBuilder(); + + Configure(builder, connectionString, options?.MySqlServerVersion); + configure?.Invoke(builder); + + return new SqliteContext(builder.Options); + } + + /// + /// The one place the provider is configured: used by both this factory and the application's + /// registration, so a second database is configured exactly like the main one. + /// + internal static void Configure(DbContextOptionsBuilder options, string? connectionString, string? mySqlServerVersion) + { + options.UseSqlite(connectionString); + } +} diff --git a/src/BaGet.Database.Sqlite/readme.md b/src/BaGet.Database.Sqlite/readme.md deleted file mode 100644 index aa2e59577..000000000 --- a/src/BaGet.Database.Sqlite/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -# BaGet's SQLite Database Provider - -This project contains BaGet's SQLite database provider. - -## Migrations - -Add a migration with: - -``` -dotnet ef migrations add MigrationName --context SqliteContext --output-dir Migrations --startup-project ..\BaGet\BaGet.csproj - -dotnet ef database update --context SqliteContext -``` diff --git a/src/BaGet.Frontend.Base/BaGet.Frontend.Base.csproj b/src/BaGet.Frontend.Base/BaGet.Frontend.Base.csproj new file mode 100644 index 000000000..84f8a5d87 --- /dev/null +++ b/src/BaGet.Frontend.Base/BaGet.Frontend.Base.csproj @@ -0,0 +1,46 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's shared MVC infrastructure for the screens: view controller bases, layout and shared partials, tag helpers. + BaGet.Frontend + true + enable + Extension.$(MSBuildProjectName) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Frontend.Base/Controllers/Base/AccessControllerBase.cs b/src/BaGet.Frontend.Base/Controllers/Base/AccessControllerBase.cs new file mode 100644 index 000000000..06f607020 --- /dev/null +++ b/src/BaGet.Frontend.Base/Controllers/Base/AccessControllerBase.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Services.Accounts; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the access-control screens (groups, permission targets, projects, audit). Signed in, accounts enabled, an administrator, unless a screen widens it to a project's administrators +/// (); anyone else gets 404. Needs a relational database: where there is no access model (Azure +/// Table) every screen sends an administrator to /admin/access-unavailable, which says so. Every POST is refused with 503 +/// while the is closed, and changes go through , which audits +/// them and invalidates the evaluator's cache. Retention and replication screens build on it +/// (, ). +/// +public abstract class AccessControllerBase : AdminControllerBase +{ + /// Outcome of the last action. + [TempData] + public string? Message { get; set; } + + /// Why the last action was refused. + [TempData] + public string? Error { get; set; } + + /// Whether the signed-in user is a server administrator (rather than only a project administrator). + public bool IsServerAdministrator { get; private set; } + + /// The signed-in user's id. + protected string? CurrentUserId { get; private set; } + + /// Whether the signed in user has a password to confirm with. + public bool HasPassword { get; private set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; private set; } + + /// Whether an external provider linked to the signed-in account is available to sign in again with. + public bool CanReauthenticate { get; private set; } + + /// The access model's administration, resolved per request. + protected IAccessAdministration AccessAdmin => HttpContext.RequestServices.GetRequiredService(); + + /// The access evaluator, resolved per request. + protected IAccessEvaluator Evaluator => HttpContext.RequestServices.GetRequiredService(); + + /// The user name recorded in the audit log. + protected string? Actor => User.Identity?.Name; + + /// The model of the password confirmation partial, with for the input. + [NonAction] + public ConfirmPasswordView Confirmation(string id) + => new(id, HasPassword, Reauthenticated, CanReauthenticate, "~" + Request.Path + Request.QueryString); + + /// + /// Whether the signed-in user may use this screen. The default is server administrators; project screens also admit the + /// administrators of the project they act on. + /// + protected virtual async Task AuthorizeAsync(CancellationToken cancellationToken) + { + await Task.CompletedTask; + return IsServerAdministrator; + } + + /// + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + // Not AdminControllerBase's own check: a project administrator is admitted by AuthorizeAsync. + OnActionExecuting(context); + if (context.Result != null) return; + + var cancellationToken = HttpContext.RequestAborted; + CurrentUserId = UserManager.GetUserId(User); + + // The gate holds the order: administrator or whoever AuthorizeAsync admits, the access model present, writable on a POST. + var gate = await Gate.CheckAsync( + User, + new GateRequest(Role: GateRole.AccessAdministrator, IsWrite: HttpMethods.IsPost(Request.Method), AlsoAllow: async ct => await AuthorizeAsync(ct)), + cancellationToken); + IsServerAdministrator = gate.IsServerAdministrator; + + if (gate.Outcome == GateOutcome.AccessUnavailable) + { + context.Result = RedirectToAction(ScreenCatalog.AdminAccessUnavailable.Action, ScreenCatalog.AdminAccessUnavailable.Controller); + return; + } + + if (!gate.IsAllowed) + { + context.Result = NotFound(); + return; + } + + var current = await UserManager.GetUserAsync(User); + HasPassword = current == null || await UserManager.HasPasswordAsync(current); + Reauthenticated = !HasPassword && await HasReauthenticatedRecentlyAsync(); + CanReauthenticate = await HttpContext.RequestServices.GetRequiredService().CanReauthenticateAsync(current); + + OnActionExecuted(await next()); + } + + /// + /// Runs one change: asks for the password when , turns an into + /// , and redirects to . + /// + /// What the user typed. + /// Whether the change asks for the password (grants, memberships, deletions). + /// The change; returns the message to show. + /// Where to go afterwards. + protected async Task ActAsync(string? password, bool confirm, Func> change, Func redirect) + { + if (confirm) + { + var current = await UserManager.GetUserAsync(User); + if (current == null) return Challenge(); + + if (!await IsConfirmedAsync(current, password)) + { + Error = "The confirmation is incorrect, so nothing was changed."; + return redirect(); + } + } + + try + { + Message = await change(); + } + catch (AccessModelException e) + { + Error = e.Message; + } + + return redirect(); + } + + /// + /// What a set of patterns selects, for the pattern editors: the repositories whose names match the repository patterns, and, + /// when a package ID was typed in the test box, whether the target would apply to it. + /// + protected Task PreviewAsync( + string[] repositoryPatterns, + string[] includePatterns, + string[] excludePatterns, + string? testPackage, + CancellationToken cancellationToken) + => AccessSupport.PreviewAsync(HttpContext.RequestServices, repositoryPatterns, includePatterns, excludePatterns, testPackage, cancellationToken); + + /// Parses the ticked action boxes (names of values). + protected static AccessAction ParseActions(IEnumerable? names) => AccessSupport.ParseActions(names); + + /// The single actions, in display order. + public static AccessAction[] AllActions => AccessSupport.AllActions; + + /// The actions in as words, or "none". + public static string Words(AccessAction actions) => AccessSupport.Words(actions); + + /// Patterns one per line, the way the editors show them. + public static string Lines(IEnumerable patterns) => AccessSupport.Lines(patterns); + + /// The package filter and repository patterns as one line a person can read back. + public static string Join(IEnumerable patterns) => AccessSupport.Join(patterns); +} diff --git a/src/BaGet.Frontend.Base/Controllers/Base/AccountControllerBase.cs b/src/BaGet.Frontend.Base/Controllers/Base/AccountControllerBase.cs new file mode 100644 index 000000000..5d2f45562 --- /dev/null +++ b/src/BaGet.Frontend.Base/Controllers/Base/AccountControllerBase.cs @@ -0,0 +1,139 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Identity.Application.Email; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Shared by the account screens. The screens are always compiled in, but +/// answer 404 while accounts are disabled, so their services are resolved per request rather than injected: they are only +/// registered when accounts are enabled. +/// +/// checks, in this order: accounts enabled (else 404), mail +/// configured when (else 404), signed in when (else a challenge, which +/// sends the visitor to sign in). It is checked here rather than with [Authorize] because while accounts are disabled +/// there is no scheme to challenge with and the screen must answer 404 instead. +/// +/// +public abstract class AccountControllerBase : UiControllerBase +{ + /// The accounts options. + protected AccountsOptions Accounts + => HttpContext.RequestServices.GetRequiredService>().Value; + + /// Signs users in and out. + protected SignInManager SignInManager + => HttpContext.RequestServices.GetRequiredService>(); + + /// Users, passwords, tokens. + protected UserManager UserManager + => HttpContext.RequestServices.GetRequiredService>(); + + /// Package and organization ownership. + protected PackageOwnershipService Ownership + => HttpContext.RequestServices.GetRequiredService(); + + /// API keys. + protected ApiKeyService ApiKeys + => HttpContext.RequestServices.GetRequiredService(); + + /// Whether outgoing mail is configured. + protected bool EmailConfigured + => HttpContext.RequestServices.GetRequiredService>().Value.IsConfigured; + + /// Sends the account emails. + protected IEmailSender EmailSender + => HttpContext.RequestServices.GetRequiredService>(); + + /// Screens that only make sense when there is a way to send mail answer 404 otherwise. + protected virtual bool RequiresEmail => false; + + /// Whether the screen needs a signed-in user (checked here, not with [Authorize], see the class remarks). + protected virtual bool RequiresSignIn => false; + + /// The gate every account and administration screen passes (the JSON API bases ask the same one). + protected ScreenGate Gate + => HttpContext.RequestServices.GetService() + ?? ActivatorUtilities.CreateInstance(HttpContext.RequestServices); + + /// + public override void OnActionExecuting(ActionExecutingContext context) + { + var metadata = context.ActionDescriptor.EndpointMetadata ?? (System.Collections.Generic.IList)Array.Empty(); + var request = new GateRequest( + RequiresSignIn: RequiresSignIn || metadata.OfType().Any(), + RequiresEmail: RequiresEmail || metadata.OfType().Any()); + + switch (Gate.CheckAccount(User, request)) + { + case GateOutcome.Allowed: + base.OnActionExecuting(context); + break; + case GateOutcome.SignIn: + context.Result = Challenge(); + break; + default: + context.Result = NotFound(); + break; + } + } + + private AccountScreen? _screen; + + /// The request as the account workflows see it. + internal AccountScreen Screen => _screen ??= new AccountScreen(HttpContext, Url, ModelState); + + /// Turns a workflow's decision into this controller's action result; renders the screen. + internal IActionResult Respond(ScreenOutcome outcome, string view, object? model = null) + => outcome.ToResult(Url, () => View(view, model)); + + /// Only follow a local return URL, so a sign-in link cannot redirect elsewhere. + protected IActionResult RedirectToLocal(string? returnUrl) + => LocalRedirect(AccountSupport.LocalTarget(Url, returnUrl)); + + /// Identity's tokens carry characters that do not survive a URL, so they travel encoded. + protected static string EncodeToken(string token) + => PasswordResetLinkSender.EncodeToken(token); + + /// Decodes a token written by , or null. + protected static string? DecodeToken(string? code) + => AccountSupport.DecodeToken(code); + + /// + /// An absolute link to an account screen, for an email. Built only from Site:PublicUrl, never from the request's host or + /// scheme: see . + /// + protected string AbsoluteLink(ScreenRef screen, object values) + => AccountSupport.AbsoluteLink(HttpContext, Url, screen, values); + + /// How long a sign-in with the external provider counts as proof of presence for a sensitive action. + public static TimeSpan ReauthenticationWindow => AccountSupport.ReauthenticationWindow; + + /// + /// The check behind every sensitive action (change email, set a password, delete the account, turn two-factor off or reset + /// it). An account with a password types it again; one without (external sign-in only) must have signed in again with its + /// provider a moment ago. + /// + protected Task IsConfirmedAsync(BaGetUser? user, string? password) + => AccountSupport.IsConfirmedAsync(UserManager, HttpContext, user, password); + + /// Whether the session re-authenticated with the external provider within . + protected Task HasReauthenticatedRecentlyAsync() + => AccountSupport.HasReauthenticatedRecentlyAsync(HttpContext); + + /// The messages of an identity failure as one sentence. + protected static string Describe(IdentityResult result) + => AccountSupport.Describe(result); +} diff --git a/src/BaGet.Frontend.Base/Controllers/Base/AdminControllerBase.cs b/src/BaGet.Frontend.Base/Controllers/Base/AdminControllerBase.cs new file mode 100644 index 000000000..43ddc1da7 --- /dev/null +++ b/src/BaGet.Frontend.Base/Controllers/Base/AdminControllerBase.cs @@ -0,0 +1,81 @@ +using System.Threading.Tasks; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Services.Accounts; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the administrator screens. Signed in, accounts enabled (see +/// ), and an administrator. Anyone else gets 404, so the screens' existence is not disclosed +/// (an anonymous visitor is challenged to sign in first, as the pages did). +/// +public abstract class AdminControllerBase : AccountControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + /// The administrator service, resolved per request: it exists only while accounts are enabled. + protected AdministratorService Administrators + => HttpContext.RequestServices.GetRequiredService(); + + /// + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + OnActionExecuting(context); + if (context.Result != null) return; + + if (!(await Gate.CheckAsync(User, new GateRequest(Role: GateRole.Administrator), HttpContext.RequestAborted)).IsAllowed) + { + context.Result = NotFound(); + return; + } + + OnActionExecuted(await next()); + } + + /// + /// Carries the outcome of an action across a redirect, as [TempData] Message / [TempData] Error did on the page + /// models: a value the action just set is stored for the next request; otherwise the model shows (and consumes) what the previous + /// request stored. Call it once per action, after the workflow ran and before returning. + /// + [NonAction] + protected void Flash(IFlashMessage model) + { + if (model.Message != null) TempData["Message"] = model.Message; + else model.Message = TempData["Message"] as string; + } + + /// for a screen that also flashes an error. + [NonAction] + protected void Flash(IFlashModel model) + { + Flash((IFlashMessage)model); + + if (model.Error != null) TempData["Error"] = model.Error; + else model.Error = TempData["Error"] as string; + } + + /// + /// Render for a screen whose model carries the outcome of the last action across a redirect + /// (, ): the message and error the previous request stored are moved into the model before the + /// view renders, as did on the page models. A redirect (Next with a message) stores them for the next request. + /// + [NonAction] + protected IActionResult RenderFlashed(UiApiResponse response, string view) + where TModel : class, IFlashMessage + => Render( + response, + view, + model => + { + if (model is IFlashModel flash) Flash(flash); + else Flash((IFlashMessage)model); + + return model; + }); +} diff --git a/src/BaGet.Frontend.Base/Controllers/Base/ReplicationControllerBase.cs b/src/BaGet.Frontend.Base/Controllers/Base/ReplicationControllerBase.cs new file mode 100644 index 000000000..15aaff78c --- /dev/null +++ b/src/BaGet.Frontend.Base/Controllers/Base/ReplicationControllerBase.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.UseCases.Policies; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the replication screens. The access screens' rules +/// (administrators only, 404 for anyone else, redirect where there is no relational database, 503 on a POST while the server is +/// read-only), with the replication services and the repositories a configuration can name. A +/// is an , so ActAsync turns it into the screen's Error. +/// +public abstract class ReplicationControllerBase : AccessControllerBase +{ + /// Configurations and their log. + protected IReplicationAdministration Replication => HttpContext.RequestServices.GetRequiredService(); + + /// Runs replications in the background. + protected ReplicationJobs Jobs => HttpContext.RequestServices.GetRequiredService(); + + /// The local repositories a replication can name (remote and virtual ones are not replicated), by name. + public IReadOnlyList Repositories { get; private set; } = Array.Empty(); + + /// Loads . + protected async Task LoadChoicesAsync(CancellationToken cancellationToken) + { + Repositories = await PolicyScreenSupport.ReplicationRepositoriesAsync(HttpContext.RequestServices.GetRequiredService(), cancellationToken); + } + + /// The schedule and triggers of a configuration in a few words. + public static string Describe(ReplicationConfig c) => PolicyScreenSupport.DescribeReplication(c); +} diff --git a/src/BaGet.Frontend.Base/Controllers/Base/RepositoryControllerBase.cs b/src/BaGet.Frontend.Base/Controllers/Base/RepositoryControllerBase.cs new file mode 100644 index 000000000..68268ba4a --- /dev/null +++ b/src/BaGet.Frontend.Base/Controllers/Base/RepositoryControllerBase.cs @@ -0,0 +1,52 @@ +using BaGet.Identity.Application.Services.Accounts; +using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using BaGet.Identity.Application.Models.Shared; +using Microsoft.AspNetCore.Mvc; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the repository administration screens that change a remote repository's upstream or empty its cache. They ask for the administrator's password again (or a recent sign-in with the +/// external provider, for an account without one), like the access screens do for changes that hand out credentials or delete +/// data. +/// +public abstract class RepositoryControllerBase : AdminControllerBase +{ + /// The message shown when the confirmation fails; nothing was changed. + protected const string NotConfirmed = "The confirmation is incorrect, so nothing was changed."; + + /// Why the last action was refused. + public string? Error { get; protected set; } + + /// Whether the signed-in user has a password to confirm with. + public bool HasPassword { get; private set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; private set; } + + /// Whether an external provider linked to the signed-in account is available to sign in again with. + public bool CanReauthenticate { get; private set; } + + /// The model of the password confirmation partial, with for the input. + [NonAction] + public ConfirmPasswordView Confirmation(string id) + => new(id, HasPassword, Reauthenticated, CanReauthenticate, "~" + Request.Path + Request.QueryString); + + /// Works out what the confirmation partials must show; call before rendering a screen that has them. + protected async Task LoadConfirmationAsync() + { + var current = await UserManager.GetUserAsync(User); + HasPassword = current == null || await UserManager.HasPasswordAsync(current); + Reauthenticated = !HasPassword && await HasReauthenticatedRecentlyAsync(); + CanReauthenticate = await HttpContext.RequestServices.GetRequiredService().CanReauthenticateAsync(current); + } + + /// Whether what the user typed (or a recent re-authentication) confirms the change. + protected async Task ConfirmedAsync(string? password) + { + var current = await UserManager.GetUserAsync(User); + + return current != null && await IsConfirmedAsync(current, password); + } +} diff --git a/src/BaGet.Frontend.Base/Controllers/Base/RetentionControllerBase.cs b/src/BaGet.Frontend.Base/Controllers/Base/RetentionControllerBase.cs new file mode 100644 index 000000000..59cec9d2c --- /dev/null +++ b/src/BaGet.Frontend.Base/Controllers/Base/RetentionControllerBase.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.UseCases.Policies; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of the retention screens (policies, a policy's report, legal holds). The access screens' rules (administrators only, 404 for anyone else, redirect where there is no +/// relational database, 503 on a POST while the server is read-only), with the retention services and the lists the forms choose +/// from. A is an , so ActAsync turns it into the screen's +/// Error. +/// +public abstract class RetentionControllerBase : AccessControllerBase +{ + /// Policies and legal holds. + protected IRetentionAdministration Retention => HttpContext.RequestServices.GetRequiredService(); + + /// Runs policies in the background and keeps their last report. + protected RetentionJobs Jobs => HttpContext.RequestServices.GetRequiredService(); + + /// The repositories a policy or hold can name (virtual ones store nothing), by name. + public IReadOnlyList Repositories { get; private set; } = Array.Empty(); + + /// The names of the projects a policy can name. + public IReadOnlyList ProjectNames { get; private set; } = Array.Empty(); + + /// Loads and . + protected async Task LoadChoicesAsync(CancellationToken cancellationToken) + { + Repositories = await PolicyScreenSupport.RetentionRepositoriesAsync(HttpContext.RequestServices.GetRequiredService(), cancellationToken); + ProjectNames = await PolicyScreenSupport.ProjectNamesAsync(HttpContext.RequestServices.GetRequiredService(), cancellationToken); + } + + /// The rules of a policy in one line, for the lists. + public static string Describe(RetentionPolicy p) => PolicyScreenSupport.DescribeRetention(p); +} diff --git a/src/BaGet.Frontend.Base/Controllers/Base/UiControllerBase.cs b/src/BaGet.Frontend.Base/Controllers/Base/UiControllerBase.cs new file mode 100644 index 000000000..a4a841b9f --- /dev/null +++ b/src/BaGet.Frontend.Base/Controllers/Base/UiControllerBase.cs @@ -0,0 +1,135 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace BaGet.Frontend.Controllers.Base; + +/// +/// Base of every controller that serves a screen of BaGet's own web UI. What it gives a screen: +/// +/// Antiforgery. : every unsafe request (POST) without +/// a valid token is answered 400 before anything else runs, as for a page. Never opt a UI action out. +/// Handlers. picks the action by ?handler=, so form URLs +/// do not change; is the value. +/// Filters. The controller's own OnActionExecuting/OnActionExecutionAsync override runs first, before +/// the global RepositoryActionFilter. +/// +/// A screen is identified by its controller and its default GET action (); a UI controller +/// of a repository's page also carries . +/// +/// +/// How to migrate a page: the page's +/// @page "/x" becomes [Route("x")]; OnGet becomes [HttpGet, HttpHead, PageHandler]; OnPostX +/// becomes [HttpPost, PageHandler("X")] taking [FromForm]/[FromQuery] parameters instead of +/// [BindProperty]; return Page() becomes return View("Name", model); [TempData] properties stay +/// [TempData] properties of the controller. The view moves to Views/<Controller>/<Name>.cshtml with +/// the view model as @model. +/// +[AutoValidateAntiforgeryToken] +public abstract class UiControllerBase : Controller, IScreenController +{ + /// + /// The handler the request names (?handler=, or the handler route value), or null for the default handler. + /// + protected string? RequestedHandler => PageHandlerAttribute.RequestedHandler(HttpContext, RouteData); + + /// + /// Calls the JSON twin of this screen in process () and returns what it answered. The twin does the work; this + /// controller only Renders the answer. The twin's filters do not run, so the controller base has run the screen gate + /// and the antiforgery validation of the view action already. + /// + /// The twin controller. + /// The screen's model. + protected Task> Api(Func>>> call) + where TApi : ApiControllerBase + => UiApiInvoker.InvokeAsync(this, call); + + /// Api for a twin action that does not await. + protected Task> Api(Func>> call) + where TApi : ApiControllerBase + { + if (call == null) throw new ArgumentNullException(nameof(call)); + + return UiApiInvoker.InvokeAsync(this, api => Task.FromResult(call(api))); + } + + /// + /// Turns the answer of a twin into this controller's result: a plain action result the twin returned is returned unchanged; Ok and Invalid + /// render (errors copied into ModelState, the result's status code applied); NotFound is 404, SignIn a challenge + /// (the sign-in redirect), Forbidden a bare 403 (what a page answered), Next sets the flash message and redirects to the next screen by its + /// controller and action (the repository stays), or to its local address. + /// + /// What Api returned. + /// The view to render. + /// Maps the twin's model to the view's model when they differ (default: the model itself). + /// + /// The view prints the form-level message from its model (Model.Error), so the form-level errors (the empty key) are not copied into ModelState as + /// well: the page would show the message twice. Field errors are always copied. + /// + protected IActionResult Render(UiApiResponse response, string view, Func? viewModel = null, bool modelShowsFormErrors = false) + { + if (response == null) throw new ArgumentNullException(nameof(response)); + + return response.Raw ?? Render(response.Screen, view, viewModel, modelShowsFormErrors); + } + + /// + /// The same mapping for a result a controller got from a use case directly: only the browser-only steps (the external provider's challenge and + /// callback) have no twin to call. + /// + protected IActionResult Render(ScreenResult screen, string view, Func? viewModel = null, bool modelShowsFormErrors = false) + { + if (screen == null) throw new ArgumentNullException(nameof(screen)); + + switch (screen.Status) + { + case ScreenStatus.Ok: + case ScreenStatus.Invalid: + foreach (var pair in screen.Errors) + { + if (modelShowsFormErrors && pair.Key.Length == 0) continue; + + foreach (var message in pair.Value) + { + // A binding or validation error MVC already recorded for the field says the same: once is enough. + if (ModelState.TryGetValue(pair.Key, out var entry) && entry.Errors.Any(e => e.ErrorMessage == message)) continue; + + ModelState.AddModelError(pair.Key, message); + } + } + + var model = screen.Model == null ? null : viewModel != null ? viewModel(screen.Model) : screen.Model; + var result = View(view, model); + if (screen.StatusCode is { } code) result.StatusCode = code; + + return result; + + case ScreenStatus.NotFound: + return NotFound(); + + case ScreenStatus.SignIn: + return Challenge(); + + case ScreenStatus.Forbidden: + // What a page answered: a bare 403 (Forbid() would hand the request to the cookie handler's access-denied redirect). + return new StatusCodeResult(StatusCodes.Status403Forbidden); + + case ScreenStatus.Next: + var next = screen.Next!; + if (next.Message != null) TempData["Message"] = next.Message; + if (next.Error != null) TempData["Error"] = next.Error; + + return next.LocalUrl != null + ? new LocalRedirectResult(next.LocalUrl) { UrlHelper = Url } + : new RedirectToActionResult(next.Screen!.Action, next.Screen.Controller, next.RouteValues, fragment: next.Fragment) { UrlHelper = Url }; + + default: + throw new InvalidOperationException($"Unknown screen status {screen.Status}."); + } + } +} diff --git a/src/BaGet.Frontend.Base/Mvc/Attributes/ImplicitPageHandlerAttribute.cs b/src/BaGet.Frontend.Base/Mvc/Attributes/ImplicitPageHandlerAttribute.cs new file mode 100644 index 000000000..f61188b44 --- /dev/null +++ b/src/BaGet.Frontend.Base/Mvc/Attributes/ImplicitPageHandlerAttribute.cs @@ -0,0 +1,16 @@ +using System; + +namespace BaGet.Frontend.Mvc.Attributes; + +/// +/// Marks the default action ( without a name) that stands for a verb the page had no +/// handler method for. A Razor Page answers every verb at its route: antiforgery runs first (a POST without a token is +/// 400) and a request no handler claims renders the page. A controller route does not exist for a verb no action +/// claims (404), so a screen whose forms can post to its own URL without a handler (a form whose buttons carry the +/// ?handler= as formaction) gets such an action, which renders the screen like the page did. It is not a handler of +/// the page: the route contract (ui-routes.txt) does not list it. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class ImplicitPageHandlerAttribute : Attribute +{ +} diff --git a/src/BaGet.Frontend.Base/Mvc/Screens/AccessSupport.cs b/src/BaGet.Frontend.Base/Mvc/Screens/AccessSupport.cs new file mode 100644 index 000000000..83c9addb2 --- /dev/null +++ b/src/BaGet.Frontend.Base/Mvc/Screens/AccessSupport.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.UseCases.Access; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Mvc.Screens; + +/// +/// The thin forwards of the access screens' pattern helpers (the code is in ) +/// used by . +/// +internal static class AccessSupport +{ + /// The single actions, in display order. + public static readonly AccessAction[] AllActions = AccessPatternSupport.AllActions; + + /// Parses the ticked action boxes (names of values). + public static AccessAction ParseActions(IEnumerable? names) => AccessPatternSupport.ParseActions(names); + + /// The actions in as words, or "none". + public static string Words(AccessAction actions) => AccessPatternSupport.Words(actions); + + /// Patterns one per line, the way the editors show them. + public static string Lines(IEnumerable patterns) => AccessPatternSupport.Lines(patterns); + + /// The package filter and repository patterns as one line a person can read back. + public static string Join(IEnumerable patterns) => AccessPatternSupport.Join(patterns); + + /// What a set of patterns selects: the matching repository names and, for a typed package ID, whether it applies. + public static Task PreviewAsync( + IServiceProvider services, + string[] repositoryPatterns, + string[] includePatterns, + string[] excludePatterns, + string? testPackage, + CancellationToken cancellationToken) + => AccessPatternSupport.PreviewAsync(services.GetRequiredService(), repositoryPatterns, includePatterns, excludePatterns, testPackage, cancellationToken); +} diff --git a/src/BaGet.Frontend.Base/Mvc/Screens/AccountScreen.cs b/src/BaGet.Frontend.Base/Mvc/Screens/AccountScreen.cs new file mode 100644 index 000000000..8f5d9e7db --- /dev/null +++ b/src/BaGet.Frontend.Base/Mvc/Screens/AccountScreen.cs @@ -0,0 +1,70 @@ +using System; +using System.Security.Claims; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Identity.Application.Email; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace BaGet.Frontend.Mvc.Screens; + +/// +/// What an account workflow needs from the request, whatever hosts it (). The services are resolved per call: they are +/// only registered while accounts are enabled, and the callers check that first. +/// +internal sealed class AccountScreen +{ + public AccountScreen(HttpContext httpContext, IUrlHelper url, ModelStateDictionary modelState) + { + HttpContext = httpContext ?? throw new ArgumentNullException(nameof(httpContext)); + Url = url ?? throw new ArgumentNullException(nameof(url)); + ModelState = modelState ?? throw new ArgumentNullException(nameof(modelState)); + } + + public HttpContext HttpContext { get; } + + public IUrlHelper Url { get; } + + public ModelStateDictionary ModelState { get; } + + public ClaimsPrincipal User => HttpContext.User; + + public IServiceProvider Services => HttpContext.RequestServices; + + public AccountsOptions Accounts => Services.GetRequiredService>().Value; + + public SignInManager SignInManager => Services.GetRequiredService>(); + + public UserManager UserManager => Services.GetRequiredService>(); + + public PackageOwnershipService Ownership => Services.GetRequiredService(); + + public ApiKeyService ApiKeys => Services.GetRequiredService(); + + public bool EmailConfigured => Services.GetRequiredService>().Value.IsConfigured; + + public IEmailSender EmailSender => Services.GetRequiredService>(); + + public DateTime UtcNow => Services.GetRequiredService().UtcNow; + + public string AbsoluteLink(ScreenRef screen, object values) => AccountSupport.AbsoluteLink(HttpContext, Url, screen, values); + + public Task IsConfirmedAsync(BaGetUser? user, string? password) + => AccountSupport.IsConfirmedAsync(UserManager, HttpContext, user, password); + + public Task HasReauthenticatedRecentlyAsync() => AccountSupport.HasReauthenticatedRecentlyAsync(HttpContext); + + public static string Describe(IdentityResult result) => AccountSupport.Describe(result); + + public static string EncodeToken(string token) => PasswordResetLinkSender.EncodeToken(token); + + public static string? DecodeToken(string? code) => AccountSupport.DecodeToken(code); +} diff --git a/src/BaGet.Frontend.Base/Mvc/Screens/PackageControllerSupport.cs b/src/BaGet.Frontend.Base/Mvc/Screens/PackageControllerSupport.cs new file mode 100644 index 000000000..4b1fb45e6 --- /dev/null +++ b/src/BaGet.Frontend.Base/Mvc/Screens/PackageControllerSupport.cs @@ -0,0 +1,39 @@ +using System.Reflection; +using BaGet.Frontend.Mvc.Attributes; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace BaGet.Frontend.Mvc.Screens; + +/// What the package-management controllers share: reading the request. +internal static class PackageControllerSupport +{ + /// + /// The name of the handler about to run ([PageHandler("Unlist")] gives Unlist; the default handler null): for the administrator audit line. + /// + public static string? HandlerName(ActionExecutingContext context) + => (context.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo.GetCustomAttribute()?.Name; + + /// A route value as text (the identity of the screen's subject comes from the address, never from the body). + public static string? Route(ActionExecutingContext context, string key) + => context.RouteData.Values.TryGetValue(key, out var value) ? value as string : null; + + /// A form field of a POST, else a query string value: how the screens read their input. + public static string? FormOrQuery(ActionExecutingContext context, string key) + => FormOrQuery(context.HttpContext.Request, key); + + /// A form field of a POST, else a query string value: how the screens read their input. + public static string? FormOrQuery(Microsoft.AspNetCore.Http.HttpRequest request, string key) + { + if (request.HasFormContentType && request.Form.TryGetValue(key, out var form) && form.Count > 0) + { + var posted = form.ToString(); + + return posted.Length == 0 ? null : posted; + } + + var query = request.Query[key].ToString(); + + return query.Length == 0 ? null : query; + } +} diff --git a/src/BaGet.Frontend.Base/Mvc/Screens/ScreenOutcome.cs b/src/BaGet.Frontend.Base/Mvc/Screens/ScreenOutcome.cs new file mode 100644 index 000000000..b1df1b0bd --- /dev/null +++ b/src/BaGet.Frontend.Base/Mvc/Screens/ScreenOutcome.cs @@ -0,0 +1,63 @@ +using System; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Mvc; + +namespace BaGet.Frontend.Mvc.Screens; + +/// +/// What an account workflow decided, independent of the programming model that runs it: show the screen again, or leave for +/// somewhere. turns it into the same a controller action returns, so the workflow holds the rules and the host holds only the plumbing. +/// +internal sealed class ScreenOutcome +{ + private readonly ScreenOutcomeKind _kind; + private readonly string? _text; + private readonly AuthenticationProperties? _properties; + private readonly int _status; + + private ScreenOutcome(ScreenOutcomeKind kind, string? text = null, AuthenticationProperties? properties = null, int status = 0) + { + _kind = kind; + _text = text; + _properties = properties; + _status = status; + } + + /// Render the screen (Page() / View(model)). + public static readonly ScreenOutcome Show = new(ScreenOutcomeKind.Show); + + /// 404. + public static readonly ScreenOutcome NotFound = new(ScreenOutcomeKind.NotFound); + + /// Send the visitor to sign in. + public static readonly ScreenOutcome Challenge = new(ScreenOutcomeKind.Challenge); + + /// Send the visitor to an external provider. + public static ScreenOutcome ChallengeWith(string scheme, AuthenticationProperties properties) + => new(ScreenOutcomeKind.ChallengeWith, scheme, properties: properties); + + /// A local redirect to when it is local, else to the site root. + public static ScreenOutcome Local(string? returnUrl) => new(ScreenOutcomeKind.Local, returnUrl); + + /// A local redirect to exactly (which must be local: an application-relative address). + public static ScreenOutcome LocalExact(string url) => new(ScreenOutcomeKind.LocalExact, url); + + /// A bare status code. + public static ScreenOutcome Status(int code) => new(ScreenOutcomeKind.Status, status: code); + + /// Turns the decision into an action result; renders the screen. + public IActionResult ToResult(IUrlHelper url, Func show) + { + switch (_kind) + { + case ScreenOutcomeKind.Show: return show(); + case ScreenOutcomeKind.NotFound: return new NotFoundResult(); + case ScreenOutcomeKind.Challenge: return new ChallengeResult(); + case ScreenOutcomeKind.ChallengeWith: return new ChallengeResult(_text!, _properties); + case ScreenOutcomeKind.Local: return new LocalRedirectResult(AccountSupport.LocalTarget(url, _text)) { UrlHelper = url }; + case ScreenOutcomeKind.LocalExact: return new LocalRedirectResult(_text!) { UrlHelper = url }; + case ScreenOutcomeKind.Status: return new StatusCodeResult(_status); + default: throw new InvalidOperationException(); + } + } +} diff --git a/src/BaGet.Frontend.Base/Mvc/Screens/ScreenOutcomeKind.cs b/src/BaGet.Frontend.Base/Mvc/Screens/ScreenOutcomeKind.cs new file mode 100644 index 000000000..5761df6f9 --- /dev/null +++ b/src/BaGet.Frontend.Base/Mvc/Screens/ScreenOutcomeKind.cs @@ -0,0 +1,4 @@ +namespace BaGet.Frontend.Mvc.Screens; + +/// What a decided to do. +internal enum ScreenOutcomeKind { Show, NotFound, Challenge, ChallengeWith, Local, LocalExact, Status } diff --git a/src/BaGet.Frontend.Base/Mvc/UI/UiApiInvoker.cs b/src/BaGet.Frontend.Base/Mvc/UI/UiApiInvoker.cs new file mode 100644 index 000000000..6d7f35045 --- /dev/null +++ b/src/BaGet.Frontend.Base/Mvc/UI/UiApiInvoker.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Mvc.UI; + +/// +/// Calls a JSON twin from its view controller without an HTTP hop (decision D1). The twin is created like MVC creates a controller +/// (dependency injection) and given the view action's : the same HttpContext (so the same user, route +/// values, query and repository), the same RouteData and the same . +/// Only the action method runs: the twin's filters do not (its , its base's gate), so a view controller base +/// runs the same and the antiforgery validation of its own first. A propagates +/// to the middleware (503). The twin must not use [ApiController] (see ). +/// +public static class UiApiInvoker +{ + /// Calls on a new that shares the caller's context. + /// The twin controller. + /// The screen's model. + /// The view controller (its is shared). + /// The action to call. + public static async Task> InvokeAsync( + ControllerBase caller, + Func>>> call) + where TApi : ApiControllerBase + { + if (caller == null) throw new ArgumentNullException(nameof(caller)); + if (call == null) throw new ArgumentNullException(nameof(call)); + + var api = ActivatorUtilities.CreateInstance(caller.HttpContext.RequestServices); + api.ControllerContext = caller.ControllerContext; + + return Unwrap(await call(api)); + } + + // The twin answers with a ScreenResult (UiApiResult), or with a plain result: NotFound(), Forbid(), a status code. + private static UiApiResponse Unwrap(ActionResult> action) + { + if (action.Value != null) return new UiApiResponse(action.Value, null); + + switch (action.Result) + { + case ObjectResult { Value: ScreenResult screen }: + return new UiApiResponse(screen, null); + + case NotFoundResult or NotFoundObjectResult: + return new UiApiResponse(ScreenResult.NotFound(), action.Result); + + case UnauthorizedResult or UnauthorizedObjectResult or ChallengeResult: + return new UiApiResponse(ScreenResult.SignIn(), action.Result); + + case ForbidResult: + return new UiApiResponse(ScreenResult.Forbidden(), action.Result); + + case StatusCodeResult { StatusCode: 404 } or ObjectResult { StatusCode: 404 }: + return new UiApiResponse(ScreenResult.NotFound(), action.Result); + + case StatusCodeResult { StatusCode: 401 } or ObjectResult { StatusCode: 401 }: + return new UiApiResponse(ScreenResult.SignIn(), action.Result); + + case StatusCodeResult { StatusCode: 403 } or ObjectResult { StatusCode: 403 }: + return new UiApiResponse(ScreenResult.Forbidden(), action.Result); + + case null: + throw new InvalidOperationException("A UI API action returned neither a ScreenResult nor an action result."); + + default: + // Any other answer (a redirect, a file) is passed on as it is; the decision is "next" for lack of a better word. + return new UiApiResponse(ScreenResult.GoTo(new ScreenNext(null)), action.Result); + } + } +} diff --git a/src/BaGet.Frontend.Base/README.md b/src/BaGet.Frontend.Base/README.md new file mode 100644 index 000000000..284ef6dc5 --- /dev/null +++ b/src/BaGet.Frontend.Base/README.md @@ -0,0 +1,32 @@ +# Extension.BaGet.Frontend.Base + +The MVC base of the screens of [BaGet Extension](https://pieroviano.github.io/BaGet/): the view controller bases, the layout and shared partials, and the link helpers. +It has no controller of its own. The screens are in `Extension.BaGet.Identity.FrontEnd` and `Extension.BaGet.Web.FrontEnd`, which reference this package; +the `/api/ui` twin bases, `[UiApi]`, `[RepositoryPage]`, `ScreenEndpoints` and `RequestPrincipalResolver` are in `Extension.BaGet.Api.Base`, which this package references. + +```powershell +dotnet add package Extension.BaGet.Frontend.Base +``` + +Reference it directly only to write your own screens on the same bases; the business services are in +`Extension.BaGet.Identity.Application` (namespace `BaGet.Identity.Application.*`). + +## Contents + +| Folder / type | Role | +|---|---| +| `Controllers/Base/UiControllerBase` (an `IScreenController`) and `AccountControllerBase`, `AdminControllerBase`, `AccessControllerBase`, `RepositoryControllerBase`, `RetentionControllerBase`, `ReplicationControllerBase` | Bases of the view controllers: antiforgery on every POST (`[AutoValidateAntiforgeryToken]`) and the shared checks (`ScreenGate`: admin or project admin, `NullContext` redirect, maintenance gate on POST, password confirmation) in a fixed order. `AdminControllerBase.Flash(model)` carries `Message`/`Error` across a redirect | +| `Mvc/Attributes/ImplicitPageHandlerAttribute` | The default POST that renders the screen (a form posted to its own URL); not in the route contract | +| `Mvc/Screens` | `ScreenOutcome`, `AccessSupport`, `PackageControllerSupport`, `AccountScreen`: shared screen rules | +| `Mvc/UI/UiApiInvoker` | A view controller calls its twin in process | +| `Routing` | `RepositoryUrlHelper` / `RepositoryUrlHelperFactory` (links stay inside the repository being browsed), `UiActionMap` | +| `TagHelpers/NavLinkTagHelper` | `nav-link`: marks the anchor of the current screen | +| `Views/Shared` | The layout (`_Layout`) and the partials both front ends use; BaGet's views name them (`Layout = "_Layout"`, ``), so a host copy in its own `Views/Shared` or `Pages/Shared` overrides them | + +## Layout + +One type per file, no nested types, namespace = `BaGet.Frontend` + folder (`CodeLayoutTests`). + +## Links + +[UI API](https://pieroviano.github.io/BaGet/ui-api/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Frontend.Base/Routing/RepositoryUrlHelper.cs b/src/BaGet.Frontend.Base/Routing/RepositoryUrlHelper.cs new file mode 100644 index 000000000..72188794a --- /dev/null +++ b/src/BaGet.Frontend.Base/Routing/RepositoryUrlHelper.cs @@ -0,0 +1,81 @@ +using System; +using BaGet.Frontend.Mvc.Attributes; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.Routing; + +namespace BaGet.Frontend.Routing; + +/// +/// Keeps links to repository pages inside the repository being browsed. ASP.NET Core carries ambient route values (here +/// repo) only to links that target the same action, so Url.Action("Show", "Package"), asp-controller="Package" and +/// RedirectToAction("Index", "PackageManage") on a /r/second/… page would otherwise drop the prefix and leave the repository. +/// This helper adds the request's repo as an explicit route value to every link to a controller action marked +/// that does not name one itself. An explicit value always wins, and +/// repo = null is the way to leave for the default repository. A link to any other action is untouched, so no stray ?repo= +/// appears on it. Razor Pages of a host are not touched either: BaGet's screens are controllers, and a screen is addressed by its controller +/// and action (Url.Action, asp-controller/asp-action, RedirectToAction), never by a page name. +/// +public class RepositoryUrlHelper : IUrlHelper +{ + private readonly IUrlHelper _inner; + private readonly UiActionMap? _actions; + + /// MVC's own helper for the same context (the endpoint-routing one), which does the work. + public RepositoryUrlHelper(IUrlHelper inner) + : this(inner, null) + { + } + + internal RepositoryUrlHelper(IUrlHelper inner, UiActionMap? actions) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + _actions = actions; + } + + /// + public ActionContext ActionContext => _inner.ActionContext; + + /// + public string? Action(UrlActionContext actionContext) + { + if (actionContext == null) throw new ArgumentNullException(nameof(actionContext)); + + if (_actions != null && ActionContext.RouteData.Values.TryGetValue(RepositoryPageAttribute.RouteKey, out var repo) && repo is string name) + { + var values = actionContext.Values as RouteValueDictionary + ?? (actionContext.Values == null ? new RouteValueDictionary() : new RouteValueDictionary(actionContext.Values)); + + // A missing controller or action is the current one, as MVC's own helper reads it. + var controller = actionContext.Controller ?? Convert.ToString(ActionContext.RouteData.Values["controller"], System.Globalization.CultureInfo.InvariantCulture); + var action = actionContext.Action ?? Convert.ToString(ActionContext.RouteData.Values["action"], System.Globalization.CultureInfo.InvariantCulture); + if (!values.ContainsKey(RepositoryPageAttribute.RouteKey) && controller != null && action != null && _actions.IsRepositoryAction(controller, action)) + { + values[RepositoryPageAttribute.RouteKey] = name; + actionContext = new UrlActionContext + { + Action = actionContext.Action, + Controller = actionContext.Controller, + Values = values, + Protocol = actionContext.Protocol, + Host = actionContext.Host, + Fragment = actionContext.Fragment, + }; + } + } + + return _inner.Action(actionContext); + } + + /// + public string? Content(string? contentPath) => _inner.Content(contentPath); + + /// + public bool IsLocalUrl(string? url) => _inner.IsLocalUrl(url); + + /// + public string? Link(string? routeName, object? values) => _inner.Link(routeName, values); + + /// + public string? RouteUrl(UrlRouteContext routeContext) => _inner.RouteUrl(routeContext); +} diff --git a/src/BaGet.Frontend.Base/Routing/RepositoryUrlHelperFactory.cs b/src/BaGet.Frontend.Base/Routing/RepositoryUrlHelperFactory.cs new file mode 100644 index 000000000..caa253e3b --- /dev/null +++ b/src/BaGet.Frontend.Base/Routing/RepositoryUrlHelperFactory.cs @@ -0,0 +1,35 @@ +using System; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Frontend.Routing; + +/// +/// Hands out wrapping MVC's default URL helper; one per request, like the default. +/// +public class RepositoryUrlHelperFactory : IUrlHelperFactory +{ + private readonly UrlHelperFactory _default = new(); + + /// + public IUrlHelper GetUrlHelper(ActionContext context) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + var items = context.HttpContext.Items; + RepositoryUrlHelper? helper; + if (items.TryGetValue(typeof(RepositoryUrlHelper), out var cached) + && (helper = cached as RepositoryUrlHelper) != null + && ReferenceEquals(helper.ActionContext.RouteData, context.RouteData) + && ReferenceEquals(helper.ActionContext.ActionDescriptor, context.ActionDescriptor)) + { + return helper; + } + + helper = new RepositoryUrlHelper(_default.GetUrlHelper(context), context.HttpContext.RequestServices.GetService()); + items[typeof(RepositoryUrlHelper)] = helper; + + return helper; + } +} diff --git a/src/BaGet.Frontend.Base/Routing/UiActionMap.cs b/src/BaGet.Frontend.Base/Routing/UiActionMap.cs new file mode 100644 index 000000000..2bd813cc6 --- /dev/null +++ b/src/BaGet.Frontend.Base/Routing/UiActionMap.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using BaGet.Frontend.Mvc.Attributes; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Infrastructure; + +namespace BaGet.Frontend.Routing; + +/// +/// Which controller actions are repository pages (), read from the registered actions. +/// asks it whether a link to controller/action must carry the request's repo. +/// +internal sealed class UiActionMap +{ + private readonly IActionDescriptorCollectionProvider _actions; + private UiActionMapSnapshot? _snapshot; + + public UiActionMap(IActionDescriptorCollectionProvider actions) + { + _actions = actions ?? throw new ArgumentNullException(nameof(actions)); + } + + /// Whether the action . is marked . + public bool IsRepositoryAction(string controller, string action) + => Current().RepositoryActions.Contains(controller + "/" + action); + + private UiActionMapSnapshot Current() + { + var collection = _actions.ActionDescriptors; + var snapshot = Volatile.Read(ref _snapshot); + if (snapshot != null && snapshot.Version == collection.Version) return snapshot; + + var repositoryActions = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var action in collection.Items.OfType()) + { + if (action.EndpointMetadata.OfType().Any()) repositoryActions.Add(action.ControllerName + "/" + action.ActionName); + } + + snapshot = new UiActionMapSnapshot(collection.Version, repositoryActions); + Volatile.Write(ref _snapshot, snapshot); + + return snapshot; + } +} diff --git a/src/BaGet.Frontend.Base/Routing/UiActionMapSnapshot.cs b/src/BaGet.Frontend.Base/Routing/UiActionMapSnapshot.cs new file mode 100644 index 000000000..7500a8c79 --- /dev/null +++ b/src/BaGet.Frontend.Base/Routing/UiActionMapSnapshot.cs @@ -0,0 +1,6 @@ +using System.Collections.Generic; + +namespace BaGet.Frontend.Routing; + +/// What knows about the controller actions at one version of the action descriptors. +internal sealed record UiActionMapSnapshot(int Version, HashSet RepositoryActions); diff --git a/src/BaGet.Frontend.Base/TagHelpers/NavLinkTagHelper.cs b/src/BaGet.Frontend.Base/TagHelpers/NavLinkTagHelper.cs new file mode 100644 index 000000000..98f836a0e --- /dev/null +++ b/src/BaGet.Frontend.Base/TagHelpers/NavLinkTagHelper.cs @@ -0,0 +1,98 @@ +using System; +using BaGet.Frontend.Mvc.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Razor.TagHelpers; +using BaGet.Identity.Application.Screens; + +namespace BaGet.Frontend.TagHelpers; + +[HtmlTargetElement(Attributes = "nav-link")] +public class NavLinkTagHelper : TagHelper +{ + private const string ActiveClass = "active"; + private const string PackagesPath = "/packages"; + + private readonly IHttpContextAccessor _accessor; + + public NavLinkTagHelper(IHttpContextAccessor accessor) + { + _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor)); + } + + /// The controller the link points at (asp-controller); with it names the screen the link is active on. + [HtmlAttributeName("asp-controller")] + public string? Controller { get; set; } + + /// The action the link points at (asp-action). + [HtmlAttributeName("asp-action")] + public string? Action { get; set; } + + public override void Process(TagHelperContext context, TagHelperOutput output) + { + if (!IsActiveLink(context)) + { + return; + } + + // This helper applies to any element carrying "nav-link", so it adds its class + // instead of replacing the classes the markup already set. + var existing = output.Attributes.ContainsName("class") + ? output.Attributes["class"].Value?.ToString() + : null; + + output.Attributes.SetAttribute("class", WithActiveClass(existing)); + } + + private static string WithActiveClass(string? classes) + { + if (string.IsNullOrWhiteSpace(classes)) + { + return ActiveClass; + } + + foreach (var name in classes.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + if (string.Equals(name, ActiveClass, StringComparison.Ordinal)) + { + return classes; + } + } + + return $"{classes} {ActiveClass}"; + } + + private bool IsActiveLink(TagHelperContext context) + { + // A link to a Razor Page (a host's own, in an overridden layout) never names a BaGet screen, so it is never the + // current one here; without this it would fall into the packages-link case below. + if (context.AllAttributes.ContainsName("asp-page")) return false; + + var httpContext = _accessor.HttpContext; + if (httpContext == null) return false; + + // The screen of the endpoint: the controller and default GET action of the screen the current action belongs to. + var screen = ScreenEndpoints.ScreenOf(httpContext.GetEndpoint()); + if (screen == null) return false; + + // When the link names a screen, that name alone decides whether it is active. + // Falling through to the path check below would light up every nav link on the + // pages that check covers. + if (!string.IsNullOrEmpty(Controller) || !string.IsNullOrEmpty(Action)) + { + return string.Equals(screen.Controller, Controller, StringComparison.OrdinalIgnoreCase) + && string.Equals(screen.Action, Action, StringComparison.OrdinalIgnoreCase); + } + + // The packages link names no screen: both "/" and "/packages" render the index. + if (screen != ScreenCatalog.Index) return false; + + // Routing is case-insensitive and tolerates a trailing slash, so the comparison + // must be too. + #pragma warning disable CS8602 + var path = httpContext.Request.Path.Value?.TrimEnd('/'); + #pragma warning restore CS8602 + + return string.IsNullOrEmpty(path) + || string.Equals(path, PackagesPath, StringComparison.OrdinalIgnoreCase); + } +} \ No newline at end of file diff --git a/src/BaGet.Frontend.Base/Views/Shared/_Avatar.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_Avatar.cshtml new file mode 100644 index 000000000..4ce8eccad --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_Avatar.cshtml @@ -0,0 +1,10 @@ +@model BaGet.Core.AvatarModel +@* A Gravatar when there is an address for it, otherwise (Site:UseGravatar off) the account's initial. *@ +@if (Model.Url != null) +{ + +} +else +{ + +} diff --git a/src/BaGet.Frontend.Base/Views/Shared/_ConfirmPassword.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_ConfirmPassword.cshtml new file mode 100644 index 000000000..379be9135 --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_ConfirmPassword.cshtml @@ -0,0 +1,13 @@ +@model BaGet.Identity.Application.Models.Shared.ConfirmPasswordView + +@if (Model.HasPassword) +{ +
+ + +
+} +else +{ + +} diff --git a/src/BaGet.Frontend.Base/Views/Shared/_Explanation.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_Explanation.cshtml new file mode 100644 index 000000000..971934e2e --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_Explanation.cshtml @@ -0,0 +1,42 @@ +@using BaGet.Frontend.Mvc.Screens +@model BaGet.Core.AccessExplanation + +@* The actions someone holds in a repository and the grants behind them (shared by the account, user and repository pages). *@ +

+ Actions: + @AccessSupport.Words(Model.Actions) +

+@if (Model.Override != null) +{ +

@Model.Override

+} +else if (Model.Reasons.Count == 0) +{ +

No permission target or project role grants anything.

+} +else +{ + + + + + + @foreach (var reason in Model.Reasons) + { + + + + + + + + } + +
SourceThroughGrantsAppliesPackages
@reason.Source@reason.Principal@AccessSupport.Words(reason.Granted) + @AccessSupport.Words(reason.Effective) + @if (reason.Note != null) + { +
@reason.Note + } +
@(reason.Packages ?? "all")
+} diff --git a/src/BaGet.Frontend.Base/Views/Shared/_Layout.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_Layout.cshtml new file mode 100644 index 000000000..652b91ed2 --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_Layout.cshtml @@ -0,0 +1,281 @@ +@using BaGet.Frontend.Mvc.Attributes +@using Microsoft.Extensions.DependencyInjection +@using BaGet.Identity.Application.Screens +@inject Microsoft.Extensions.Options.IOptions Accounts +@inject Microsoft.Extensions.Options.IOptionsSnapshot Site +@inject BaGet.Core.IRepositoryContext RepositoryContext +@inject BaGet.Core.IRepositoryAccess RepositoryAccess +@inject Microsoft.Extensions.Options.IOptionsSnapshot Options +@{ + var hideSearchBar = ViewData["HideSearchBar"] is true; + // Type-ahead for the search boxes: the repository's own V3 autocomplete resource (site.js fills the datalist). + var autocompleteUrl = Context.RequestServices.GetService()?.GetAutocompleteResourceUrl(); + + // No Upload entry where an upload is impossible (read-only, a closed maintenance gate, nothing to authenticate with). + var canUpload = BaGet.Web.Application.Services.UploadAvailability.IsPossible( + Options.Value, Accounts.Value, Context.RequestServices.GetService()); + + // The repository this page shows. Links in the header stay inside it ("r/{name}/" in front), and a page that acts + // on a repository ([RepositoryPage]) offers the switcher when more than one is readable. The list + // comes from IRepositoryAccess, the one place that decides who sees which repository. + var repository = RepositoryContext.Current; + var repositoryPrefix = repository.PathPrefix; + // An npm repository has its own pages ([RepositoryPage(Format = ...)]): the header leads to them. + var isNpm = repository.Format == BaGet.Core.RepositoryFormat.Npm; + var hasOwnPages = repository.Format != BaGet.Core.RepositoryFormat.NuGet; + // The path under the repository that lists its packages: the format's own browse page, or NuGet's (the front page when asked for the brand). + string BrowseSegment(BaGet.Core.RepositoryFormat format, string nuGet) => format switch + { + BaGet.Core.RepositoryFormat.Npm => "npm-packages", + BaGet.Core.RepositoryFormat.Maven => "maven-artifacts", + BaGet.Core.RepositoryFormat.Docker => "docker-images", + _ => nuGet, + }; + // A repository page is a controller action marked [RepositoryPage]. + var isRepositoryPage = ViewContext.ActionDescriptor.EndpointMetadata.OfType().Any(); + IReadOnlyList switchable = Array.Empty(); + if (isRepositoryPage && RepositoryAccess.SupportsMultipleRepositories) + { + var readable = await RepositoryAccess.ReadableAsync(User, Context.RequestAborted); + if (readable.Count > 1) switchable = readable; + } + + // The signed-in user's avatar, for the account menu. The service exists only while accounts are enabled. + string? headerAvatar = null; + var isAdministrator = false; + if (Accounts.Value.Enabled && User.Identity?.IsAuthenticated == true) + { + // Likewise the administrator check: read from the database, so a demotion shows at once. + var administrators = Context.RequestServices.GetService(); + if (administrators != null) + { + isAdministrator = await administrators.IsAdministratorAsync(User, Context.RequestAborted); + } + + var avatars = Context.RequestServices.GetService(); + if (avatars != null) + { +#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. + headerAvatar = (await avatars.GetUrlsAsync(new[] { User.Identity.Name }, 24, Context.RequestAborted)) +#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. + .GetValueOrDefault(User.Identity.Name); + } + } +} + + + + + + + + + + + + + + + @ViewData["Title"]@(repository.IsDefault ? "" : " (" + repository.Name + ")") - BaGet Extension + + + + + @{ + var maintenanceGate = Context.RequestServices.GetService(); + } + @if (maintenanceGate != null && maintenanceGate.IsClosed) + { +
+
+ Read-only. Changes are refused for now: @maintenanceGate.Reason. + @if (maintenanceGate.IsClosedUntilRestart) + { + Restart the server to finish. + } +
+
+ } + +
+ @RenderBody() +
+ + + + + + + + + + @await RenderSectionAsync("Scripts", required: false) + + diff --git a/src/BaGet.Frontend.Base/Views/Shared/_PatternFields.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_PatternFields.cshtml new file mode 100644 index 000000000..762f4324d --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_PatternFields.cshtml @@ -0,0 +1,47 @@ +@model BaGet.Identity.Application.Models.Policies.PatternFieldsView + +
+ + + Repository names or globs, one per line: * is every repository, second one, team-* a family. +
+
+ + + Package ID globs, one per line, e.g. Contoso.*. Empty means every package. +
+
+ + + Package ID globs the target leaves out, whatever the include patterns say. +
+
+ + + +
+ +@if (Model.Preview != null) +{ +
+

+ Repositories matched: + @if (Model.Preview.Repositories.Count == 0) + { + none + } + else + { + @string.Join(", ", Model.Preview.Repositories) + } +

+ @if (Model.Preview.Test != null) + { +

+ @Model.Preview.TestPackage + @(Model.Preview.Test.Matches ? "matches" : "does not match") + (@Model.Preview.Test.Explanation). +

+ } +
+} diff --git a/src/BaGet.Frontend.Base/Views/Shared/_Reauthenticate.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_Reauthenticate.cshtml new file mode 100644 index 000000000..e56419813 --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_Reauthenticate.cshtml @@ -0,0 +1,17 @@ +@model BaGet.Identity.Application.Models.Account.ReauthenticateView + +
+ @if (Model.Done) + { +

You signed in again with your provider. This lasts a few minutes.

+ } + else if (Model.Available) + { +

This account has no password. Confirm it is you by signing in again with your provider.

+ + } + else + { +

This account has no password and no provider is available to confirm it is you. Ask an administrator to reset the password.

+ } +
diff --git a/src/BaGet.Frontend.Base/Views/Shared/_RemoteFields.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_RemoteFields.cshtml new file mode 100644 index 000000000..d82146cb2 --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_RemoteFields.cshtml @@ -0,0 +1,116 @@ +@model BaGet.Identity.Application.Models.Repositories.RemoteFormModel + +@* The upstream fields of a remote repository; rendered with so the names carry the prefix. *@ +
+ + @if (Model.EndpointFromMirror) + { + +

Set by the Mirror:PackageSource, Mirror:Legacy and Mirror:PackageDownloadTimeoutSeconds settings while Mirror:Enabled is on; change them on the Settings page.

+ } + else + { + @if (Model.Format == BaGet.Core.RepositoryFormat.Npm) + { + +

The base URL of an npm registry (packages are at {url}/{name}). Put credentials in the fields below, not in the URL.

+ } + else if (Model.Format == BaGet.Core.RepositoryFormat.Docker) + { + +

The address of a Docker registry (the root, not /v2): Docker Hub is https://registry-1.docker.io (an official image such as nginx is asked for as library/nginx), GitHub is https://ghcr.io, Quay is https://quay.io. Put credentials in the fields below, not in the URL.

+ } + else if (Model.Format == BaGet.Core.RepositoryFormat.Maven) + { + +

The root of a Maven repository (files are at {url}/{group/as/folders}/{artifact}/{version}/{file}); Maven Central is https://repo.maven.apache.org/maven2/. Put credentials in the fields below, not in the URL.

+ } + else + { + +

A V3 index.json URL or a V2 feed URL (for npm, the registry's base URL). Put credentials in the fields below, not in the URL.

+ } + } +
+@if (Model.Format == BaGet.Core.RepositoryFormat.Npm) +{ + +

Protocol: the npm registry protocol.

+} +else if (Model.Format == BaGet.Core.RepositoryFormat.Maven) +{ + +

Protocol: the Maven 2 repository layout.

+} +else if (Model.Format == BaGet.Core.RepositoryFormat.Docker) +{ + +

Protocol: the Docker registry API (OCI Distribution), with the registry's token authentication.

+} +else +{ +
+ + @if (Model.EndpointFromMirror) + { + + + } + else + { + + } +
+} +
+ + +
+
+ + +

+ Sent as HTTP Basic to the upstream's own host only (an npm upstream with no user name gets it as a bearer token, npm's _authToken; a Maven upstream gets Basic, like settings.xml's <server>; a Docker registry gets the pair at its token service, as docker login does, or a password with no user name as a bearer token - leave both blank for anonymous pulls, which Docker Hub allows with a rate limit). Stored protected (ASP.NET Core data protection), never shown again, never logged. + @if (Model.HasPassword) + { + A password is stored; leave blank to keep it. + } +

+ @if (Model.HasPassword) + { +
+ +
+ } +
+
+ + +

How long the upstream's version lists and metadata are reused. 0 asks the upstream every time. An expired answer is still served while the upstream is down.

+
+
+ + +

How long "the upstream does not have it" (404) is remembered. A failure to reach the upstream is never remembered as "not found".

+
+
+ + @if (Model.EndpointFromMirror) + { + + } + else + { + + } +
+
+ +

On: packages (Maven: files; Docker: manifests and layers, which are kept while they stream to the client) are kept (database and files) the first time they are requested and served from there afterwards, also while the upstream is down. Off: pass-through; metadata and downloads come from the upstream each time and nothing is kept (search and package pages stay empty).

+
+
+ +

Never contact the upstream: only stored packages and remembered answers are served.

+
diff --git a/src/BaGet.Frontend.Base/Views/Shared/_ReplicationFields.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_ReplicationFields.cshtml new file mode 100644 index 000000000..b73c2272c --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_ReplicationFields.cshtml @@ -0,0 +1,72 @@ +@model BaGet.Identity.Application.Models.Policies.ReplicationFieldsView +@{ + var f = Model.Form; + var p = Model.IdPrefix; +} + +
+ + +
+
+ + + + @foreach (var repository in Model.Repositories) + { + + } + + A local repository (a remote one caches an upstream and a virtual one stores nothing). +
+
+ + +
+
+ + +
+
+ + + default or the repository name; it must be of the same format. +
+
+ + + An administrator's key with the admin:api scope on the peer. Sent to the peer address only; stored protected; never shown again. + @if (Model.HasApiKey) + { +
+ } +
+ +

When

+
+ +
+
+ +
+
+ + + Empty: only when started here. +
+ +

Rules

+
+ +
+
+ + + NuGet keeps no content digest, so two servers holding the same id and version are taken to hold the same package. +
diff --git a/src/BaGet.Frontend.Base/Views/Shared/_RetentionPolicyFields.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_RetentionPolicyFields.cshtml new file mode 100644 index 000000000..7790ee92b --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_RetentionPolicyFields.cshtml @@ -0,0 +1,79 @@ +@model BaGet.Identity.Application.Models.Policies.RetentionFieldsView +@{ + var f = Model.Form; + var p = Model.IdPrefix; +} + +
+ + +
+
+ + +
+
+ + + + @foreach (var repository in Model.Repositories) + { + + } + @foreach (var project in Model.Projects) + { + + } + + Virtual repositories store nothing, so no policy applies to them. +
+
+ + + Globs with *, one per line, for package ids, npm names, Maven group:artifact or Docker images. Empty: every artifact. +
+ +

Rules

+

A version is deleted when any rule selects it and no legal hold covers it. Leave a rule empty to switch it off.

+
+ + +
+
+ + +
+
+ + + Counts from the last recorded download, or from the publish time when none was recorded (downloads before this feature are not known). +
+
+ +
+
+ + + Remote repositories only: the least recently used cached versions are deleted until the cache fits. +
+
+ + + Counted from the push. Manifests an index or a referrer relationship still needs are kept. +
+
+ +
+ +

When

+
+ + + Empty: only when you press Run now. Scheduled runs happen only while the policy is enabled, and wait while the server is read-only. +
+
+ +
diff --git a/src/BaGet.Frontend.Base/Views/Shared/_ScanFindingsTable.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_ScanFindingsTable.cshtml new file mode 100644 index 000000000..a8e340bc0 --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_ScanFindingsTable.cshtml @@ -0,0 +1,36 @@ +@model BaGet.Core.ScanResult +@{ + string LabelOf(int severity) => severity switch { 3 => "label-danger", 2 => "label-warning", 1 => "label-info", _ => "label-default" }; +} + +@if (Model.Findings != null && Model.Findings.Count > 0) +{ + + + + @foreach (var finding in Model.Findings) + { + + + + + + + + } + +
SeverityAdvisoryComponentFixed inSummary
@BaGet.Core.ScanSeverities.Name(finding.Severity) + @if (Uri.TryCreate(finding.AdvisoryUrl, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp)) + { + @finding.VulnerabilityId + } + else + { + @finding.VulnerabilityId + } + @finding.Component @finding.ComponentVersion@(finding.FixedVersion ?? "-")@finding.Summary
+ @if (Model.FindingCount >= BaGet.Core.ScanService.MaxFindingsPerResult) + { +

Only the first @BaGet.Core.ScanService.MaxFindingsPerResult findings, worst first, are kept.

+ } +} diff --git a/src/BaGet.Frontend.Base/Views/Shared/_ScanPolicyForm.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_ScanPolicyForm.cshtml new file mode 100644 index 000000000..dd31a523b --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_ScanPolicyForm.cshtml @@ -0,0 +1,43 @@ +@model BaGet.Identity.Application.Models.Policies.ScanPolicyFormView +@{ + var severities = new (string Value, string Text)[] { ("", "Off"), ("0", "Low and above"), ("1", "Moderate and above"), ("2", "High and above"), ("3", "Critical only") }; +} + +
+ + +

The package page shows a warning for a version with a finding at this severity or above.

+
+
+ + +

Downloading a version with a finding at this severity or above is refused with 403 and the reason, on every route and page of every format. Docker: refused when the image manifest is pulled.

+
+
+ + +

A deploy whose artifact or declared dependencies have such a finding is refused with 403 and the reason, before anything is stored. A container image is scanned after it is pushed and removed again when it reaches the threshold. A vulnerability source that is down lets the deploy through.

+
+
+ + +
+ diff --git a/src/BaGet.Frontend.Base/Views/Shared/_SettingField.cshtml b/src/BaGet.Frontend.Base/Views/Shared/_SettingField.cshtml new file mode 100644 index 000000000..67c19dcf8 --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/Shared/_SettingField.cshtml @@ -0,0 +1,99 @@ +@model BaGet.Core.SettingState +@{ + var d = Model.Descriptor; + var id = d.Key.Replace(':', '_'); + var name = SettingsForm.ValuePrefix + d.Key; + var mask = SettingPresentation.Mask; + var siblings = ViewData["Siblings"] as IEnumerable ?? Enumerable.Empty(); + var dependsValue = SettingPresentation.DependsValue(d, siblings); + var example = SettingPresentation.ExampleFor(d, dependsValue); + var hasExamples = d.ExampleDependsOnKey != null && d.Examples != null && d.Examples.Count > 0; +} + +
+ + @if (d.RequiresRestart) { Restart required } + @if (Model.IsOverridden) { Saved override } + @if (Model.ShadowedBy != null) { Overridden by @Model.ShadowedBy } + + @switch (d.Kind) + { + case SettingKind.Boolean: +
+ +
+ break; + case SettingKind.Integer: + + break; + case SettingKind.Number: + + break; + case SettingKind.Enum: + + break; + case SettingKind.StringList: + +

One entry per line.

+ break; + case SettingKind.ReadOnly: +
@(d.IsSensitive ? (Model.HasValue ? mask : string.Empty) : Model.EffectiveValue)
+

Edit the configuration file.

+ break; + default: + if (d.IsSensitive) + { + +
+ } + else + { + + } + break; + } + + @if (hasExamples) + { + @* The example is only a hint: a placeholder (when nothing is stored) and this line, never the value. + Settings.cshtml's script rewrites them when the selector changes, reading the data-examples JSON attribute (keyed by the lower-cased value, so no value can collide + with the data-example-source/-target/-stored control attributes). + A TagBuilder encodes every attribute value and text. *@ + var line = new TagBuilder("p"); + line.AddCssClass("help-block"); + line.AddCssClass("setting-example"); + line.Attributes["id"] = id + "_example"; + line.Attributes["data-example-source"] = d.ExampleDependsOnKey!.Replace(':', '_'); + line.Attributes["data-example-target"] = id; + line.Attributes["data-example-stored"] = Model.HasValue ? "true" : "false"; + if (example == null) line.Attributes["hidden"] = "hidden"; + line.Attributes["data-examples"] = SettingPresentation.ExamplesJson(d.Examples!); + + var type = new TagBuilder("span"); + type.Attributes["data-example-type"] = string.Empty; + type.InnerHtml.Append(dependsValue ?? string.Empty); + var text = new TagBuilder("code"); + text.Attributes["data-example-text"] = string.Empty; + text.InnerHtml.Append(example ?? string.Empty); + + line.InnerHtml.Append("Example for "); + line.InnerHtml.AppendHtml(type); + line.InnerHtml.Append(": "); + line.InnerHtml.AppendHtml(text); + @line + } + @if (!string.IsNullOrEmpty(d.Description)) {

@d.Description

} + @if (Model.ShadowedBy != null) {

The saved value has no effect while the @Model.ShadowedBy sets this key.

} + @if (Model.IsOverridden) + { +
+ } +
diff --git a/src/BaGet.Frontend.Base/Views/_ViewImports.cshtml b/src/BaGet.Frontend.Base/Views/_ViewImports.cshtml new file mode 100644 index 000000000..011eda9bb --- /dev/null +++ b/src/BaGet.Frontend.Base/Views/_ViewImports.cshtml @@ -0,0 +1,17 @@ +@using BaGet +@using BaGet.Core +@using Microsoft.AspNetCore.Html +@using BaGet.Identity.Application.Links +@using BaGet.Identity.Application.Models.Account +@using BaGet.Identity.Application.Models.Operations +@using BaGet.Identity.Application.Models.Packages +@using BaGet.Identity.Application.Models.Policies +@using BaGet.Identity.Application.Models.Settings +@using BaGet.Identity.Application.Models.Shared +@using BaGet.Identity.Application.Models.Users +@using BaGet.Identity.Application.Security +@using BaGet.Identity.Application.Services.Accounts +@using BaGet.Identity.Application.UseCases.Access +@namespace BaGet.Frontend.Views +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers +@addTagHelper *, BaGet.Frontend.Base diff --git a/src/BaGet.Web/Pages/_ViewStart.cshtml b/src/BaGet.Frontend.Base/Views/_ViewStart.cshtml similarity index 100% rename from src/BaGet.Web/Pages/_ViewStart.cshtml rename to src/BaGet.Frontend.Base/Views/_ViewStart.cshtml diff --git a/src/BaGet.Gcp/BaGet.Gcp.csproj b/src/BaGet.Gcp/BaGet.Gcp.csproj index 3dc33ae66..0a86fe766 100644 --- a/src/BaGet.Gcp/BaGet.Gcp.csproj +++ b/src/BaGet.Gcp/BaGet.Gcp.csproj @@ -1,18 +1,31 @@ - netstandard2.0 - + net10.0 + latest NuGet;Google;Cloud - The libraries to host BaGet on the Google Cloud Platform. + The libraries to host BaGet Extension on the Google Cloud Platform. + enable - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs b/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs index 5dcb1bb8a..c1ed91e3c 100644 --- a/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs +++ b/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs @@ -4,34 +4,35 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet +namespace BaGet; + +public static class GoogleCloudApplicationExtensions { - public static class GoogleCloudApplicationExtensions + public static BaGetApplication AddGoogleCloudStorage(this BaGetApplication app) { - public static BaGetApplication AddGoogleCloudStorage(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("GoogleCloud")) return null; + app.Services.AddProvider((provider, config) => + { + #pragma warning disable CS8603 + if (!config.HasStorageType("GoogleCloud")) return null; + #pragma warning restore CS8603 - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddGoogleCloudStorage( - this BaGetApplication app, - Action configure) - { - app.AddGoogleCloudStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddGoogleCloudStorage( + this BaGetApplication app, + Action configure) + { + app.AddGoogleCloudStorage(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Gcp/GoogleCloudStorageOptions.cs b/src/BaGet.Gcp/GoogleCloudStorageOptions.cs index 6b9a2ff42..556199081 100644 --- a/src/BaGet.Gcp/GoogleCloudStorageOptions.cs +++ b/src/BaGet.Gcp/GoogleCloudStorageOptions.cs @@ -1,11 +1,10 @@ using System.ComponentModel.DataAnnotations; using BaGet.Core; -namespace BaGet.Gcp +namespace BaGet.Gcp; + +public class GoogleCloudStorageOptions : StorageOptions { - public class GoogleCloudStorageOptions : StorageOptions - { - [Required] - public string BucketName { get; set; } - } -} + [Required] + public string? BucketName { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Gcp/GoogleCloudStorageService.Streaming.cs b/src/BaGet.Gcp/GoogleCloudStorageService.Streaming.cs new file mode 100644 index 000000000..14e20a125 --- /dev/null +++ b/src/BaGet.Gcp/GoogleCloudStorageService.Streaming.cs @@ -0,0 +1,414 @@ +using System; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Google; +using Google.Cloud.Storage.V1; + +namespace BaGet.Gcp; + +/// +/// Streaming uploads on Cloud Storage resumable upload sessions (). A session writes to a +/// temporary object under .uploads/ (the final name is only known at commit); at commit the session is finalised, the +/// object is verified and copied server side to its final name with ifGenerationMatch=0. +/// +/// +/// The sessions are driven over HTTP directly (the client library resumes from a seekable whole-content stream, which a +/// chunked upload does not have). GCS wants every chunk but the last to be a multiple of 256 KiB, so bytes short of a chunk are +/// kept in a small .tail object (at most ) that the next chunk is prepended with; the state of an +/// upload is the session's own persisted size plus that tail, so any node can take the next chunk. Memory per request: one chunk. +/// The upload id is opaque: the upload's name and the session URI. +/// +public partial class GoogleCloudStorageService +{ + /// The chunk size: a multiple of 256 KiB, as resumable uploads require. + internal const int ChunkSize = 8 * 1024 * 1024; + + private const string GenericContentType = "application/octet-stream"; + + public async Task BeginUploadAsync(string contentType, CancellationToken cancellationToken = default) + { + var id = Guid.NewGuid().ToString("N"); + using var storage = await CreateClientAsync().ConfigureAwait(false); + + var url = UploadBase(storage) + "b/" + Uri.EscapeDataString(_bucketName!) + "/o?uploadType=resumable&name=" + Uri.EscapeDataString(TempName(id)); + using var request = new HttpRequestMessage(HttpMethod.Post, url) + { + Content = new StringContent("{\"name\":\"" + TempName(id) + "\"}", Encoding.UTF8, "application/json"), + }; + request.Headers.TryAddWithoutValidation("X-Upload-Content-Type", string.IsNullOrEmpty(contentType) ? GenericContentType : contentType); + + using var response = await storage.Service.HttpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + var session = response.Headers.Location ?? throw new IOException("The upload session was created without a location."); + + return Convert.ToBase64String(Encoding.UTF8.GetBytes(id + "|" + session.AbsoluteUri)) + .Replace('+', '-').Replace('/', '_').TrimEnd('='); + } + + public async Task AppendAsync(string uploadId, long offset, Stream chunk, CancellationToken cancellationToken = default) + { + if (chunk == null) throw new ArgumentNullException(nameof(chunk)); + + var (id, session) = Decode(uploadId); + using var storage = await CreateClientAsync().ConfigureAwait(false); + var state = await ReadStateAsync(storage, id, session, uploadId, cancellationToken).ConfigureAwait(false); + if (state.Length != offset) throw new StorageUploadOffsetException(state.Length, offset); + + var tracked = UploadDigestTracker.Shared.Track(uploadId, offset, chunk); + try + { + var persisted = state.Persisted; + + var tail = await StreamPartitioner.SplitAsync( + tracked, + state.Tail, + ChunkSize, + async (part, ct) => + { + await PutRangeAsync(storage, session, persisted, part, total: null, ct).ConfigureAwait(false); + persisted += part.Length; + }, + cancellationToken).ConfigureAwait(false); + + if (tail.Length > 0) + { + await PutTailAsync(storage, TailName(id), tail, cancellationToken).ConfigureAwait(false); + } + else if (state.Tail.Length > 0) + { + await DeleteQuietlyAsync(storage, TailName(id), cancellationToken).ConfigureAwait(false); + } + + var length = persisted + tail.Length; + tracked.Complete(length); + return length; + } + catch + { + tracked.Fail(); + throw; + } + } + + public async Task GetUploadLengthAsync(string uploadId, CancellationToken cancellationToken = default) + { + try + { + var (id, session) = Decode(uploadId); + using var storage = await CreateClientAsync().ConfigureAwait(false); + return (await ReadStateAsync(storage, id, session, uploadId, cancellationToken).ConfigureAwait(false)).Length; + } + catch (StorageUploadNotFoundException) + { + return null; + } + } + + public async Task CommitAsync(string uploadId, string path, string? expectedSha256, CancellationToken cancellationToken = default) + { + var (id, session) = Decode(uploadId); + using var storage = await CreateClientAsync().ConfigureAwait(false); + var state = await ReadStateAsync(storage, id, session, uploadId, cancellationToken).ConfigureAwait(false); + var sha = UploadDigestTracker.Shared.TryComplete(uploadId, state.Length); + var temp = TempName(id); + var finalName = CoercePath(path); + + try + { + if (sha != null && expectedSha256 != null && !string.Equals(expectedSha256, sha, StringComparison.OrdinalIgnoreCase)) + { + await CancelSessionAsync(storage, session).ConfigureAwait(false); + throw new StorageDigestMismatchException(expectedSha256, sha); + } + + // Finalise the session with the tail (or with an empty body when everything is persisted). + await PutRangeAsync(storage, session, state.Persisted, state.Tail, total: state.Length, cancellationToken).ConfigureAwait(false); + + if (sha == null) + { + using var read = await GetRangeAsync(temp, 0, null, cancellationToken).ConfigureAwait(false) + ?? throw new StorageUploadNotFoundException(uploadId); + sha = await StreamingStorage.Sha256HexAsync(read, cancellationToken).ConfigureAwait(false); + } + + StreamingStorage.VerifyDigest(expectedSha256, sha); + + try + { + await storage.CopyObjectAsync( + _bucketName, + temp, + _bucketName, + finalName, + new CopyObjectOptions { IfGenerationMatch = 0 }, + cancellationToken).ConfigureAwait(false); + return new StorageCommitResult(StoragePutResult.Success, state.Length, sha); + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.PreconditionFailed) + { + string existing; + using (var stored = await GetRangeAsync(finalName, 0, null, cancellationToken).ConfigureAwait(false) ?? Stream.Null) + { + existing = await StreamingStorage.Sha256HexAsync(stored, cancellationToken).ConfigureAwait(false); + } + + return new StorageCommitResult( + string.Equals(existing, sha, StringComparison.Ordinal) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict, + state.Length, + sha); + } + } + finally + { + UploadDigestTracker.Shared.Forget(uploadId); + await DeleteQuietlyAsync(storage, temp, CancellationToken.None).ConfigureAwait(false); + await DeleteQuietlyAsync(storage, TailName(id), CancellationToken.None).ConfigureAwait(false); + } + } + + public async Task AbortAsync(string uploadId, CancellationToken cancellationToken = default) + { + UploadDigestTracker.Shared.Forget(uploadId); + + string id; + Uri session; + try + { + (id, session) = Decode(uploadId); + } + catch (StorageUploadNotFoundException) + { + return; + } + + using var storage = await CreateClientAsync().ConfigureAwait(false); + await CancelSessionAsync(storage, session).ConfigureAwait(false); + await DeleteQuietlyAsync(storage, TempName(id), cancellationToken).ConfigureAwait(false); + await DeleteQuietlyAsync(storage, TailName(id), cancellationToken).ConfigureAwait(false); + } + + public async Task GetInfoAsync(string path, CancellationToken cancellationToken = default) + { + using var storage = await CreateClientAsync().ConfigureAwait(false); + try + { + var obj = await storage.GetObjectAsync(_bucketName, CoercePath(path), cancellationToken: cancellationToken).ConfigureAwait(false); + return new StorageBlobInfo(checked((long)(obj.Size ?? 0)), obj.ContentType); + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) + { + return null; + } + } + + public async Task GetRangeAsync(string path, long offset, long? length, CancellationToken cancellationToken = default) + { + var info = await GetInfoAsync(path, cancellationToken).ConfigureAwait(false); + if (info == null) return null; + + var count = StreamingStorage.ResolveRange(info.Length, offset, length); + if (count == 0) return Stream.Null; + + var storage = await CreateClientAsync().ConfigureAwait(false); + var url = storage.Service.BaseUri + "b/" + Uri.EscapeDataString(_bucketName!) + "/o/" + Uri.EscapeDataString(CoercePath(path)) + "?alt=media"; + + // Bounded range requests, each re-requested from the exact byte if its connection drops: one GET of many GB must not be the unit of failure. + var windows = new WindowedReadStream( + async (from, size, ct) => + { + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.Range = new RangeHeaderValue(from, from + size - 1); + + var response = await storage.Service.HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + try + { + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); + + // Servers that ignore Range answer 200 with the whole object: skip to the offset and stop at the count. + if (response.StatusCode == HttpStatusCode.OK && from > 0) + { + var skip = new byte[81920]; + for (var left = from; left > 0;) + { + var read = await body.ReadAsync(skip.AsMemory(0, (int)Math.Min(skip.Length, left)), ct).ConfigureAwait(false); + if (read == 0) break; + left -= read; + } + } + + return new OwnedReadStream(new RangeReadStream(body, size), response); + } + catch + { + response.Dispose(); + throw; + } + }, + offset, + count); + + return new OwnedReadStream(windows, storage); + } + + private string TempName(string id) => StreamingStorage.UploadsFolder + "/" + id; + + private string TailName(string id) => StreamingStorage.UploadsFolder + "/" + id + ".tail"; + + private static string UploadBase(StorageClient storage) + => storage.Service.BaseUri.Replace("/storage/v1/", "/upload/storage/v1/"); + + private static (string Id, Uri Session) Decode(string uploadId) + { + try + { + var padded = uploadId.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + (4 - padded.Length % 4) % 4, '='); + var text = Encoding.UTF8.GetString(Convert.FromBase64String(padded)); + var bar = text.IndexOf('|'); + if (bar == 32 && Guid.TryParseExact(text.Substring(0, bar), "N", out _) + && Uri.TryCreate(text.Substring(bar + 1), UriKind.Absolute, out var session)) + { + return (text.Substring(0, bar), session); + } + } + catch (FormatException) + { + } + + throw new StorageUploadNotFoundException(uploadId); + } + + private sealed record UploadState(long Persisted, byte[] Tail) + { + public long Length => Persisted + Tail.Length; + } + + private async Task ReadStateAsync(StorageClient storage, string id, Uri session, string uploadId, CancellationToken cancellationToken) + { + // "bytes */*" asks how much the session holds: 308 with "Range: bytes=0-N" (no header = nothing yet). + using var response = await SendIdempotentAsync( + storage, + () => + { + var request = new HttpRequestMessage(HttpMethod.Put, session) { Content = new ByteArrayContent(Array.Empty()) }; + request.Content.Headers.TryAddWithoutValidation("Content-Range", "bytes */*"); + return request; + }, + cancellationToken).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Gone) + { + throw new StorageUploadNotFoundException(uploadId); + } + + if ((int)response.StatusCode != 308) response.EnsureSuccessStatusCode(); + + long persisted = 0; + if ((int)response.StatusCode == 308 && response.Headers.TryGetValues("Range", out var values)) + { + var range = values.First(); + persisted = long.Parse(range.Substring(range.LastIndexOf('-') + 1), System.Globalization.CultureInfo.InvariantCulture) + 1; + + // Only whole chunks are ever sent before the final one (a multiple of 256 KiB), so one persisted byte cannot be real: + // an empty session is reported as "bytes=0-0" by some emulators, and as no Range header by the service. + if (persisted == 1) persisted = 0; + } + + var tail = Array.Empty(); + try + { + using var buffer = new MemoryStream(); + await storage.DownloadObjectAsync(_bucketName, TailName(id), buffer, cancellationToken: cancellationToken).ConfigureAwait(false); + tail = buffer.ToArray(); + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) + { + } + + return new UploadState(persisted, tail); + } + + private static async Task PutRangeAsync(StorageClient storage, Uri session, long start, ReadOnlyMemory bytes, long? total, CancellationToken cancellationToken) + { + var totalText = total?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "*"; + var range = bytes.Length == 0 ? "bytes */" + totalText : $"bytes {start}-{start + bytes.Length - 1}/{totalText}"; + + // The same range of the same session may be sent again: the session ignores bytes it already holds. + using var response = await SendIdempotentAsync( + storage, + () => + { + var request = new HttpRequestMessage(HttpMethod.Put, session) { Content = new ReadOnlyMemoryContent(bytes) }; + request.Content.Headers.TryAddWithoutValidation("Content-Range", range); + return request; + }, + cancellationToken).ConfigureAwait(false); + var status = (int)response.StatusCode; + if (status == 308 || response.IsSuccessStatusCode) return; + + throw new IOException($"The upload session answered {status}."); + } + + // The tail is at most one chunk: one simple upload (a single request) rather than the client library's resumable one (two or more). + private async Task PutTailAsync(StorageClient storage, string name, byte[] bytes, CancellationToken cancellationToken) + { + var url = UploadBase(storage) + "b/" + Uri.EscapeDataString(_bucketName!) + "/o?uploadType=media&name=" + Uri.EscapeDataString(name); + using var response = await SendIdempotentAsync( + storage, + () => + { + var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new ByteArrayContent(bytes) }; + request.Content.Headers.ContentType = new MediaTypeHeaderValue(GenericContentType); + return request; + }, + cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + } + + // Sends a request whose repetition is harmless (a session status query, the same range of a session, an overwrite of the tail), + // again when the connection fails before an answer arrives (a reused connection the service closed, a reset): up to 3 tries. + private static async Task SendIdempotentAsync(StorageClient storage, Func create, CancellationToken cancellationToken) + { + for (var attempt = 1; ; attempt++) + { + using var request = create(); + try + { + return await storage.Service.HttpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + } + catch (HttpRequestException) when (attempt < 3 && !cancellationToken.IsCancellationRequested) + { + } + } + } + + private static async Task CancelSessionAsync(StorageClient storage, Uri session) + { + try + { + using var request = new HttpRequestMessage(HttpMethod.Delete, session); + using var response = await storage.Service.HttpClient.SendAsync(request).ConfigureAwait(false); + } + catch (HttpRequestException) + { + } + } + + private async Task DeleteQuietlyAsync(StorageClient storage, string name, CancellationToken cancellationToken) + { + try + { + await storage.DeleteObjectAsync(_bucketName, name, cancellationToken: cancellationToken).ConfigureAwait(false); + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) + { + } + } +} diff --git a/src/BaGet.Gcp/GoogleCloudStorageService.cs b/src/BaGet.Gcp/GoogleCloudStorageService.cs index 6a01f4064..66a3c07a7 100644 --- a/src/BaGet.Gcp/GoogleCloudStorageService.cs +++ b/src/BaGet.Gcp/GoogleCloudStorageService.cs @@ -1,6 +1,6 @@ using System; +using System.Collections.Generic; using System.IO; -using System.Linq; using System.Net; using System.Security.Cryptography; using System.Threading; @@ -10,91 +10,144 @@ using Google.Cloud.Storage.V1; using Microsoft.Extensions.Options; -namespace BaGet.Gcp +namespace BaGet.Gcp; + +public partial class GoogleCloudStorageService : IStreamingStorageService, IListableStorageService { - public class GoogleCloudStorageService : IStorageService + private readonly string? _bucketName; + private readonly Func> _clientFactory; + + public GoogleCloudStorageService(IOptionsSnapshot options) + : this(options, () => StorageClient.CreateAsync()) { - private readonly string _bucketName; + } - public GoogleCloudStorageService(IOptionsSnapshot options) - { - if (options == null) - throw new ArgumentNullException(nameof(options)); + /// Builds the service over a client other than the default one (an emulator, in tests). + internal GoogleCloudStorageService(IOptionsSnapshot options, Func> clientFactory) + { + if (options == null) + throw new ArgumentNullException(nameof(options)); - _bucketName = options.Value.BucketName; - } + _bucketName = options.Value.BucketName; + _clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } + + private Task CreateClientAsync() => _clientFactory(); - public async Task GetAsync(string path, CancellationToken cancellationToken = default) + public async Task GetAsync(string path, CancellationToken cancellationToken = default) + { + // Spooled to a temporary file (deleted on dispose), not to a MemoryStream: the object is never held in managed memory. + using (var storage = await CreateClientAsync().ConfigureAwait(false)) { - using (var storage = await StorageClient.CreateAsync()) + var file = new FileStream( + Path.Combine(Path.GetTempPath(), "baget-gcs-" + Guid.NewGuid().ToString("N")), + FileMode.CreateNew, + FileAccess.ReadWrite, + FileShare.None, + 81920, + FileOptions.DeleteOnClose | FileOptions.Asynchronous); + try { - var stream = new MemoryStream(); - await storage.DownloadObjectAsync(_bucketName, CoercePath(path), stream, cancellationToken: cancellationToken); - stream.Position = 0; - return stream; + await storage.DownloadObjectAsync(_bucketName, CoercePath(path), file, cancellationToken: cancellationToken).ConfigureAwait(false); + file.Position = 0; + return file; } - } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) + { + await file.DisposeAsync().ConfigureAwait(false); - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) - { - // returns an Authenticated Browser Download URL: https://cloud.google.com/storage/docs/request-endpoints#cookieauth - return Task.FromResult(new Uri($"https://storage.googleapis.com/{_bucketName}/{CoercePath(path).TrimStart('/')}")); + // The one "missing content" exception of IStorageService.GetAsync, as FileStorageService throws. + throw new FileNotFoundException("The object '" + path + "' does not exist.", path, e); + } + catch + { + await file.DisposeAsync().ConfigureAwait(false); + throw; + } } + } + + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + // returns an Authenticated Browser Download URL: https://cloud.google.com/storage/docs/request-endpoints#cookieauth + return Task.FromResult(new Uri($"https://storage.googleapis.com/{_bucketName}/{CoercePath(path).TrimStart('/')}")); + } - public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + { + using (var storage = await CreateClientAsync().ConfigureAwait(false)) + // A temporary file, not a MemoryStream: a large package is never held in managed memory. + using (var seekableContent = await StreamingStreams.SpoolAsync(content, cancellationToken).ConfigureAwait(false)) { - using (var storage = await StorageClient.CreateAsync()) - using (var seekableContent = new MemoryStream()) + + var objectName = CoercePath(path); + + try + { + // attempt to upload, succeeding only if the object doesn't exist + await storage.UploadObjectAsync(_bucketName, objectName, contentType, seekableContent, new UploadObjectOptions { IfGenerationMatch = 0 }, cancellationToken); + return StoragePutResult.Success; + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.PreconditionFailed) { - await content.CopyToAsync(seekableContent, 65536, cancellationToken); + // the object already exists; get the hash of its content from its metadata + var existingObject = await storage.GetObjectAsync(_bucketName, objectName, cancellationToken: cancellationToken); + var existingHash = Convert.FromBase64String(existingObject.Md5Hash); + + // hash the content that was uploaded seekableContent.Position = 0; + byte[] contentHash; + using (var md5 = MD5.Create()) + contentHash = md5.ComputeHash(seekableContent); - var objectName = CoercePath(path); - - try - { - // attempt to upload, succeeding only if the object doesn't exist - await storage.UploadObjectAsync(_bucketName, objectName, contentType, seekableContent, new UploadObjectOptions { IfGenerationMatch = 0 }, cancellationToken); - return StoragePutResult.Success; - } - catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.PreconditionFailed) - { - // the object already exists; get the hash of its content from its metadata - var existingObject = await storage.GetObjectAsync(_bucketName, objectName, cancellationToken: cancellationToken); - var existingHash = Convert.FromBase64String(existingObject.Md5Hash); - - // hash the content that was uploaded - seekableContent.Position = 0; - byte[] contentHash; - using (var md5 = MD5.Create()) - contentHash = md5.ComputeHash(seekableContent); - - // conflict if the two hashes are different - return existingHash.SequenceEqual(contentHash) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict; - } + // conflict if the two hashes are different + return existingHash.SequenceEqual(contentHash) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict; } } + } - public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) + public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + using (var storage = await CreateClientAsync()) { - using (var storage = await StorageClient.CreateAsync()) + try + { + var obj = await storage.GetObjectAsync(_bucketName, CoercePath(path), cancellationToken: cancellationToken); + await storage.DeleteObjectAsync(obj, cancellationToken: cancellationToken); + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) { - try - { - var obj = await storage.GetObjectAsync(_bucketName, CoercePath(path), cancellationToken: cancellationToken); - await storage.DeleteObjectAsync(obj, cancellationToken: cancellationToken); - } - catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) - { - } } } + } + + /// + /// Every object under a prefix. The sweep of abandoned staged uploads is the only + /// caller, and without this a bucket would keep them forever. + /// + public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // "staging-archive/...". + var prefix = CoercePath(pathPrefix).TrimEnd('/') + "/"; + var paths = new List(); - private static string CoercePath(string path) + using (var storage = await CreateClientAsync()) { - // although Google Cloud Storage objects exist in a flat namespace, using forward slashes allows the objects to - // be exposed as nested subdirectories, e.g., when browsing via Google Cloud Console - return path.Replace('\\', '/'); + // The object's name is already the path IStorageService takes. + await foreach (var item in storage.ListObjectsAsync(_bucketName, prefix).WithCancellation(cancellationToken)) + { + paths.Add(item.Name); + } } + + return paths; + } + + private static string CoercePath(string path) + { + // although Google Cloud Storage objects exist in a flat namespace, using forward slashes allows the objects to + // be exposed as nested subdirectories, e.g., when browsing via Google Cloud Console + return path.Replace('\\', '/'); } -} +} \ No newline at end of file diff --git a/src/BaGet.Gcp/README.md b/src/BaGet.Gcp/README.md new file mode 100644 index 000000000..2652f00c7 --- /dev/null +++ b/src/BaGet.Gcp/README.md @@ -0,0 +1,26 @@ +# Extension.BaGet.Gcp + +Google Cloud Storage package storage for [BaGet Extension](https://pieroviano.github.io/BaGet/). + +```powershell +dotnet add package Extension.BaGet.Gcp +``` + +## Usage + +```csharp +services.AddBaGetWebApplication(app => app.AddGoogleCloudStorage()); +``` + +Active when `Storage:Type` is `GoogleCloud`. + +| Setting | Value | +|---|---| +| `Storage:BucketName` | Bucket name | + +Credentials come from [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials) +(e.g. `GOOGLE_APPLICATION_CREDENTIALS`). + +## Links + +[Hosting on Google Cloud](https://pieroviano.github.io/BaGet/installation/gcp/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Identity.Api/BaGet.Identity.Api.csproj b/src/BaGet.Identity.Api/BaGet.Identity.Api.csproj new file mode 100644 index 000000000..332cedc93 --- /dev/null +++ b/src/BaGet.Identity.Api/BaGet.Identity.Api.csproj @@ -0,0 +1,36 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's user accounts, package owners and per-user API keys. + BaGet.Identity + enable + Extension.$(MSBuildProjectName) + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Identity.Api/Controllers/UI/AccountApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AccountApiController.cs new file mode 100644 index 000000000..7380ad3a2 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AccountApiController.cs @@ -0,0 +1,120 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the sign-in side of the account screens (/api/ui/account/...): sign in, the two second-factor steps, sign out, +/// registration, email confirmation, the password reset pair and the re-authentication screen. AccountController calls it in process +/// and renders the views. Registration, the confirmation link, forgot and reset password are s: open to an anonymous HTTP caller from this server's origin (or a listed one), who gets no cookie (registration answers the new account's tokens, or nothing). Interactive session only for the rest: signing in sets the same session cookie as the page (same lockout, approval, two-factor and +/// return-URL rules), so over HTTP an API key and an anonymous caller get 403 "use the web screen" (a client without a cookie signs in at POST /api/ui/session); the view controller calls the twin in process. +/// The external provider's challenge and callback are browser-only and have no twin. +/// +[Route("api/ui/account")] +public sealed class AccountApiController : AccountApiControllerBase +{ + // ----- login + + /// The sign-in form. + [HttpGet("login"), UiApi("Account", "Login")] + public ActionResult> Login(string? returnUrl) + => Respond(UseCase().ShowLogin(returnUrl)); + + /// Signs in. Success sets the session cookie and continues at next.localUrl (the local return URL, else the site root), or at the second-factor screen. + [HttpPost("login"), UiApi("Account", "Login")] + public async Task>> LoginPost([FromBody] LoginForm? form) + => Respond(await UseCase().LoginAsync(form)); + + // ----- loginwith2fa + + /// The authenticator code form (back to sign-in without the half-signed-in cookie). + [HttpGet("loginwith2fa"), UiApi("Account", "LoginWith2fa")] + public async Task>> LoginWith2fa(bool rememberMe, string? returnUrl) + => Respond(await UseCase().ShowTwoFactorAsync(rememberMe, returnUrl)); + + /// Completes the sign-in with an authenticator code. + [HttpPost("loginwith2fa"), UiApi("Account", "LoginWith2fa")] + public async Task>> LoginWith2faPost([FromBody] TwoFactorLoginForm? form) + => Respond(await UseCase().TwoFactorAsync(form)); + + // ----- loginwithrecoverycode + + /// The recovery code form. + [HttpGet("loginwithrecoverycode"), UiApi("Account", "LoginWithRecoveryCode")] + public async Task>> LoginWithRecoveryCode(string? returnUrl) + => Respond(await UseCase().ShowRecoveryCodeAsync(returnUrl)); + + /// Completes the sign-in with a recovery code (each works once). + [HttpPost("loginwithrecoverycode"), UiApi("Account", "LoginWithRecoveryCode")] + public async Task>> LoginWithRecoveryCodePost([FromBody] RecoveryCodeLoginForm? form) + => Respond(await UseCase().RecoveryCodeAsync(form)); + + // ----- logout + + /// The sign-out screen. + [HttpGet("logout"), UiApi("Account", "Logout")] + public ActionResult> Logout() + => Respond(UseCase().ShowLogout()); + + /// Signs the user out. + [HttpPost("logout"), UiApi("Account", "Logout")] + public async Task>> LogoutPost() + => Respond(await UseCase().LogoutAsync()); + + // ----- register + + /// The registration form (404 while Accounts:AllowRegistration is off). + [HttpGet("register"), UiApi("Account", "Register"), AnonymousSessionEndpoint] + public ActionResult> Register(string? returnUrl) + => Respond(UseCase().ShowRegister(returnUrl)); + + /// Creates an account (and signs it in when no confirmation or approval is pending). + [HttpPost("register"), UiApi("Account", "Register"), AnonymousSessionEndpoint] + public async Task>> RegisterPost([FromBody] RegisterForm? form, CancellationToken cancellationToken) + => Respond(await UseCase().RegisterAsync(form, cancellationToken)); + + // ----- confirmemail + + /// The target of the links in confirmation emails (a GET that confirms the address, like the page). + [HttpGet("confirmemail"), UiApi("Account", "ConfirmEmail"), RequiresEmail, AnonymousSessionEndpoint] + public async Task>> ConfirmEmail(string? userId, string? code, string? email) + => Respond(await UseCase().ConfirmEmailAsync(User, userId, code, email)); + + // ----- forgotpassword + + /// The "forgot password" form. + [HttpGet("forgotpassword"), UiApi("Account", "ForgotPassword"), RequiresEmail, AnonymousSessionEndpoint] + public ActionResult> ForgotPassword() + => Respond(UseCase().ShowForgotPassword()); + + /// Asks for a reset link. The answer is the same whether or not an account matches. + [HttpPost("forgotpassword"), UiApi("Account", "ForgotPassword"), RequiresEmail, AnonymousSessionEndpoint] + public async Task>> ForgotPasswordPost([FromBody] ForgotPasswordForm? form) + => Respond(await UseCase().ForgotPasswordAsync(form, HttpContext.Connection.RemoteIpAddress?.ToString())); + + // ----- resetpassword + + /// The new-password form behind the link of a reset email. + [HttpGet("resetpassword"), UiApi("Account", "ResetPassword"), RequiresEmail, AnonymousSessionEndpoint] + public ActionResult> ResetPassword(string? userId, string? code) + => Respond(UseCase().ShowResetPassword(userId, code)); + + /// Sets the new password from the link; success continues at the sign-in screen. + [HttpPost("resetpassword"), UiApi("Account", "ResetPassword"), RequiresEmail, AnonymousSessionEndpoint] + public async Task>> ResetPasswordPost([FromBody] ResetPasswordForm? form) + => Respond(await UseCase().ResetPasswordAsync(form)); + + // ----- reauthenticate + + /// The "confirm it is you" screen (the button that starts the provider's sign-in is browser-only). + [HttpGet("reauthenticate"), UiApi("Account", "Reauthenticate"), RequiresSignIn] + public ActionResult> Reauthenticate(string? returnUrl) + => Respond(ExternalSignInUseCase.ShowReauthenticate(returnUrl)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AccountOrganizationsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AccountOrganizationsApiController.cs new file mode 100644 index 000000000..57abe14df --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AccountOrganizationsApiController.cs @@ -0,0 +1,42 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Organizations; +using BaGet.Identity.Application.UseCases.Account; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the signed-in user's organizations (/api/ui/account/organizations): AccountOrganizationsController calls it +/// in process. Interactive session only: over HTTP it answers 403 to an API key and to an anonymous caller. +/// +[Route("api/ui/account/organizations")] +public sealed class AccountOrganizationsApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + /// The organizations of the user. + [HttpGet, UiApi("AccountOrganizations", "Organizations")] + public async Task>> Organizations(CancellationToken cancellationToken) + => Respond(await UseCase().ShowOrganizationsAsync(User, cancellationToken)); + + /// Create an organization. + [HttpPost("create"), UiApi("AccountOrganizations", "Organizations", Handler = "Create")] + public async Task>> OrganizationsCreate([FromBody] CreateOrganizationForm? form, CancellationToken cancellationToken) + => Respond(await UseCase().CreateOrganizationAsync(User, form, cancellationToken)); + + /// Add a member (organization administrators only; 403 otherwise). + [HttpPost("add-member"), UiApi("AccountOrganizations", "Organizations", Handler = "AddMember")] + public async Task>> OrganizationsAddMember([FromBody] AddOrganizationMemberForm? form, CancellationToken cancellationToken) + => Respond(await UseCase().AddMemberAsync(User, form, cancellationToken)); + + /// Remove a member (an administrator removes anyone; any member may leave; 403 otherwise). + [HttpPost("remove-member"), UiApi("AccountOrganizations", "Organizations", Handler = "RemoveMember")] + public async Task>> OrganizationsRemoveMember([FromBody] RemoveOrganizationMemberForm? form, CancellationToken cancellationToken) + => Respond(await UseCase().RemoveMemberAsync(User, form, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AccountPackagesApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AccountPackagesApiController.cs new file mode 100644 index 000000000..6846e4160 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AccountPackagesApiController.cs @@ -0,0 +1,37 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of "My packages", "My access" and the "my profile" redirect (/api/ui/account/packages, access, profile): +/// AccountPackagesController calls it in process. Interactive session only: over HTTP it answers 403 to an API key and to an anonymous caller. +/// +[Route("api/ui/account")] +public sealed class AccountPackagesApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + /// The package IDs the user owns, per repository. + [HttpGet("packages"), UiApi("AccountPackages", "Packages")] + public async Task>> Packages(CancellationToken cancellationToken) + => Respond(await UseCase().ShowPackagesAsync(User, cancellationToken)); + + /// What the user may do in each repository (optionally for one package ID). + [HttpGet("access"), UiApi("AccountPackages", "Access")] + public async Task>> Access(string? package, CancellationToken cancellationToken) + => Respond(await UseCase().ShowAccessAsync(User, package, cancellationToken)); + + /// The user's own profile: continues at next.localUrl (~/profiles/{name}). + [HttpGet("profile"), UiApi("AccountPackages", "MyProfile")] + public ActionResult> MyProfile() + => Respond(UseCase().ShowMyProfile(User)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AccountSettingsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AccountSettingsApiController.cs new file mode 100644 index 000000000..8ae1add73 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AccountSettingsApiController.cs @@ -0,0 +1,90 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the signed-in user's own settings (/api/ui/account/settings, twofactor, apikeys): +/// AccountSettingsController calls it in process. Interactive session only (a session token, or the cookie with an antiforgery header): over HTTP an API key and an anonymous caller get 403 +/// "use the web screen"; an API key never changes credentials, reads the authenticator key or mints another key. A refused action answers +/// 400 with the screen's model (error says why); the password-confirmed actions re-ask the password like the page. +/// +[Route("api/ui/account")] +public sealed class AccountSettingsApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + // ----- settings + + /// Account settings. + [HttpGet("settings"), UiApi("AccountSettings", "Settings")] + public async Task>> Settings() + => Respond(await UseCase().ShowAsync(User)); + + /// Change the password. + [HttpPost("settings/change-password"), UiApi("AccountSettings", "Settings", Handler = "ChangePassword")] + public async Task>> SettingsChangePassword([FromBody] ChangePasswordForm? form) + => Respond(await UseCase().ChangePasswordAsync(User, form)); + + /// Change the email address (asks the password again). + [HttpPost("settings/change-email"), UiApi("AccountSettings", "Settings", Handler = "ChangeEmail")] + public async Task>> SettingsChangeEmail([FromBody] ChangeEmailForm? form) + => Respond(await UseCase().ChangeEmailAsync(User, form)); + + /// Unlinks the account's login at an external provider (asks the password again; refused when it is the only way to sign in). Linking is browser-only: it redirects to the provider. + [HttpPost("settings/unlink-external"), UiApi("AccountSettings", "Settings", Handler = "UnlinkExternal")] + public async Task>> SettingsUnlinkExternal([FromBody] UnlinkExternalForm? form) + => Respond(await UseCase().UnlinkAsync(User, form)); + + /// Delete the account (asks the password again). Success signs the user out. + [HttpPost("settings/delete"), UiApi("AccountSettings", "Settings", Handler = "Delete")] + public async Task>> SettingsDelete([FromBody] PasswordConfirmationForm? form, CancellationToken cancellationToken) + => Respond(await UseCase().DeleteAsync(User, form, cancellationToken)); + + // ----- two-factor authentication + + /// Two-factor authentication (the setup key and QR code while it is off). + [HttpGet("twofactor"), UiApi("AccountSettings", "TwoFactor")] + public async Task>> TwoFactor() + => Respond(await UseCase().ShowAsync(User)); + + /// Turn two-factor authentication on with a code from the authenticator; the answer carries the recovery codes, once. + [HttpPost("twofactor/enable"), UiApi("AccountSettings", "TwoFactor", Handler = "Enable")] + public async Task>> TwoFactorEnable([FromBody] TwoFactorCodeForm? form) + => Respond(await UseCase().EnableAsync(User, form)); + + /// Turn two-factor authentication off (asks the password again). + [HttpPost("twofactor/disable"), UiApi("AccountSettings", "TwoFactor", Handler = "Disable")] + public async Task>> TwoFactorDisable([FromBody] PasswordConfirmationForm? form) + => Respond(await UseCase().DisableAsync(User, form)); + + /// Reset the authenticator (asks the password again). + [HttpPost("twofactor/reset"), UiApi("AccountSettings", "TwoFactor", Handler = "Reset")] + public async Task>> TwoFactorReset([FromBody] PasswordConfirmationForm? form) + => Respond(await UseCase().ResetAsync(User, form)); + + // ----- API keys + + /// The user's API keys (never their values) and the new-key form. + [HttpGet("apikeys"), UiApi("AccountSettings", "ApiKeysIndex")] + public async Task>> ApiKeysIndex(CancellationToken cancellationToken) + => Respond(await UseCase().ShowAsync(User, cancellationToken)); + + /// Creates a key. The answer carries its value (createdKey) once. + [HttpPost("apikeys/create"), UiApi("AccountSettings", "ApiKeysIndex", Handler = "Create")] + public async Task>> ApiKeysCreate([FromBody] ApiKeyForm? form, CancellationToken cancellationToken) + => Respond(await UseCase().CreateAsync(User, form, BindingErrors(), cancellationToken)); + + /// Revokes a key. + [HttpPost("apikeys/revoke/{key:int}"), UiApi("AccountSettings", "ApiKeysIndex", Handler = "Revoke")] + public async Task>> ApiKeysRevoke(int key, CancellationToken cancellationToken) + => Respond(await UseCase().RevokeAsync(User, key, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminAuditApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminAuditApiController.cs new file mode 100644 index 000000000..238b6d6db --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminAuditApiController.cs @@ -0,0 +1,24 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.UseCases.Access; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the access audit log (/api/ui/admin/audit): one entry per change to groups, memberships, permission targets, grants, +/// projects, the repositories' project and anonymous-read switch, newest first, filtered by actor, subject, from and to. +/// Read only; server administrators only. AdminAuditController calls it in process. +/// +[Route("api/ui/admin/audit")] +public sealed class AdminAuditApiController : AccessApiControllerBase +{ + /// Lists the entries that match the filter. + [HttpGet(""), UiApi("AdminAudit", "Index")] + public async Task>> Get(string? actor, string? subject, string? from, string? to, CancellationToken cancellationToken = default) + => Respond(await UseCase().GetAsync(new AuditQuery(actor, subject, from, to), cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminGroupsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminGroupsApiController.cs new file mode 100644 index 000000000..bc856aa9b --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminGroupsApiController.cs @@ -0,0 +1,57 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Access; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the groups screens (/api/ui/admin/groups): the list with the new-group form and one group (rename, members, delete). +/// AdminGroupsController calls it in process. Server administrators only (a session, or an admin:api key); every change that +/// touches membership or deletes asks the administrator's password in the body, and every write is refused with 503 while the server is read-only. +/// +[Route("api/ui/admin/groups")] +public sealed class AdminGroupsApiController : AccessApiControllerBase +{ + private AdminGroupsUseCase Groups => UseCase(); + + /// Lists the groups. + [HttpGet(""), UiApi("AdminGroups", "Index")] + public async Task>> List(CancellationToken cancellationToken = default) + => Respond(await Groups.ListAsync(await CallerAsync(cancellationToken), cancellationToken)); + + /// Creates a group and points at it. + [HttpPost(""), UiApi("AdminGroups", "Index")] + public async Task>> Create([FromBody] GroupCreation? form, CancellationToken cancellationToken = default) + => Respond(await Groups.CreateAsync(await CallerAsync(cancellationToken), form ?? new GroupCreation(null, null), cancellationToken)); + + /// Shows one group, with the member search for . + [HttpGet("{name}"), UiApi("AdminGroups", "Detail")] + public async Task>> Get(string name, string? q, CancellationToken cancellationToken = default) + => Respond(await Groups.GetAsync(await CallerAsync(cancellationToken), name, q, cancellationToken)); + + /// Renames the group. + [HttpPost("{name}/rename"), UiApi("AdminGroups", "Detail", Handler = "Rename")] + public async Task>> Rename(string name, [FromBody] GroupRename? form, CancellationToken cancellationToken = default) + => Respond(await Groups.RenameAsync(await CallerAsync(cancellationToken), name, form ?? new GroupRename(null), cancellationToken)); + + /// Adds a user to the group. + [HttpPost("{name}/add-member"), UiApi("AdminGroups", "Detail", Handler = "AddMember")] + public async Task>> AddMember(string name, [FromBody] GroupMemberChange? form, CancellationToken cancellationToken = default) + => Respond(await Groups.AddMemberAsync(await CallerAsync(cancellationToken), name, form ?? new GroupMemberChange(null, null), cancellationToken)); + + /// Removes a user from the group. + [HttpPost("{name}/remove-member"), UiApi("AdminGroups", "Detail", Handler = "RemoveMember")] + public async Task>> RemoveMember(string name, [FromBody] GroupMemberChange? form, CancellationToken cancellationToken = default) + => Respond(await Groups.RemoveMemberAsync(await CallerAsync(cancellationToken), name, form ?? new GroupMemberChange(null, null), cancellationToken)); + + /// Deletes the group with the grants and project roles that name it. + [HttpPost("{name}/delete"), UiApi("AdminGroups", "Detail", Handler = "Delete")] + public async Task>> Delete(string name, [FromBody] PasswordForm? form, CancellationToken cancellationToken = default) + => Respond(await Groups.DeleteAsync(await CallerAsync(cancellationToken), name, form ?? new PasswordForm(null), cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminOperationsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminOperationsApiController.cs new file mode 100644 index 000000000..456d2f90a --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminOperationsApiController.cs @@ -0,0 +1,93 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Operations; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the administrator's operational screens (/api/ui/admin/...): maintenance operations, the validation queue, abuse reports, the +/// package formats, the cluster status and the "access control unavailable" notice. AdminOperationsController calls it in process. Every write is +/// refused with 503 while the server is read-only; releasing or rejecting a submission and starting an operation that deletes data ask the administrator's +/// password in the body. +/// +[Route("api/ui/admin")] +public sealed class AdminOperationsApiController : AdminApiControllerBase +{ + private AdminOperationsUseCase Operations => UseCase(); + + // ---------------------------------------------------------------- Operations + + /// Lists the operations and their status. + [HttpGet("operations"), UiApi("AdminOperations", "Index")] + public async Task>> GetOperations(CancellationToken cancellationToken = default) + => Respond(await Operations.GetOperationsAsync(User, "~" + Request.Path + Request.QueryString, cancellationToken)); + + /// Starts an operation on a repository. + [HttpPost("operations"), UiApi("AdminOperations", "Index")] + public async Task>> Start([FromBody] OperationForm? form, CancellationToken cancellationToken = default) + => Respond(await Operations.StartAsync(User, form?.Operation, form?.Repository, form?.Password, cancellationToken)); + + // ---------------------------------------------------------------- Validation + + /// Lists the pending and quarantined submissions. + [HttpGet("validation"), UiApi("AdminOperations", "Validation")] + public async Task>> GetValidation(CancellationToken cancellationToken = default) + => Respond(await Operations.GetValidationAsync(User, cancellationToken)); + + /// Validates the submission again. + [HttpPost("validation/retry"), UiApi("AdminOperations", "Validation", Handler = "Retry")] + public async Task>> Retry([FromBody] SubmissionForm? form, CancellationToken cancellationToken = default) + => Respond(await Operations.RetryAsync(User, form?.SubmissionId, cancellationToken)); + + /// Indexes the quarantined package although validation failed. + [HttpPost("validation/release"), UiApi("AdminOperations", "Validation", Handler = "Release")] + public async Task>> Release([FromBody] SubmissionForm? form, CancellationToken cancellationToken = default) + => Respond(await Operations.ReleaseAsync(User, form?.SubmissionId, form?.Password, cancellationToken)); + + /// Deletes the quarantined package. + [HttpPost("validation/reject"), UiApi("AdminOperations", "Validation", Handler = "Reject")] + public async Task>> Reject([FromBody] SubmissionForm? form, CancellationToken cancellationToken = default) + => Respond(await Operations.RejectAsync(User, form?.SubmissionId, form?.Password, cancellationToken)); + + // ---------------------------------------------------------------- Abuse + + /// Lists the abuse reports (the unresolved ones unless ). + [HttpGet("abuse"), UiApi("AdminOperations", "Abuse")] + public async Task>> GetAbuse(bool all, CancellationToken cancellationToken = default) + => Respond(await Operations.GetAbuseAsync(all, cancellationToken)); + + /// Marks a report resolved. + [HttpPost("abuse/resolve"), UiApi("AdminOperations", "Abuse", Handler = "Resolve")] + public async Task>> Resolve([FromBody] AbuseForm? form, CancellationToken cancellationToken = default) + => Respond(await Operations.ResolveAsync(User, form?.Key ?? 0, form?.All ?? false, cancellationToken)); + + /// Reopens a resolved report. + [HttpPost("abuse/reopen"), UiApi("AdminOperations", "Abuse", Handler = "Reopen")] + public async Task>> Reopen([FromBody] AbuseForm? form, CancellationToken cancellationToken = default) + => Respond(await Operations.ReopenAsync(User, form?.Key ?? 0, form?.All ?? false, cancellationToken)); + + // ---------------------------------------------------------------- Cluster, Formats, AccessUnavailable + + /// The cluster status; ?refresh=true runs the health checks again. + [HttpGet("cluster"), UiApi("AdminOperations", "Cluster")] + public async Task>> GetCluster(bool refresh, CancellationToken cancellationToken = default) + => Respond(await Operations.GetClusterAsync(refresh, cancellationToken)); + + /// The package formats this server can host. + [HttpGet("formats"), UiApi("AdminOperations", "Formats")] + public async Task>> GetFormats(CancellationToken cancellationToken = default) + => Respond(await Operations.GetFormatsAsync(cancellationToken)); + + /// Why the access screens are not available: the configured database has no access model. + [HttpGet("access-unavailable"), UiApi("AdminOperations", "AccessUnavailable")] + public ActionResult> GetAccessUnavailable() + => Respond(Operations.GetAccessUnavailable()); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminOrganizationsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminOrganizationsApiController.cs new file mode 100644 index 000000000..111425564 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminOrganizationsApiController.cs @@ -0,0 +1,57 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Organizations; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the administrator's organization screens (/api/ui/admin/organizations): the list, and one organization with its rename, member +/// and delete actions. AdminOrganizationsController calls it in process. Every change asks the administrator's password in the body and is +/// refused with 503 while the server is read-only. +/// +[Route("api/ui/admin/organizations")] +public sealed class AdminOrganizationsApiController : AdminApiControllerBase +{ + private AdminOrganizationsUseCase Organizations => UseCase(); + + /// Lists the organizations. + [HttpGet(""), UiApi("AdminOrganizations", "Index")] + public async Task>> List(CancellationToken cancellationToken = default) + => Respond(await Organizations.ListAsync(cancellationToken)); + + /// Shows one organization. + [HttpGet("{name}"), UiApi("AdminOrganizations", "Detail")] + public async Task>> Get(string name, CancellationToken cancellationToken = default) + => Respond(await Organizations.GetAsync(User, name, cancellationToken)); + + /// Renames the organization. + [HttpPost("{name}/rename"), UiApi("AdminOrganizations", "Detail", Handler = "Rename")] + public async Task>> Rename(string name, [FromBody] OrganizationRenameForm? form, CancellationToken cancellationToken = default) + => Respond(await Organizations.RenameAsync(User, name, form?.NewName, form?.Password, cancellationToken)); + + /// Deletes the organization (refused while it owns packages). + [HttpPost("{name}/delete"), UiApi("AdminOrganizations", "Detail", Handler = "Delete")] + public async Task>> Delete(string name, [FromBody] PasswordForm? form, CancellationToken cancellationToken = default) + => Respond(await Organizations.DeleteAsync(User, name, form?.Password, cancellationToken)); + + /// Adds a user to the organization. + [HttpPost("{name}/add-member"), UiApi("AdminOrganizations", "Detail", Handler = "AddMember")] + public async Task>> AddMember(string name, [FromBody] OrganizationMemberForm? form, CancellationToken cancellationToken = default) + => Respond(await Organizations.AddMemberAsync(User, name, form?.UserName, form?.IsAdmin ?? false, form?.Password, cancellationToken)); + + /// Makes a member an administrator of the organization, or not. + [HttpPost("{name}/set-admin"), UiApi("AdminOrganizations", "Detail", Handler = "SetAdmin")] + public async Task>> SetAdmin(string name, [FromBody] OrganizationMemberForm? form, CancellationToken cancellationToken = default) + => Respond(await Organizations.SetAdminAsync(User, name, form?.UserName, form?.IsAdmin ?? false, form?.Password, cancellationToken)); + + /// Removes a member from the organization. + [HttpPost("{name}/remove-member"), UiApi("AdminOrganizations", "Detail", Handler = "RemoveMember")] + public async Task>> RemoveMember(string name, [FromBody] OrganizationMemberForm? form, CancellationToken cancellationToken = default) + => Respond(await Organizations.RemoveMemberAsync(User, name, form?.UserName, form?.Password, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminPackagesApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminPackagesApiController.cs new file mode 100644 index 000000000..15ef85afd --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminPackagesApiController.cs @@ -0,0 +1,25 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the ownerless packages screen (GET /api/ui/admin/packages, and /api/ui/r/{repo}/admin/packages like the page): the package +/// IDs that have no owner, in every repository. AdminPackagesController calls it in process. (The packages of one user are +/// .) +/// +[Route("api/ui/admin/packages")] +public sealed class AdminPackagesApiController : AdminApiControllerBase +{ + /// Lists the ownerless IDs of every repository, being one-based. + [HttpGet(""), UiApi("AdminPackages", "Index"), RepositoryPage] + public async Task>> List([FromQuery(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => Respond(await UseCase().GetOwnerlessAsync(pageNumber, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminPermissionsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminPermissionsApiController.cs new file mode 100644 index 000000000..db8f3499f --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminPermissionsApiController.cs @@ -0,0 +1,94 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Access; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the permission target screens (/api/ui/admin/permissions): the list with the new-target form (server administrators only) +/// and one target (patterns, preview, grants, delete), which also admits the administrators of the target's project for a project target (the target +/// is the name route value). AdminPermissionsController calls it in process. Saving patterns, changing grants and deleting ask for +/// the password in the body; every write is refused with 503 while the server is read-only. +/// +[Route("api/ui/admin/permissions")] +public sealed class AdminPermissionsApiController : AccessApiControllerBase +{ + private static readonly ScreenRef DetailScreen = ScreenCatalog.AdminPermissionDetail; + + private AdminPermissionsUseCase Permissions => UseCase(); + + /// + protected override async Task AuthorizeAsync(CancellationToken cancellationToken) + { + // Only the detail screen is widened to a project's administrators (the target is the name route value). + if (CurrentScreen() != DetailScreen) return false; + + var services = HttpContext.RequestServices; + + return await AccessAuthorization.TargetAsync( + services.GetRequiredService(), + false, + services.GetRequiredService>().GetUserId(User), + RouteData.Values["name"]?.ToString(), + cancellationToken); + } + + /// Lists the permission targets. + [HttpGet(""), UiApi("AdminPermissions", "Index")] + public async Task>> List(CancellationToken cancellationToken = default) + => Respond(await Permissions.ListAsync(await CallerAsync(cancellationToken), cancellationToken)); + + /// Creates a target and points at it. + [HttpPost(""), UiApi("AdminPermissions", "Index")] + public async Task>> Create([FromBody] PermissionTargetForm? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.CreateAsync(await CallerAsync(cancellationToken), form ?? new PermissionTargetForm(), cancellationToken)); + + /// Previews the form patterns without saving anything. + [HttpPost("preview"), UiApi("AdminPermissions", "Index", Handler = "Preview")] + public async Task>> Preview([FromBody] PermissionTargetForm? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.PreviewAsync(await CallerAsync(cancellationToken), form ?? new PermissionTargetForm(), cancellationToken)); + + /// Re-creates the built-in groups and targets that are missing (the upgrade defaults). + [HttpPost("restore-built-ins"), UiApi("AdminPermissions", "Index", Handler = "RestoreBuiltIns")] + public async Task>> RestoreBuiltIns([FromBody] PasswordForm? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.RestoreBuiltInsAsync(await CallerAsync(cancellationToken), form ?? new PasswordForm(null), cancellationToken)); + + /// Shows one target. and pre-fill the grant form. + [HttpGet("{name}"), UiApi("AdminPermissions", "Detail")] + public async Task>> Get(string name, string? testPackage, PrincipalType? principalType, string? principalName, CancellationToken cancellationToken = default) + => Respond(await Permissions.GetAsync(await CallerAsync(cancellationToken), name, testPackage, principalType, principalName, cancellationToken)); + + /// Previews the form patterns (and the test package) without saving anything. + [HttpPost("{name}/preview"), UiApi("AdminPermissions", "Detail", Handler = "Preview")] + public async Task>> PreviewDetail(string name, [FromBody] PermissionTargetForm? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.PreviewDetailAsync(await CallerAsync(cancellationToken), name, form ?? new PermissionTargetForm(), cancellationToken)); + + /// Replaces the target's patterns. + [HttpPost("{name}/save"), UiApi("AdminPermissions", "Detail", Handler = "Save")] + public async Task>> Save(string name, [FromBody] PermissionTargetForm? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.SaveAsync(await CallerAsync(cancellationToken), name, form ?? new PermissionTargetForm(), cancellationToken)); + + /// Gives a principal the ticked actions through the target, replacing an earlier grant to it. + [HttpPost("{name}/set-grant"), UiApi("AdminPermissions", "Detail", Handler = "SetGrant")] + public async Task>> SetGrant(string name, [FromBody] GrantForm? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.SetGrantAsync(await CallerAsync(cancellationToken), name, form ?? new GrantForm(null, null, null, null), cancellationToken)); + + /// Removes a principal's grant. + [HttpPost("{name}/remove-grant"), UiApi("AdminPermissions", "Detail", Handler = "RemoveGrant")] + public async Task>> RemoveGrant(string name, [FromBody] PrincipalRemoval? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.RemoveGrantAsync(await CallerAsync(cancellationToken), name, form ?? new PrincipalRemoval(PrincipalType.Group, null, null), cancellationToken)); + + /// Deletes the target and its grants. + [HttpPost("{name}/delete"), UiApi("AdminPermissions", "Detail", Handler = "Delete")] + public async Task>> Delete(string name, [FromBody] PasswordForm? form, CancellationToken cancellationToken = default) + => Respond(await Permissions.DeleteAsync(await CallerAsync(cancellationToken), name, form ?? new PasswordForm(null), cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminProjectsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminProjectsApiController.cs new file mode 100644 index 000000000..5e297b528 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminProjectsApiController.cs @@ -0,0 +1,90 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Access; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the project screens (/api/ui/admin/projects): the list with the new-project form and one project (repositories, members, +/// the project's permission targets, delete). Server administrators, and a project's administrators for the projects they administer (the project is the +/// name route value; only server administrators create and delete projects and assign repositories). AdminProjectsController calls +/// it in process. Member changes and deletions ask for the password in the body; every write is refused with 503 while the server is read-only. +/// +[Route("api/ui/admin/projects")] +public sealed class AdminProjectsApiController : AccessApiControllerBase +{ + private static readonly ScreenRef DetailScreen = ScreenCatalog.AdminProjectDetail; + + private AdminProjectsUseCase Projects => UseCase(); + + /// + protected override async Task AuthorizeAsync(CancellationToken cancellationToken) + { + var services = HttpContext.RequestServices; + var access = services.GetRequiredService(); + var userId = services.GetRequiredService>().GetUserId(User); + + return CurrentScreen() == DetailScreen + ? await AccessAuthorization.ProjectAsync(access, false, userId, RouteData.Values["name"]?.ToString(), cancellationToken) + : await AccessAuthorization.ProjectsAsync(access, false, userId, cancellationToken); + } + + /// Lists the projects the caller may open. + [HttpGet(""), UiApi("AdminProjects", "Index")] + public async Task>> List(CancellationToken cancellationToken = default) + => Respond(await Projects.ListAsync(await CallerAsync(cancellationToken), cancellationToken)); + + /// Creates a project (server administrators only) and points at it. + [HttpPost(""), UiApi("AdminProjects", "Index")] + public async Task>> Create([FromBody] ProjectCreation? form, CancellationToken cancellationToken = default) + => Respond(await Projects.CreateAsync(await CallerAsync(cancellationToken), form ?? new ProjectCreation(null, null), cancellationToken)); + + /// Shows one project. + [HttpGet("{name}"), UiApi("AdminProjects", "Detail")] + public async Task>> Get(string name, CancellationToken cancellationToken = default) + => Respond(await Projects.GetAsync(await CallerAsync(cancellationToken), name, cancellationToken)); + + /// Gives a user or group a role in the project, replacing an earlier one. + [HttpPost("{name}/set-member"), UiApi("AdminProjects", "Detail", Handler = "SetMember")] + public async Task>> SetMember(string name, [FromBody] ProjectMemberForm? form, CancellationToken cancellationToken = default) + => Respond(await Projects.SetMemberAsync(await CallerAsync(cancellationToken), name, form ?? new ProjectMemberForm(PrincipalType.User, null, ProjectRole.Viewer, null), cancellationToken)); + + /// Takes a user or group out of the project. + [HttpPost("{name}/remove-member"), UiApi("AdminProjects", "Detail", Handler = "RemoveMember")] + public async Task>> RemoveMember(string name, [FromBody] PrincipalRemoval? form, CancellationToken cancellationToken = default) + => Respond(await Projects.RemoveMemberAsync(await CallerAsync(cancellationToken), name, form ?? new PrincipalRemoval(PrincipalType.User, null, null), cancellationToken)); + + /// Puts a repository in the project (server administrators only); it leaves any project it was in. + [HttpPost("{name}/assign-repository"), UiApi("AdminProjects", "Detail", Handler = "AssignRepository")] + public async Task>> AssignRepository(string name, [FromBody] ProjectRepositoryForm? form, CancellationToken cancellationToken = default) + => Respond(await Projects.AssignRepositoryAsync(await CallerAsync(cancellationToken), name, form ?? new ProjectRepositoryForm(null, null), cancellationToken)); + + /// Takes a repository out of the project (server administrators only). + [HttpPost("{name}/unassign-repository"), UiApi("AdminProjects", "Detail", Handler = "UnassignRepository")] + public async Task>> UnassignRepository(string name, [FromBody] ProjectRepositoryForm? form, CancellationToken cancellationToken = default) + => Respond(await Projects.UnassignRepositoryAsync(await CallerAsync(cancellationToken), name, form ?? new ProjectRepositoryForm(null, null), cancellationToken)); + + /// Creates a permission target that applies only to the project's repositories. + [HttpPost("{name}/create-target"), UiApi("AdminProjects", "Detail", Handler = "CreateTarget")] + public async Task>> CreateTarget(string name, [FromBody] ProjectTargetForm? form, CancellationToken cancellationToken = default) + => Respond(await Projects.CreateTargetAsync(await CallerAsync(cancellationToken), name, form ?? new ProjectTargetForm(null, null, null, null, null), cancellationToken)); + + /// Previews the new target's patterns without saving anything. + [HttpPost("{name}/preview"), UiApi("AdminProjects", "Detail", Handler = "Preview")] + public async Task>> Preview(string name, [FromBody] ProjectTargetForm? form, CancellationToken cancellationToken = default) + => Respond(await Projects.PreviewAsync(await CallerAsync(cancellationToken), name, form ?? new ProjectTargetForm(null, null, null, null, null), cancellationToken)); + + /// Deletes the project (server administrators only) with its members and targets; the repositories stay. + [HttpPost("{name}/delete"), UiApi("AdminProjects", "Detail", Handler = "Delete")] + public async Task>> Delete(string name, [FromBody] PasswordForm? form, CancellationToken cancellationToken = default) + => Respond(await Projects.DeleteAsync(await CallerAsync(cancellationToken), name, form ?? new PasswordForm(null), cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminRepositoriesApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminRepositoriesApiController.cs new file mode 100644 index 000000000..44dbe3bee --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminRepositoriesApiController.cs @@ -0,0 +1,127 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the administrator's repository screens (/api/ui/admin/repositories): the list with the create forms, one repository +/// ({name}: anonymous read, upstream, cache, members, Maven policy) and its deletion ({name}/delete). AdminRepositoriesController calls +/// it in process. Every write is refused with 503 while the server is read-only; creating or changing a remote repository, purging its cache and testing its +/// connection ask the administrator's password in the body; a refused change answers 400 with the screen's model and the reason. No answer carries a password. +/// +/// The create handlers live under create/... so that no repository name (format, virtual...) can shadow them. +/// +/// +[Route("api/ui/admin/repositories")] +public sealed class AdminRepositoriesApiController : AdminApiControllerBase +{ + private AdminRepositoriesUseCase List => UseCase(); + + private AdminRepositoryEditUseCase Edit => UseCase(); + + private AdminRepositoryDeleteUseCase Delete => UseCase(); + + private string ReturnPage => "~" + Request.Path + Request.QueryString; + + // ---------------------------------------------------------------- Repositories + + /// Lists the repositories (narrowed by , , ) and describes the create forms. + [HttpGet(""), UiApi("AdminRepositories", "Index")] + public async Task>> GetRepositories(string? format = null, string? kind = null, string? q = null, CancellationToken cancellationToken = default) + => Respond(await List.GetAsync(User, format, kind, q, ReturnPage, cancellationToken)); + + /// Creates a local NuGet repository (name). + [HttpPost(""), UiApi("AdminRepositories", "Index")] + public async Task>> Create([FromBody] RepositoryCreateForm? form, CancellationToken cancellationToken = default) + => Respond(await List.CreateAsync(User, form, ReturnPage, cancellationToken)); + + /// Creates a local repository of a format other than NuGet (name, format, fields, anonymousRead). + [HttpPost("create/format"), UiApi("AdminRepositories", "Index", Handler = "Format")] + public async Task>> CreateFormat([FromBody] RepositoryCreateForm? form, CancellationToken cancellationToken = default) + => Respond(await List.CreateFormatAsync(User, form, ReturnPage, cancellationToken)); + + /// Creates a virtual repository with no members (name, format, anonymousRead). + [HttpPost("create/virtual"), UiApi("AdminRepositories", "Index", Handler = "Virtual")] + public async Task>> CreateVirtual([FromBody] RepositoryCreateForm? form, CancellationToken cancellationToken = default) + => Respond(await List.CreateVirtualAsync(User, form, ReturnPage, cancellationToken)); + + /// Creates a remote repository (name, format, remote, anonymousRead, password). + [HttpPost("create/remote"), UiApi("AdminRepositories", "Index", Handler = "Remote")] + public async Task>> CreateRemote([FromBody] RepositoryCreateForm? form, CancellationToken cancellationToken = default) + => Respond(await List.CreateRemoteAsync(User, form, ReturnPage, cancellationToken)); + + // ---------------------------------------------------------------- RepositoryEdit + + /// Shows one repository. + [HttpGet("{name}"), UiApi("AdminRepositories", "Edit")] + public async Task>> GetRepository(string name, CancellationToken cancellationToken = default) + => Respond(await Edit.GetAsync(User, name, ReturnPage, cancellationToken)); + + /// Saves the repository (anonymousRead; a remote one also remote and password). + [HttpPost("{name}"), UiApi("AdminRepositories", "Edit")] + public async Task>> Save(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.SaveAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Saves the policy of a local Maven repository (policy, redeploy, snapshotBuilds). + [HttpPost("{name}/maven-settings"), UiApi("AdminRepositories", "Edit", Handler = "MavenSettings")] + public async Task>> MavenSettings(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.SaveMavenSettingsAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Asks a remote repository's upstream with the unsaved remote values and saves nothing (password). + [HttpPost("{name}/test"), UiApi("AdminRepositories", "Edit", Handler = "Test")] + public async Task>> Test(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.TestAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Deletes everything a remote repository cached (password). + [HttpPost("{name}/purge"), UiApi("AdminRepositories", "Edit", Handler = "Purge")] + public async Task>> Purge(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.PurgeAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Deletes one cached package of a remote repository (packageId, packageVersion, password). + [HttpPost("{name}/purge-package"), UiApi("AdminRepositories", "Edit", Handler = "PurgePackage")] + public async Task>> PurgePackage(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.PurgePackageAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Adds a member at the end of a virtual repository (member). + [HttpPost("{name}/add-member"), UiApi("AdminRepositories", "Edit", Handler = "AddMember")] + public async Task>> AddMember(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.AddMemberAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Removes a member of a virtual repository (member). + [HttpPost("{name}/remove-member"), UiApi("AdminRepositories", "Edit", Handler = "RemoveMember")] + public async Task>> RemoveMember(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.RemoveMemberAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Moves a member of a virtual repository up or down (member, direction). + [HttpPost("{name}/move-member"), UiApi("AdminRepositories", "Edit", Handler = "MoveMember")] + public async Task>> MoveMember(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.MoveMemberAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Sets the member of a virtual repository that receives uploads (deploy). + [HttpPost("{name}/deploy"), UiApi("AdminRepositories", "Edit", Handler = "Deploy")] + public async Task>> Deploy(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.SetDeployAsync(User, name, request, ReturnPage, cancellationToken)); + + /// Shows where a package version would come from in a virtual repository (previewPackageId, previewVersion). + [HttpPost("{name}/preview"), UiApi("AdminRepositories", "Edit", Handler = "Preview")] + public async Task>> Preview(string name, [FromBody] RepositoryEditRequest? request, CancellationToken cancellationToken = default) + => Respond(await Edit.PreviewAsync(User, name, request, ReturnPage, cancellationToken)); + + // ---------------------------------------------------------------- RepositoryDelete + + /// Shows what deleting the repository does. + [HttpGet("{name}/delete"), UiApi("AdminRepositories", "DeleteRepository")] + public async Task>> GetDeletion(string name, CancellationToken cancellationToken = default) + => Respond(await Delete.GetAsync(name, cancellationToken)); + + /// Deletes the repository (refused while it holds packages or is a member of a virtual repository). + [HttpPost("{name}/delete"), UiApi("AdminRepositories", "DeleteRepository")] + public async Task>> DeleteRepository(string name, CancellationToken cancellationToken = default) + => Respond(await Delete.DeleteAsync(name, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminSettingsApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminSettingsApiController.cs new file mode 100644 index 000000000..390a9fd8d --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminSettingsApiController.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the server settings screen (/api/ui/admin/settings): every registered setting (a sensitive one never carries its value), a save per +/// section, the per-source log levels, the database copy progress and the telemetry connection test. AdminSettingsController calls it in process. +/// Every change asks the administrator's password in the body and is refused with 503 while the server is read-only (the connection test writes nothing, so it +/// is not). A save that is refused answers 400 with the screen's model and the reasons. +/// +[Route("api/ui/admin/settings")] +public sealed class AdminSettingsApiController : AdminApiControllerBase +{ + private AdminSettingsUseCase Settings => UseCase(); + + /// Shows the settings; is the id of the section to show. + [HttpGet(""), UiApi("AdminSettings", "Index")] + public async Task>> Get(string? section = null) + => Respond(await Settings.GetAsync(User, section)); + + /// The progress of the database copy. + [HttpGet("copy-status"), UiApi("AdminSettings", "Index", Handler = "CopyStatus")] + public ActionResult> GetCopyStatus() + => Respond(Settings.GetCopyStatus()); + + /// + /// Saves the settings of one section: the body names the section, the password and the fields (v:<key> values, reset:<key>, + /// clear:<key>, copyData), each an array of strings. + /// + [HttpPost(""), UiApi("AdminSettings", "Index")] + public async Task>> Save([FromBody] SettingsSubmission? submission, CancellationToken cancellationToken = default) + => Respond(await Settings.SaveAsync(User, Normalize(submission), cancellationToken)); + + /// Adds or changes a named OpenID Connect provider (password in the body; takes effect after a restart; a blank secret keeps the saved one). + [HttpPost("save-provider"), UiApi("AdminSettings", "Index", Handler = "SaveProvider")] + public async Task>> SaveProvider([FromBody] SignInProviderForm? form, CancellationToken cancellationToken = default) + => Respond(await Settings.SaveSignInProviderAsync(User, form, cancellationToken)); + + /// Removes a named OpenID Connect provider saved on this screen (takes effect after a restart). + [HttpPost("remove-provider"), UiApi("AdminSettings", "Index", Handler = "RemoveProvider")] + public async Task>> RemoveProvider([FromBody] RemoveSignInProviderForm? form, CancellationToken cancellationToken = default) + => Respond(await Settings.RemoveSignInProviderAsync(User, form, cancellationToken)); + + /// Sets the lowest level logged for one source. + [HttpPost("set-log-level"), UiApi("AdminSettings", "Index", Handler = "SetLogLevel")] + public async Task>> SetLogLevel([FromBody] LogLevelForm? form, CancellationToken cancellationToken = default) + => Respond(await Settings.SetLogLevelAsync(User, form?.Source, form?.Level, form?.Password, cancellationToken)); + + /// Removes a per-source level saved on this screen. + [HttpPost("remove-log-level"), UiApi("AdminSettings", "Index", Handler = "RemoveLogLevel")] + public async Task>> RemoveLogLevel([FromBody] LogLevelForm? form, CancellationToken cancellationToken = default) + => Respond(await Settings.RemoveLogLevelAsync(User, form?.Source, form?.Password, cancellationToken)); + + /// Sends one test span to the posted, unsaved telemetry endpoint (v:Telemetry:Otlp:* fields) and answers the outcome; nothing is saved. + [HttpPost("test-telemetry"), UiApi("AdminSettings", "Index", Handler = "TestTelemetry")] + public async Task>> TestTelemetry([FromBody] SettingsSubmission? submission, CancellationToken cancellationToken = default) + => Respond(await Settings.TestTelemetryAsync(User, Normalize(submission), cancellationToken)); + + private static SettingsSubmission Normalize(SettingsSubmission? submission) + => new(submission?.Section, submission?.Password, submission?.Fields ?? new Dictionary()); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/AdminUsersApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/AdminUsersApiController.cs new file mode 100644 index 000000000..82069ceca --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/AdminUsersApiController.cs @@ -0,0 +1,124 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.Models.Users; +using BaGet.Identity.Application.UseCases.Admin; +using BaGet.Identity.Application.UseCases.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the administrator's account screens (/api/ui/admin/users): the user list and its actions, one account +/// (/api/ui/admin/users/{name}), its deletion and the packages it owns. AdminUsersController calls it in process and renders the +/// views. Administrators only (a session, or an admin:api key); every write asks the administrator's password in the body and is refused with 503 +/// while the server is read-only. A password a write generates (reset, new account) is in the answer once, with Cache-Control: no-store. +/// +[Route("api/ui/admin/users")] +public sealed class AdminUsersApiController : AdminApiControllerBase +{ + // Resolved in the action, after the gate: the use cases exist only while accounts are enabled. + private AdminUsersUseCase Users => UseCase(); + + private AdminUserDetailUseCase Detail => UseCase(); + + private AdminUserDeletionUseCase Deletion => UseCase(); + + private AdminPackagesUseCase Packages => UseCase(); + + // ---------------------------------------------------------------- Users + + /// Lists the users, filtered by (user name contains), one page of them. + [HttpGet(""), UiApi("AdminUsers", "Index")] + public async Task>> List(string? q, [FromQuery(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => Respond(await Users.GetAsync(User, q, pageNumber, cancellationToken)); + + /// Enables a self-registered account that waits for approval. + [HttpPost("approve"), UiApi("AdminUsers", "Index", Handler = "Approve")] + public async Task>> Approve([FromBody] UserChange? change, CancellationToken cancellationToken = default) + => Respond(await Users.ApproveAsync(User, change ?? new UserChange(null, null), cancellationToken)); + + /// Makes a user an administrator. + [HttpPost("promote"), UiApi("AdminUsers", "Index", Handler = "Promote")] + public async Task>> Promote([FromBody] UserChange? change, CancellationToken cancellationToken = default) + => Respond(await Users.PromoteAsync(User, change ?? new UserChange(null, null), cancellationToken)); + + /// Removes a user's administrator flag. + [HttpPost("demote"), UiApi("AdminUsers", "Index", Handler = "Demote")] + public async Task>> Demote([FromBody] UserChange? change, CancellationToken cancellationToken = default) + => Respond(await Users.DemoteAsync(User, change ?? new UserChange(null, null), cancellationToken)); + + /// Replaces a user's password with a generated one, which the answer carries once (generatedPassword). + [HttpPost("reset-password"), UiApi("AdminUsers", "Index", Handler = "ResetPassword")] + public async Task>> ResetPassword([FromBody] UserChange? change, CancellationToken cancellationToken = default) + => Shown(await Users.ResetPasswordAsync(User, change ?? new UserChange(null, null), cancellationToken)); + + /// Mails a user a password reset link. + [HttpPost("send-reset-link"), UiApi("AdminUsers", "Index", Handler = "SendResetLink")] + public async Task>> SendResetLink([FromBody] UserChange? change, CancellationToken cancellationToken = default) + => Respond(await Users.SendResetLinkAsync(User, change ?? new UserChange(null, null), cancellationToken)); + + /// Creates an account (typed, generated or invited password). A generated password is in the answer once. + [HttpPost("create"), UiApi("AdminUsers", "Index", Handler = "Create")] + public async Task>> Create([FromBody] UserCreation? creation, CancellationToken cancellationToken = default) + => Shown(await Users.CreateAsync(User, creation ?? new UserCreation(null, null, null, false, null), cancellationToken)); + + // A password that is shown once must never be cached by the browser or a proxy. + private ActionResult> Shown(ScreenResult result) + { + if (result.Model?.GeneratedPassword != null) Response.Headers.CacheControl = "no-store"; + + return Respond(result); + } + + // ---------------------------------------------------------------- UserDetail + + /// Shows one account. is a package ID to evaluate the effective permissions for. + [HttpGet("{name}"), UiApi("AdminUsers", "Detail")] + public async Task>> Get(string name, string? package, CancellationToken cancellationToken = default) + => Respond(await Detail.GetAsync(User, name, package, cancellationToken)); + + /// Enables the account when it waits for approval. + [HttpPost("{name}/approve"), UiApi("AdminUsers", "Detail", Handler = "Approve")] + public async Task>> ApproveAccount(string name, [FromBody] PasswordForm? form, CancellationToken cancellationToken = default) + => Respond(await Detail.ApproveAsync(User, name, form?.Password, cancellationToken)); + + /// Revokes one of the account's API keys. + [HttpPost("{name}/revoke-key"), UiApi("AdminUsers", "Detail", Handler = "RevokeKey")] + public async Task>> RevokeKey(string name, [FromBody] UserKeyForm? form, CancellationToken cancellationToken = default) + => Respond(await Detail.RevokeKeyAsync(User, name, form?.Key ?? 0, form?.Password, cancellationToken)); + + /// Adds the account to a group. + [HttpPost("{name}/add-group"), UiApi("AdminUsers", "Detail", Handler = "AddGroup")] + public async Task>> AddGroup(string name, [FromBody] UserGroupForm? form, CancellationToken cancellationToken = default) + => Respond(await Detail.AddGroupAsync(User, name, form?.Group, form?.Password, cancellationToken)); + + /// Removes the account from a group. + [HttpPost("{name}/remove-group"), UiApi("AdminUsers", "Detail", Handler = "RemoveGroup")] + public async Task>> RemoveGroup(string name, [FromBody] UserGroupForm? form, CancellationToken cancellationToken = default) + => Respond(await Detail.RemoveGroupAsync(User, name, form?.Group, form?.Password, cancellationToken)); + + // ---------------------------------------------------------------- DeleteUser + + /// Shows what deleting the account does. + [HttpGet("{name}/delete"), UiApi("AdminUsers", "DeleteUser")] + public async Task>> GetDeletion(string name, CancellationToken cancellationToken = default) + => Respond(await Deletion.GetAsync(User, name, cancellationToken)); + + /// Deletes the account after the administrator's password. + [HttpPost("{name}/delete"), UiApi("AdminUsers", "DeleteUser")] + public async Task>> Delete(string name, [FromBody] UserDeletionForm? form, CancellationToken cancellationToken = default) + => Respond(await Deletion.DeleteAsync(User, name, form?.SoleOwned, form?.Password, cancellationToken)); + + // ---------------------------------------------------------------- UserPackages + + /// Lists the package IDs one user owns. + [HttpGet("{name}/packages"), UiApi("AdminUsers", "UserPackages"), RepositoryPage] + public async Task>> GetPackages(string name, CancellationToken cancellationToken = default) + => Respond(await Packages.GetUserAsync(name, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/ContactOwnersApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/ContactOwnersApiController.cs new file mode 100644 index 000000000..b2ee4d20e --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/ContactOwnersApiController.cs @@ -0,0 +1,40 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the contact-owners screen: GET /api/ui/packages/{id}/contact-owners (the form's state) and POST to the same +/// address with { "message": …, "copyToSelf": … } (also under /api/ui/r/{repo}/…). Needs accounts and mail, like the page. +/// Interactive session only: over HTTP it answers 403 to an API key and to an anonymous caller. ContactOwnersController calls it in process and renders the view. +/// +[Route("api/ui/packages/{id}/contact-owners")] +[RepositoryPage(NotOnVirtual = true)] +public sealed class ContactOwnersApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + /// + protected override bool RequiresEmail => true; + + private ContactOwnersUseCase UseCase => HttpContext.RequestServices.GetRequiredService(); + + /// The form's state; 404 when the package has no owner. + [HttpGet, UiApi("ContactOwners", "Index")] + public async Task>> Get(string? id, CancellationToken cancellationToken) + => Respond(await UseCase.GetAsync(User, id, cancellationToken)); + + /// Sends the message to the owners (400 with the field errors when the message is missing or too long). + [HttpPost, UiApi("ContactOwners", "Index")] + public async Task>> Send(string? id, [FromBody] ContactOwnersForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.SendAsync(User, id, form?.Message, form?.CopyToSelf ?? false, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/DockerManageApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/DockerManageApiController.cs new file mode 100644 index 000000000..49e05f198 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/DockerManageApiController.cs @@ -0,0 +1,60 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the Docker image management screen: GET /api/ui/docker-manage/{**image} and, for each handler of the page, +/// POST /api/ui/docker-manage/{handler-in-kebab-case}/{**image} with a JSON body (the image name has slashes, so the handler comes +/// first; also under /api/ui/r/{repo}/…). Interactive session only (403 over HTTP to an API key and to an anonymous caller; the web screen calls it in process). DockerManageController calls it in process and renders +/// the view. +/// +[Route("api/ui/docker-manage")] +[RepositoryPage(Format = RepositoryFormat.Docker, NotOnVirtual = true)] +public sealed class DockerManageApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + private DockerManageUseCase UseCase => HttpContext.RequestServices.GetRequiredService(); + + /// The image-name / repository-kind / Delete-permission check that opens every handler (see ). + [NonAction] + public Task?> EnterAsync(string? image, bool isWrite, CancellationToken cancellationToken) + => UseCase.EnterAsync(User, image, isWrite, cancellationToken); + + /// The screen. + [HttpGet("{**image}"), UiApi("DockerManage", "Index")] + public async Task>> Get(string? image, CancellationToken cancellationToken) + => Respond(await UseCase.GetAsync(User, image, cancellationToken)); + + /// Deletes a tag, after the password. + [HttpPost("delete-tag/{**image}"), UiApi("DockerManage", "Index", Handler = "DeleteTag")] + public async Task>> DeleteTag(string? image, [FromBody] DockerManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteTagAsync(User, image, form?.Tag, form?.Password, cancellationToken)); + + /// Deletes a manifest with its tags, after the password. + [HttpPost("delete-manifest/{**image}"), UiApi("DockerManage", "Index", Handler = "DeleteManifest")] + public async Task>> DeleteManifest(string? image, [FromBody] DockerManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteManifestAsync(User, image, form?.Digest, form?.Password, cancellationToken)); + + /// Removes the layers no manifest uses, after the password. + [HttpPost("prune/{**image}"), UiApi("DockerManage", "Index", Handler = "Prune")] + public async Task>> Prune(string? image, [FromBody] DockerManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.PruneAsync(User, image, form?.Password, cancellationToken)); + + /// Deletes the whole image, after the password. + [HttpPost("delete-image/{**image}"), UiApi("DockerManage", "Index", Handler = "DeleteImage")] + public async Task>> DeleteImage(string? image, [FromBody] DockerManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteImageAsync(User, image, form?.Password, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/MavenManageApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/MavenManageApiController.cs new file mode 100644 index 000000000..74a7b3ddc --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/MavenManageApiController.cs @@ -0,0 +1,69 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the Maven artifact management screen: GET /api/ui/maven-manage/{group}/{artifact}?version= and, for each handler +/// of the page, POST /api/ui/maven-manage/{group}/{artifact}/{handler-in-kebab-case} with a JSON body (also under +/// /api/ui/r/{repo}/…). Interactive session only (403 over HTTP to an API key and to an anonymous caller; the web screen calls it in process). MavenManageController calls it in process and renders the view. +/// +[Route("api/ui/maven-manage/{group}/{artifact}")] +[RepositoryPage(Format = RepositoryFormat.Maven, NotOnVirtual = true, NotOnRemote = true)] +public sealed class MavenManageApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + private MavenManageUseCase UseCase => HttpContext.RequestServices.GetRequiredService(); + + /// The coordinates / repository-kind / ownership check that opens every handler (see ). + [NonAction] + public Task?> EnterAsync(string? group, string? artifact, string? version, string? handler, bool isWrite, CancellationToken cancellationToken) + => UseCase.EnterAsync(User, group, artifact, version, handler, isWrite, cancellationToken); + + /// The screen. + [HttpGet, UiApi("MavenManage", "Index")] + public async Task>> Get(string? group, string? artifact, [FromQuery] string? version, CancellationToken cancellationToken) + => Respond(await UseCase.GetAsync(User, group, artifact, version, cancellationToken)); + + /// Adds an owner. + [HttpPost("add-owner"), UiApi("MavenManage", "Index", Handler = "AddOwner")] + public async Task>> AddOwner(string? group, string? artifact, [FromBody] MavenManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.AddOwnerAsync(User, group, artifact, form?.Version, form?.OwnerName, cancellationToken)); + + /// Removes an owner. + [HttpPost("remove-owner"), UiApi("MavenManage", "Index", Handler = "RemoveOwner")] + public async Task>> RemoveOwner(string? group, string? artifact, [FromBody] MavenManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.RemoveOwnerAsync(User, group, artifact, form?.Version, form?.OwnerName, cancellationToken)); + + /// Deletes one file of the chosen version, after the password. + [HttpPost("delete-file"), UiApi("MavenManage", "Index", Handler = "DeleteFile")] + public async Task>> DeleteFile(string? group, string? artifact, [FromBody] MavenManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteFileAsync(User, group, artifact, form?.Version, form?.FileName, form?.Password, cancellationToken)); + + /// Deletes one version, after the password. + [HttpPost("delete-version"), UiApi("MavenManage", "Index", Handler = "DeleteVersion")] + public async Task>> DeleteVersion(string? group, string? artifact, [FromBody] MavenManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteVersionAsync(User, group, artifact, form?.Version, form?.Version, form?.Password, cancellationToken)); + + /// Deletes the whole artifact, after the password. + [HttpPost("delete-artifact"), UiApi("MavenManage", "Index", Handler = "DeleteArtifact")] + public async Task>> DeleteArtifact(string? group, string? artifact, [FromBody] MavenManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteArtifactAsync(User, group, artifact, form?.Version, form?.Password, cancellationToken)); + + /// Deletes old snapshot builds of a version, after the password. + [HttpPost("cleanup"), UiApi("MavenManage", "Index", Handler = "Cleanup")] + public async Task>> Cleanup(string? group, string? artifact, [FromBody] MavenManageForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.CleanupAsync(User, group, artifact, form?.Version, form?.Version, form?.Keep, form?.Password, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/NpmManageApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/NpmManageApiController.cs new file mode 100644 index 000000000..3306701d0 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/NpmManageApiController.cs @@ -0,0 +1,79 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the npm package management screen: GET /api/ui/npm-manage/{*id} and, for each handler of the page, POST +/// /api/ui/npm-manage/{handler-in-kebab-case}/{*id} with a JSON body (the package name is a catch-all, so the handler comes first; also +/// under /api/ui/r/{repo}/…). Interactive session only (403 over HTTP to an API key and to an anonymous caller; the web screen calls it in process). NpmManageController calls it in process and renders the view. +/// +[Route("api/ui/npm-manage")] +[RepositoryPage(Format = RepositoryFormat.Npm, NotOnVirtual = true, NotOnRemote = true)] +public sealed class NpmManageApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + private NpmManageUseCase UseCase => HttpContext.RequestServices.GetRequiredService(); + + /// The name / repository-kind / ownership check that opens every handler (see ). + [NonAction] + public Task?> EnterAsync(string? id, string? handler, bool isWrite, CancellationToken cancellationToken) + => UseCase.EnterAsync(User, id, handler, isWrite, cancellationToken); + + /// The screen. + [HttpGet("{*id}"), UiApi("NpmManage", "Index")] + public async Task>> Get(string? id, CancellationToken cancellationToken) + => Respond(await UseCase.GetAsync(User, id, cancellationToken)); + + /// Adds an owner. + [HttpPost("add-owner/{*id}"), UiApi("NpmManage", "Index", Handler = "AddOwner")] + public async Task>> AddOwner(string? id, [FromBody] NpmManageOwnerForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.AddOwnerAsync(User, id, form?.OwnerName, cancellationToken)); + + /// Removes an owner. + [HttpPost("remove-owner/{*id}"), UiApi("NpmManage", "Index", Handler = "RemoveOwner")] + public async Task>> RemoveOwner(string? id, [FromBody] NpmManageOwnerForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.RemoveOwnerAsync(User, id, form?.OwnerName, cancellationToken)); + + /// Points a dist-tag at a version. + [HttpPost("set-tag/{*id}"), UiApi("NpmManage", "Index", Handler = "SetTag")] + public async Task>> SetTag(string? id, [FromBody] NpmManageTagForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.SetTagAsync(User, id, form?.Tag, form?.Version, cancellationToken)); + + /// Removes a dist-tag. + [HttpPost("remove-tag/{*id}"), UiApi("NpmManage", "Index", Handler = "RemoveTag")] + public async Task>> RemoveTag(string? id, [FromBody] NpmManageTagForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.RemoveTagAsync(User, id, form?.Tag, cancellationToken)); + + /// Deprecates a version. + [HttpPost("deprecate/{*id}"), UiApi("NpmManage", "Index", Handler = "Deprecate")] + public async Task>> Deprecate(string? id, [FromBody] NpmManageDeprecateForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeprecateAsync(User, id, form?.Version, form?.Message, cancellationToken)); + + /// Removes a version's deprecation. + [HttpPost("undeprecate/{*id}"), UiApi("NpmManage", "Index", Handler = "Undeprecate")] + public async Task>> Undeprecate(string? id, [FromBody] NpmManageDeprecateForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.UndeprecateAsync(User, id, form?.Version, cancellationToken)); + + /// Unpublishes one version, after the password is confirmed. + [HttpPost("unpublish/{*id}"), UiApi("NpmManage", "Index", Handler = "Unpublish")] + public async Task>> Unpublish(string? id, [FromBody] NpmManageUnpublishForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.UnpublishAsync(User, id, form?.Version, form?.Password, cancellationToken)); + + /// Unpublishes every version, after the password is confirmed. + [HttpPost("unpublish-all/{*id}"), UiApi("NpmManage", "Index", Handler = "UnpublishAll")] + public async Task>> UnpublishAll(string? id, [FromBody] NpmManageUnpublishForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.UnpublishAllAsync(User, id, form?.Password, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/PackageManageApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/PackageManageApiController.cs new file mode 100644 index 000000000..85677682f --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/PackageManageApiController.cs @@ -0,0 +1,108 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the package management screen: GET /api/ui/packages/{id}/manage and, for each handler of the page, POST +/// /api/ui/packages/{id}/manage/{handler-in-kebab-case} with a JSON body (also under /api/ui/r/{repo}/…). Interactive session only (403 over HTTP to an API key and to an anonymous caller; the web screen calls it in process): +/// an API key never manages a package through this screen. PackageManageController calls it in process and renders the view. +/// +[Route("api/ui/packages/{id}/manage")] +[RepositoryPage(NotOnVirtual = true)] +public sealed class PackageManageApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + // Resolved per request, after the gate: the use case exists only while accounts are enabled. + private PackageManageUseCase UseCase => HttpContext.RequestServices.GetRequiredService(); + + /// The owner / administrator check that opens every handler (the view controller asks it first; the use case remembers the answer). + [NonAction] + public Task?> EnterAsync(string? id, string? handler, bool isWrite, CancellationToken cancellationToken) + => UseCase.EnterAsync(User, id, handler, isWrite, cancellationToken); + + /// The screen. + [HttpGet, UiApi("PackageManage", "Index")] + public async Task>> Get(string id, CancellationToken cancellationToken) + => Respond(await UseCase.GetAsync(User, id, cancellationToken)); + + /// Adds an owner. + [HttpPost("add-owner"), UiApi("PackageManage", "Index", Handler = "AddOwner")] + public async Task>> AddOwner(string id, [FromBody] PackageManageOwnerForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.AddOwnerAsync(User, id, form?.OwnerName, cancellationToken)); + + /// Removes an owner. + [HttpPost("remove-owner"), UiApi("PackageManage", "Index", Handler = "RemoveOwner")] + public async Task>> RemoveOwner(string id, [FromBody] PackageManageOwnerForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.RemoveOwnerAsync(User, id, form?.OwnerName, cancellationToken)); + + /// Unlists a version. + [HttpPost("unlist"), UiApi("PackageManage", "Index", Handler = "Unlist")] + public async Task>> Unlist(string id, [FromBody] PackageManageVersionForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.UnlistAsync(User, id, form?.Version, cancellationToken)); + + /// Relists a version. + [HttpPost("relist"), UiApi("PackageManage", "Index", Handler = "Relist")] + public async Task>> Relist(string id, [FromBody] PackageManageVersionForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.RelistAsync(User, id, form?.Version, cancellationToken)); + + /// Deletes a version as the server is configured to (unlist or permanent). + [HttpPost("delete"), UiApi("PackageManage", "Index", Handler = "Delete")] + public async Task>> Delete(string id, [FromBody] PackageManageVersionForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteAsync(User, id, form?.Version, cancellationToken)); + + /// Permanently deletes a version (administrators, after the password). + [HttpPost("hard-delete"), UiApi("PackageManage", "Index", Handler = "HardDelete")] + public async Task>> HardDelete(string id, [FromBody] PackageManageHardDeleteForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.HardDeleteAsync(User, id, form?.Version, form?.Password, cancellationToken)); + + /// Permanently deletes every version and the owners (administrators, after the password). + [HttpPost("hard-delete-all"), UiApi("PackageManage", "Index", Handler = "HardDeleteAll")] + public async Task>> HardDeleteAll(string id, [FromBody] PackageManagePasswordForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.HardDeleteAllAsync(User, id, form?.Password, cancellationToken)); + + /// Deprecates a version. + [HttpPost("deprecate"), UiApi("PackageManage", "Index", Handler = "Deprecate")] + public async Task>> Deprecate(string id, [FromBody] PackageManageDeprecateForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeprecateAsync(User, id, form?.Version, form?.Reasons, form?.Message, form?.AlternatePackageId, form?.AlternateVersionRange, cancellationToken)); + + /// Removes a version's deprecation. + [HttpPost("undeprecate"), UiApi("PackageManage", "Index", Handler = "Undeprecate")] + public async Task>> Undeprecate(string id, [FromBody] PackageManageVersionForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.UndeprecateAsync(User, id, form?.Version, cancellationToken)); + + /// Adds a vulnerability to a version. + [HttpPost("add-vulnerability"), UiApi("PackageManage", "Index", Handler = "AddVulnerability")] + public async Task>> AddVulnerability(string id, [FromBody] PackageManageVulnerabilityForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.AddVulnerabilityAsync(User, id, form?.Version, form?.AdvisoryUrl, form?.Severity ?? 0, form?.VersionRange, cancellationToken)); + + /// Removes a vulnerability from a version. + [HttpPost("remove-vulnerability"), UiApi("PackageManage", "Index", Handler = "RemoveVulnerability")] + public async Task>> RemoveVulnerability(string id, [FromBody] PackageManageRemoveVulnerabilityForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.RemoveVulnerabilityAsync(User, id, form?.Version, form?.Key ?? 0, cancellationToken)); + + /// Marks or unmarks the ID as verified (administrators). + [HttpPost("set-verified"), UiApi("PackageManage", "Index", Handler = "SetVerified")] + public async Task>> SetVerified(string id, [FromBody] PackageManageVerifiedForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.SetVerifiedAsync(User, id, form?.Verified ?? false, cancellationToken)); + + /// Deletes the PDBs recorded for a version. + [HttpPost("delete-symbols"), UiApi("PackageManage", "Index", Handler = "DeleteSymbols")] + public async Task>> DeleteSymbols(string id, [FromBody] PackageManageVersionForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.DeleteSymbolsAsync(User, id, form?.Version, cancellationToken)); + + /// Resolves an abuse report. + [HttpPost("resolve-report"), UiApi("PackageManage", "Index", Handler = "ResolveReport")] + public async Task>> ResolveReport(string id, [FromBody] PackageManageReportForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.ResolveReportAsync(User, id, form?.Key ?? 0, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/ProfileApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/ProfileApiController.cs new file mode 100644 index 000000000..b0f2b57d4 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/ProfileApiController.cs @@ -0,0 +1,29 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of a user's or an organization's public page (/api/ui/profiles/{name}, and /api/ui/r/{repo}/profiles/{name}): +/// ProfileController calls it in process. The page is public data (names, owned package IDs with their downloads, an avatar address), +/// so unlike the other account screens an API key may read it too. +/// +[Route("api/ui/profiles")] +[RepositoryPage] +public sealed class ProfileApiController : AccountApiControllerBase +{ + /// + protected override bool CookieOnly => false; + + /// The profile named ; 404 when neither a user nor an organization has it. + [HttpGet("{name}"), UiApi("Profile", "Profile")] + public async Task>> Profile(string? name, CancellationToken cancellationToken) + => Respond(await UseCase().ShowAsync(User, name, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/ReplicationApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/ReplicationApiController.cs new file mode 100644 index 000000000..692d77c3b --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/ReplicationApiController.cs @@ -0,0 +1,74 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Policies; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the replication screens (/api/ui/admin/replication): the replications and one replication (save, test the connection, run, +/// resume, stop, delete, its log). AdminReplicationController calls it in process. Administrators only; everything but stopping asks +/// the administrator's password in the body; every write is refused with 503 while the server is read-only. The peer API key is write only: it can +/// be sent in form.apiKey and is never part of an answer. +/// +[Route("api/ui/admin/replication")] +public sealed class ReplicationApiController : AccessApiControllerBase +{ + private ReplicationUseCase Replication => UseCase(); + + private string ReturnPage => "~" + Request.Path + Request.QueryString; + + // ---------------------------------------------------------------- replications + + /// Lists the replications and the form that creates one. + [HttpGet(""), UiApi("AdminReplication", "Index")] + public async Task>> GetReplications(CancellationToken cancellationToken = default) + => Respond(await Replication.GetReplicationsAsync(User, ReturnPage, cancellationToken)); + + /// Creates a replication and opens it. + [HttpPost(""), UiApi("AdminReplication", "Index")] + public async Task>> Create([FromBody] ReplicationBody? body, CancellationToken cancellationToken = default) + => Respond(await Replication.CreateAsync(User, body, ReturnPage, cancellationToken)); + + // ---------------------------------------------------------------- one replication + + /// Shows one replication with its log. + [HttpGet("{key:int}"), UiApi("AdminReplication", "Config")] + public async Task>> GetConfig(int key, CancellationToken cancellationToken = default) + => Respond(await Replication.GetConfigAsync(User, key, ReturnPage, cancellationToken)); + + /// Saves the settings. + [HttpPost("{key:int}/save"), UiApi("AdminReplication", "Config", Handler = "Save")] + public async Task>> Save(int key, [FromBody] ReplicationBody? body, CancellationToken cancellationToken = default) + => Respond(await Replication.SaveAsync(User, key, body, cancellationToken)); + + /// Tests the connection with the typed settings; saves nothing. + [HttpPost("{key:int}/test"), UiApi("AdminReplication", "Config", Handler = "Test")] + public async Task>> Test(int key, [FromBody] ReplicationBody? body, CancellationToken cancellationToken = default) + => Respond(await Replication.TestAsync(User, key, body, ReturnPage, cancellationToken)); + + /// Starts a run. + [HttpPost("{key:int}/run"), UiApi("AdminReplication", "Config", Handler = "Run")] + public async Task>> Run(int key, [FromBody] PasswordForm? body, CancellationToken cancellationToken = default) + => Respond(await Replication.RunAsync(User, key, body?.Password, cancellationToken)); + + /// Starts a run that continues the last interrupted or failed one. + [HttpPost("{key:int}/resume"), UiApi("AdminReplication", "Config", Handler = "Resume")] + public async Task>> Resume(int key, [FromBody] PasswordForm? body, CancellationToken cancellationToken = default) + => Respond(await Replication.ResumeAsync(User, key, body?.Password, cancellationToken)); + + /// Asks the running replication to stop; it ends as interrupted and can be resumed. + [HttpPost("{key:int}/stop"), UiApi("AdminReplication", "Config", Handler = "Stop")] + public async Task>> Stop(int key, CancellationToken cancellationToken = default) + => Respond(await Replication.StopAsync(key, cancellationToken)); + + /// Deletes the configuration with its log. + [HttpPost("{key:int}/delete"), UiApi("AdminReplication", "Config", Handler = "Delete")] + public async Task>> Delete(int key, [FromBody] PasswordForm? body, CancellationToken cancellationToken = default) + => Respond(await Replication.DeleteAsync(User, key, body?.Password, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/RetentionApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/RetentionApiController.cs new file mode 100644 index 000000000..f227ba3b6 --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/RetentionApiController.cs @@ -0,0 +1,82 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Policies; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the retention screens (/api/ui/admin/retention): the policies, one policy (save, dry run, run now, delete) and the legal +/// holds. AdminRetentionController calls it in process. Administrators only; creating, saving, running and deleting a policy and +/// lifting a hold ask the administrator's password in the body; every write is refused with 503 while the server is read-only. +/// +[Route("api/ui/admin/retention")] +public sealed class RetentionApiController : AccessApiControllerBase +{ + private RetentionUseCase Retention => UseCase(); + + private string ReturnPage => "~" + Request.Path + Request.QueryString; + + // ---------------------------------------------------------------- policies + + /// Lists the policies and the form that creates one. + [HttpGet(""), UiApi("AdminRetention", "Index")] + public async Task>> GetPolicies(CancellationToken cancellationToken = default) + => Respond(await Retention.GetPoliciesAsync(User, ReturnPage, cancellationToken)); + + /// Creates a policy and opens it. + [HttpPost(""), UiApi("AdminRetention", "Index")] + public async Task>> Create([FromBody] RetentionPolicyBody? body, CancellationToken cancellationToken = default) + => Respond(await Retention.CreateAsync(User, body, ReturnPage, cancellationToken)); + + // ---------------------------------------------------------------- one policy + + /// Shows one policy, its last run and report. + [HttpGet("{key:int}"), UiApi("AdminRetention", "Policy")] + public async Task>> GetPolicy(int key, CancellationToken cancellationToken = default) + => Respond(await Retention.GetPolicyAsync(User, key, ReturnPage, cancellationToken)); + + /// Saves the rules. + [HttpPost("{key:int}/save"), UiApi("AdminRetention", "Policy", Handler = "Save")] + public async Task>> Save(int key, [FromBody] RetentionPolicyBody? body, CancellationToken cancellationToken = default) + => Respond(await Retention.SaveAsync(User, key, body, cancellationToken)); + + /// Starts a dry run: the report of what a run would delete. + [HttpPost("{key:int}/dry-run"), UiApi("AdminRetention", "Policy", Handler = "DryRun")] + public async Task>> DryRun(int key, CancellationToken cancellationToken = default) + => Respond(await Retention.DryRunAsync(User, key, cancellationToken)); + + /// Starts a run that deletes. + [HttpPost("{key:int}/run"), UiApi("AdminRetention", "Policy", Handler = "Run")] + public async Task>> Run(int key, [FromBody] PasswordForm? body, CancellationToken cancellationToken = default) + => Respond(await Retention.RunAsync(User, key, body?.Password, cancellationToken)); + + /// Deletes the policy (what it deleted stays deleted). + [HttpPost("{key:int}/delete"), UiApi("AdminRetention", "Policy", Handler = "Delete")] + public async Task>> Delete(int key, [FromBody] PasswordForm? body, CancellationToken cancellationToken = default) + => Respond(await Retention.DeleteAsync(User, key, body?.Password, cancellationToken)); + + // ---------------------------------------------------------------- holds + + /// Lists the legal holds (of ?repository= only, when given). + [HttpGet("holds"), UiApi("AdminRetention", "Holds")] + public async Task>> GetHolds([FromQuery] string? repository, CancellationToken cancellationToken = default) + => Respond(await Retention.GetHoldsAsync(User, repository, ReturnPage, cancellationToken)); + + /// Places a hold. + [HttpPost("holds/add"), UiApi("AdminRetention", "Holds", Handler = "Add")] + public async Task>> AddHold( + [FromQuery] string? repository, [FromBody] RetentionHoldForm? form, CancellationToken cancellationToken = default) + => Respond(await Retention.AddHoldAsync(User, repository, form, ReturnPage, cancellationToken)); + + /// Lifts a hold. + [HttpPost("holds/remove"), UiApi("AdminRetention", "Holds", Handler = "Remove")] + public async Task>> RemoveHold( + [FromQuery] string? repository, [FromBody] RetentionHoldRemoval? removal, CancellationToken cancellationToken = default) + => Respond(await Retention.RemoveHoldAsync(User, repository, removal, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/ScanArtifactApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/ScanArtifactApiController.cs new file mode 100644 index 000000000..f79f0726c --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/ScanArtifactApiController.cs @@ -0,0 +1,43 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.UseCases.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of Scan now: GET /api/ui/scan-artifact?name=&version= (the stored result) and POST +/// /api/ui/scan-artifact with { "name": …, "version": … } (scans now, or queues an image; also under /api/ui/r/{repo}/…). +/// 403 without the Manage action on the artifact. A refused scan answers with the screen under 409 (scanning unavailable) or 404 (no such +/// version). Interactive session only: over HTTP it answers 403 to an API key and to an anonymous caller. ScanArtifactController calls it in process and renders the view. +/// +[Route("api/ui/scan-artifact")] +[RepositoryPage(AnyFormat = true, NotOnVirtual = true)] +public sealed class ScanArtifactApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + private ScanArtifactUseCase UseCase => HttpContext.RequestServices.GetRequiredService(); + + /// Shows the form (and the stored result) of the version. + [HttpGet, UiApi("ScanArtifact", "Index")] + public async Task>> Get(string? name, string? version, string? returnUrl, CancellationToken cancellationToken) + => Respond(await UseCase.GetAsync(User, name, version, returnUrl, BackUrl(returnUrl), cancellationToken)); + + /// Scans the version now (or queues it, for an image) and shows the outcome. + [HttpPost, UiApi("ScanArtifact", "Index")] + public async Task>> Scan([FromBody] ScanArtifactForm? form, CancellationToken cancellationToken) + => Respond(await UseCase.ScanAsync(User, form?.Name, form?.Version, form?.ReturnUrl, BackUrl(form?.ReturnUrl), cancellationToken)); + + // The return address when it is local, else the home page (under the path base). + private string BackUrl(string? returnUrl) + => !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : Url.Content("~/") ?? "/"; +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/ScanningApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/ScanningApiController.cs new file mode 100644 index 000000000..154ca94be --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/ScanningApiController.cs @@ -0,0 +1,63 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.UseCases.Policies; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the vulnerability scanning screens (/api/ui/admin/scanning): the overview, the dashboard of a repository (findings, +/// policy, Scan now) and the policy of a project. AdminScanningController calls it in process. Administrators only; saving a +/// policy asks the administrator's password in the body; every write is refused with 503 while the server is read-only. The links to the package +/// screens of the findings are packageLinks (controller, action and route values), not addresses. +/// +[Route("api/ui/admin/scanning")] +public sealed class ScanningApiController : AccessApiControllerBase +{ + private ScanningUseCase Scanning => UseCase(); + + private string ReturnPage => "~" + Request.Path + Request.QueryString; + + // ---------------------------------------------------------------- overview + + /// The overview of every repository and project. + [HttpGet(""), UiApi("AdminScanning", "Index")] + public async Task>> GetOverview(CancellationToken cancellationToken = default) + => Respond(await Scanning.GetOverviewAsync(cancellationToken)); + + // ---------------------------------------------------------------- one repository + + /// The dashboard of a repository: ?min= is the lowest severity listed (0 to 3), ?p= the page. + [HttpGet("{name}"), UiApi("AdminScanning", "Repository")] + public async Task>> GetRepository( + string name, [FromQuery(Name = "min")] int minSeverity, [FromQuery(Name = "p")] int pageNumber, CancellationToken cancellationToken = default) + => Respond(await Scanning.GetRepositoryAsync(User, name, minSeverity, pageNumber, ReturnPage, cancellationToken)); + + /// Saves the repository policy; empty values remove it. + [HttpPost("{name}/policy"), UiApi("AdminScanning", "Repository", Handler = "Policy")] + public async Task>> SaveRepositoryPolicy( + string name, [FromBody] ScanPolicyBody? body, CancellationToken cancellationToken = default) + => Respond(await Scanning.SaveRepositoryPolicyAsync(User, name, body, cancellationToken)); + + /// Starts a scan of every artifact of the repository in the background. + [HttpPost("{name}/scan"), UiApi("AdminScanning", "Repository", Handler = "Scan")] + public async Task>> Scan(string name, CancellationToken cancellationToken = default) + => Respond(await Scanning.ScanAsync(User, name, cancellationToken)); + + // ---------------------------------------------------------------- one project + + /// The scanning policy of a project. + [HttpGet("projects/{name}"), UiApi("AdminScanning", "Project")] + public async Task>> GetProject(string name, CancellationToken cancellationToken = default) + => Respond(await Scanning.GetProjectAsync(User, name, ReturnPage, cancellationToken)); + + /// Saves the project policy; empty values remove it. + [HttpPost("projects/{name}/policy"), UiApi("AdminScanning", "Project", Handler = "Policy")] + public async Task>> SaveProjectPolicy( + string name, [FromBody] ScanPolicyBody? body, CancellationToken cancellationToken = default) + => Respond(await Scanning.SaveProjectPolicyAsync(User, name, body, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/SessionApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/SessionApiController.cs new file mode 100644 index 000000000..fdb99c80d --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/SessionApiController.cs @@ -0,0 +1,255 @@ +using System; +using BaGet.Identity.Application.Services.Accounts; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Session; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.UseCases.Account; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using Microsoft.Net.Http.Headers; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// Interactive sessions for a single-page application (/api/ui/session, /api/ui/antiforgery): sign in with the password (and the second +/// factor), refresh, sign out, the external provider, the cookie variant for a same-origin client, and the antiforgery token. These are not the twin of a +/// screen (the sign-in page sets a cookie; here the answer is a pair of tokens), so they carry no [UiApi] and are not part of the parity rules. They +/// answer 404 while accounts are off. Every action is an : an expired session token in the header is no credential +/// on them, and a browser request from another origin is refused unless Cors:AllowedOrigins lists it. Tokens are only ever in a body, a header, or (the external +/// sign-in, as a 60-second exchange token) the URL fragment of the address the application returned to, never in a query string or a log; every answer carrying them is no-store. +/// +[Route("api/ui")] +public sealed class SessionApiController : ApiControllerBase +{ + private readonly IOptions _cors; + private readonly IOptions _frontend; + + /// Creates the controller. + public SessionApiController(IOptions cors, IOptions frontend) + { + _cors = cors ?? throw new ArgumentNullException(nameof(cors)); + _frontend = frontend ?? throw new ArgumentNullException(nameof(frontend)); + } + + // ----- password + + /// + /// Signs in with the user name and password. Answers the tokens, or twoFactorRequired with a short-lived twoFactorTicket for + /// /session/two-factor or /session/recovery-code. 401 for wrong credentials, 403 for a locked, unapproved or unconfirmed account. + /// + [HttpPost("session"), AnonymousSessionEndpoint] + public async Task>> SignIn([FromBody] SessionSignInForm? form) + => Tokens(Disabled() ?? await UseCase().SignInAsync(form)); + + /// Completes a sign-in with a code of the authenticator app. + [HttpPost("session/two-factor"), AnonymousSessionEndpoint] + public async Task>> TwoFactor([FromBody] SessionTwoFactorForm? form) + => Tokens(Disabled() ?? await UseCase().TwoFactorAsync(form)); + + /// Completes a sign-in with a recovery code (each works once). + [HttpPost("session/recovery-code"), AnonymousSessionEndpoint] + public async Task>> RecoveryCode([FromBody] SessionRecoveryCodeForm? form) + => Tokens(Disabled() ?? await UseCase().RecoveryCodeAsync(form)); + + /// Exchanges the refresh token for a new pair of tokens (the authentication time is kept; the session ends Accounts:SessionMaxLifetime after the sign-in). + [HttpPost("session/refresh"), AnonymousSessionEndpoint] + public async Task>> Refresh([FromBody] SessionRefreshForm? form) + => Tokens(Disabled() ?? await UseCase().RefreshAsync(form)); + + /// Exchanges the 60-second exchange_token of an external sign-in's redirect for the tokens (or the two-factor ticket). + [HttpPost("session/exchange"), AnonymousSessionEndpoint] + public async Task>> Exchange([FromBody] SessionExchangeForm? form) + => Tokens(Disabled() ?? await UseCase().ExchangeAsync(form)); + + /// + /// Ends the session: the client forgets its tokens. With everywhere the account's security stamp changes and every token and cookie + /// session of the account stops working. The caller is the access token, or the refresh token in the body. + /// + [HttpPost("session/sign-out"), AnonymousSessionEndpoint] + public async Task>> SignOutSession([FromBody] SessionSignOutForm? form) + { + if (!Gate.AccountsEnabled) return Respond(ScreenResult.NotFound()); + + NoStore(); + + return Respond(await UseCase().SignOutAsync(InteractiveCaller != null ? User : null, form)); + } + + // ----- the cookie, for a client served from this server's origin + + /// + /// Signs in with the cookie (same origin only; needs the antiforgery token of GET /api/ui/antiforgery fetched while signed out, so a cross-site page cannot + /// sign a visitor in): the rules of POST /session, the second factor in the same endpoint (ticket with code or recoveryCode), but the answer holds no tokens. + /// Fetch the antiforgery token again afterwards: it is bound to the signed-in user. + /// + [HttpPost("session/cookie"), AnonymousSessionEndpoint(SameOriginOnly = true, RequireAntiforgery = true)] + public async Task>> CookieSignIn([FromBody] SessionCookieForm? form) + => Tokens(Disabled() ?? await UseCase().CookieSignInAsync(form)); + + /// Signs the cookie session out (same origin; send the cookie with the antiforgery header). 401 for anything but a cookie session. + [HttpPost("session/cookie/sign-out"), AnonymousSessionEndpoint(SameOriginOnly = true)] + public async Task>> CookieSignOut() + { + if (!Gate.AccountsEnabled) return Respond(ScreenResult.NotFound()); + + // Only the cookie session: a token session has no cookie, and signing out would end an unrelated one of the browser. + if (InteractiveCaller == null || HttpContext.Items.ContainsKey(AccountConfirmation.SessionAuthenticatedItem)) + { + return Respond(ScreenResult.SignIn("Send the session cookie with a valid X-XSRF-TOKEN header.")); + } + + await UseCase().LogoutAsync(); + NoStore(); + + return Respond(ScreenResult.Ok(EmptyScreen.Instance)); + } + + // ----- the external providers on offer + + /// + /// The external sign-in providers a client can offer before anyone is signed in (the sign-in screen's model is interactive-only): their ids, to put in + /// /session/external/{id}, and the names for the buttons. An empty list when none is configured. + /// + [HttpGet("session/providers"), AnonymousSessionEndpoint] + public ActionResult> Providers() + { + if (!Gate.AccountsEnabled) return Respond(ScreenResult.NotFound()); + + return Respond(ScreenResult.Ok(new SessionProvidersModel { Providers = UseCase().Configured })); + } + + // ----- antiforgery for the cookie + + /// + /// The antiforgery request token for a same-origin client that uses the cookie session: send it in the X-XSRF-TOKEN header (every method). It + /// is bound to the signed-in user, so fetch it again after signing in or out. Also sets the antiforgery cookie. + /// + [HttpGet("antiforgery"), AnonymousSessionEndpoint] + public ActionResult> AntiforgeryToken([FromServices] IAntiforgery? antiforgery) + { + if (!Gate.AccountsEnabled || antiforgery == null) return Respond(ScreenResult.NotFound()); + + // The token is bound to the user the cookie authenticates, which the security filter reset for this (credential-less) request. + var current = HttpContext.User; + HttpContext.User = UiApiCaller.CookieUser(HttpContext) ?? current; + try + { + var tokens = antiforgery.GetAndStoreTokens(HttpContext); + NoStore(); + + return Respond(ScreenResult.Ok(new AntiforgeryTokenModel { HeaderName = UiApiCaller.AntiforgeryHeader, RequestToken = tokens.RequestToken })); + } + finally + { + HttpContext.User = current; + } + } + + // ----- the confirmation link again + + /// + /// Mails a new confirmation link to an account whose address is not confirmed. The answer is the same whether or not an account matches or the mail was allowed + /// (one per account per ten minutes, and per client); 404 without outgoing mail. + /// + [HttpPost("account/resend-confirmation"), AnonymousSessionEndpoint] + public async Task>> ResendConfirmation([FromBody] ForgotPasswordForm? form) + { + if (!Gate.AccountsEnabled || !Gate.EmailConfigured) return Respond(ScreenResult.NotFound()); + + return Respond(await UseCase().ResendConfirmationAsync(form, HttpContext.Connection.RemoteIpAddress?.ToString())); + } + + // ----- the external provider + + /// + /// Starts the sign-in with the external provider (a browser navigation, not a fetch). The result comes back in the URL fragment of + /// , which must lie under Frontend:SpaBasePath of this server, or be an address of an origin listed in Cors:AllowedOrigins. + /// + [HttpGet("session/external/{provider}"), AnonymousSessionEndpoint] + public IActionResult External(string provider, string? returnUrl) + { + // Not a provider id at all: 404. The return address is judged before the provider is looked up, so a probe learns nothing from the order. + if (!Gate.AccountsEnabled || OpenIdConnectProviders.ValidateId(provider?.ToLowerInvariant()) != null) return NotFound(); + if (!ReturnUrlAllowed(returnUrl)) return BadRequest(new { error = ReturnUrlMessage }); + + var callback = Url.Action(nameof(ExternalCallback), "SessionApi", new { returnUrl }, Request.Scheme); + var challenge = UseCase().Start(provider!, callback!); + if (challenge == null) return NotFound(); + + return Challenge(challenge.Properties, challenge.Scheme); + } + + /// + /// The provider's answer: redirects to with, in the URL fragment, exchange_token (+ exchange_expires_at, user_name), to exchange within + /// a minute at POST /api/ui/session/exchange, or notice (account created, not usable yet) or error. No token of the session itself is ever put in a URL. + /// + [HttpGet("session/external-callback"), AnonymousSessionEndpoint] + public async Task ExternalCallback(string? returnUrl, CancellationToken cancellationToken) + { + if (!Gate.AccountsEnabled) return NotFound(); + if (!ReturnUrlAllowed(returnUrl)) return BadRequest(new { error = ReturnUrlMessage }); + + var result = await UseCase().CompleteAsync(cancellationToken); + var fragment = new Dictionary(); + var model = result.Model; + + if (result.Status == ScreenStatus.Ok && model?.Notice != null) fragment["notice"] = model.Notice; + else if (result.Status == ScreenStatus.Ok && model?.ExchangeToken != null) + { + fragment["exchange_token"] = model.ExchangeToken; + fragment["exchange_expires_at"] = Iso(model.ExchangeExpiresAt); + fragment["user_name"] = model.UserName; + } + else + { + fragment["error"] = result.Errors.TryGetValue(string.Empty, out var errors) && errors.Length > 0 ? errors[0] : "The external sign-in failed."; + } + + NoStore(); + Response.Headers["Referrer-Policy"] = "no-referrer"; + + return Redirect(returnUrl + "#" + string.Join("&", fragment + .Where(p => p.Value != null) + .Select(p => Uri.EscapeDataString(p.Key) + "=" + Uri.EscapeDataString(p.Value!)))); + } + + // ----- helpers + + private const string ReturnUrlMessage = "returnUrl must lie under Frontend:SpaBasePath of this server, or be an address of an origin listed in Cors:AllowedOrigins."; + + private bool ReturnUrlAllowed(string? returnUrl) + => SessionReturnUrls.IsAllowed( + returnUrl, + Request.Scheme + "://" + Request.Host, + SessionReturnUrls.Origins(_cors.Value.AllowedOrigins), + _frontend.Value.NormalizedBasePath()); + + private static string? Iso(DateTime? value) => value?.ToString("O", CultureInfo.InvariantCulture); + + private ScreenResult? Disabled() + => Gate.AccountsEnabled ? null : ScreenResult.NotFound(); + + private ActionResult> Tokens(ScreenResult result) + { + NoStore(); + + return Respond(result); + } + + private void NoStore() + { + Response.Headers[HeaderNames.CacheControl] = "no-store"; + Response.Headers[HeaderNames.Pragma] = "no-cache"; + } +} diff --git a/src/BaGet.Identity.Api/Controllers/UI/ValidationStatusApiController.cs b/src/BaGet.Identity.Api/Controllers/UI/ValidationStatusApiController.cs new file mode 100644 index 000000000..68510f95d --- /dev/null +++ b/src/BaGet.Identity.Api/Controllers/UI/ValidationStatusApiController.cs @@ -0,0 +1,32 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Operations; +using BaGet.Identity.Application.UseCases.Packages; + +namespace BaGet.Identity.Controllers.UI; + +/// +/// The JSON twin of the validation status screen: GET /api/ui/packages/{id}/validation (also under /api/ui/r/{repo}/…), the +/// newest submission of each version and the verdict of its steps; 403 without Push or Manage on the ID, 404 when validation never saw it. +/// Interactive session only: over HTTP it answers 403 to an API key and to an anonymous caller. ValidationStatusPageController calls it in process and renders the view. +/// +[Route("api/ui/packages/{id}/validation")] +[RepositoryPage(NotOnVirtual = true)] +public sealed class ValidationStatusApiController : AccountApiControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + private ValidationStatusUseCase UseCase => HttpContext.RequestServices.GetRequiredService(); + + /// The submissions of the ID. + [HttpGet, UiApi("ValidationStatusPage", "Index")] + public async Task>> Get(string? id, CancellationToken cancellationToken) + => Respond(await UseCase.GetAsync(User, id, cancellationToken)); +} diff --git a/src/BaGet.Identity.Api/Extensions/AccountsServiceCollectionExtensions.cs b/src/BaGet.Identity.Api/Extensions/AccountsServiceCollectionExtensions.cs new file mode 100644 index 000000000..012aaa531 --- /dev/null +++ b/src/BaGet.Identity.Api/Extensions/AccountsServiceCollectionExtensions.cs @@ -0,0 +1,179 @@ +using System; +using BaGet.Core; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Frontend.Mvc.UI; +using BaGet.Frontend.Security; +using BaGet.Identity.Application.Extensions; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using BaGet.Identity.Application.Email; +using BaGet.Identity.Application.RateLimiting; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; +using BaGet.Identity.Application.Services.Sessions; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Extensions; + +public static class AccountsServiceCollectionExtensions +{ + public const string OpenIdConnectScheme = ExternalSignInUseCase.OpenIdConnectScheme; + + /// + /// Add accounts if "Accounts:Enabled" is set. Otherwise only an empty authentication + /// setup is added, so the pipeline's authentication middleware has nothing to do. + /// + public static IServiceCollection AddBaGetAccounts(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration.GetSection(nameof(BaGetOptions.Accounts)).Get() + ?? new AccountsOptions(); + + var site = configuration.GetSection(nameof(BaGetOptions.Site)).Get() ?? new SiteOptions(); + EmailLinkPolicy.ValidatePublicUrl(site.PublicUrl); + + // The screen gate is needed whether or not accounts are enabled: the screens answer 404 through it while they are off. + services.AddBaGetIdentityApplication(); + + if (!options.Enabled) + { + services.AddAuthentication(); + return services; + } + + // The providers whose handlers are registered below are the ones every screen and flow offers. An invalid configuration stops the startup. + var providers = OpenIdConnectProviders.Resolve(options); + services.Replace(ServiceDescriptor.Singleton(providers)); + + services.AddHttpContextAccessor(); + services.TryAddScoped(); + services.AddBaGetIdentityUseCases(); + + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddTransient(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + services.AddHttpContextAccessor(); + + // The use cases of the account screens: resolved only after the screen gate let the request in, so they exist only while accounts are enabled. + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + // Emails link to the single-page application's routes when the screens are off (or Frontend:SpaLinks): the sign-in page of the cookie is then the application's. + var frontend = configuration.GetSection(nameof(BaGetOptions.Frontend)).Get() ?? new FrontendOptions(); + var spaLinkBase = frontend.EmailLinkBase; + if (frontend.EmailLinksWouldBeDead && (configuration.GetSection(nameof(BaGetOptions.Email)).Get()?.IsConfigured ?? false)) + { + throw new InvalidOperationException( + "'Frontend:Mvc' is false and email is configured, but account emails have no page to link to: set 'Frontend:SpaPath' (an application BaGet serves), 'Frontend:SpaUrl' (one hosted elsewhere) or 'Frontend:SpaLinks'=true (one a reverse proxy serves under 'Frontend:SpaBasePath')."); + } + + services.PostConfigure(site => site.SpaLinkBase = spaLinkBase); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.AddBaGetAdminUseCases(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddHostedService(); + + // Email is optional. Nothing that needs it is offered while it is unconfigured, and + // Identity only demands a confirmed address when there is a way to send the link. + var email = configuration.GetSection(nameof(BaGetOptions.Email)).Get() + ?? new EmailOptions(); + // Links in emails need a trustworthy address for this server. Without one, email is + // switched off rather than built from the request's Host header. + var linksAvailable = EmailLinkPolicy.CanBuildLinks(site.PublicUrl); + if (email.IsConfigured && !linksAvailable) email.Suppressed = true; + services.PostConfigure(configured => configured.Suppressed = email.Suppressed); + + if (email.IsConfigured) + { + services.TryAddTransient, SmtpEmailSender>(); + services.TryAddTransient(); + } + else + { + services.TryAddTransient, NoOpEmailSender>(); + services.TryAddTransient(); + } + services.Replace(ServiceDescriptor.Transient()); + services.Replace(ServiceDescriptor.Transient()); + + // The context is chosen per database provider at runtime, so Identity's EF stores + // are given whichever one was resolved rather than a context type. + services.TryAddScoped>(provider => + new UserStore( + (DbContext)provider.GetRequiredService())); + + services + .AddIdentityCore(identity => + { + identity.User.RequireUniqueEmail = false; + identity.Lockout.AllowedForNewUsers = true; + identity.SignIn.RequireConfirmedEmail = email.IsConfigured; + }) + .AddSignInManager() + .AddDefaultTokenProviders(); + + // Identity re-checks a session against the database only every 30 minutes by default, + // so the session of a deleted user, or of one whose password was reset, would keep + // acting until then. Browser sessions are few next to API traffic, so every request + // is checked: no principal for a user that no longer exists or whose stamp changed. + services.Configure(validation => validation.ValidationInterval = TimeSpan.Zero); + + // The cookie session is accepted on /api/ui only together with this header (GET /api/ui/antiforgery hands the token out). + services.AddAntiforgery(antiforgery => antiforgery.HeaderName = UiApiCaller.AntiforgeryHeader); + + var authentication = services.AddAuthentication(IdentityConstants.ApplicationScheme); + authentication.AddIdentityCookies(cookies => cookies.ApplicationCookie?.Configure(cookie => + { + if (spaLinkBase != null && !spaLinkBase.StartsWith('/')) + { + // An application hosted elsewhere (an absolute address) cannot be a path: a challenge answers 401 instead of redirecting to a page of this server. + cookie.Events.OnRedirectToLogin = context => { context.Response.StatusCode = 401; return System.Threading.Tasks.Task.CompletedTask; }; + cookie.Events.OnRedirectToAccessDenied = context => { context.Response.StatusCode = 403; return System.Threading.Tasks.Task.CompletedTask; }; + + return; + } + + cookie.LoginPath = spaLinkBase == null ? "/account/login" : spaLinkBase + "/sign-in"; + cookie.LogoutPath = spaLinkBase == null ? "/account/logout" : spaLinkBase + "/sign-in"; + cookie.AccessDeniedPath = spaLinkBase == null ? "/account/login" : spaLinkBase + "/sign-in"; + })); + + // One authentication handler per provider: the legacy block as "oidc" (callback /signin-oidc), each named one under its own id and callback path. + foreach (var provider in providers.All) + { + var configured = provider; + authentication.AddOpenIdConnect(configured.Id, configured.DisplayName, oidc => OpenIdConnectProviderSetup.Configure(oidc, configured)); + } + + return services; + } +} diff --git a/src/BaGet.Identity.Api/Models/Packages/DockerManageForm.cs b/src/BaGet.Identity.Api/Models/Packages/DockerManageForm.cs new file mode 100644 index 000000000..ec1929beb --- /dev/null +++ b/src/BaGet.Identity.Api/Models/Packages/DockerManageForm.cs @@ -0,0 +1,14 @@ +namespace BaGet.Identity.Models.Packages; + +/// The form of the Docker management handlers; every one asks for the caller's password. +public sealed class DockerManageForm +{ + /// The tag to delete (DeleteTag). + public string? Tag { get; set; } + + /// The manifest digest to delete (DeleteManifest). + public string? Digest { get; set; } + + /// The caller's password. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Api/Models/Packages/MavenManageForm.cs b/src/BaGet.Identity.Api/Models/Packages/MavenManageForm.cs new file mode 100644 index 000000000..c4cb3878a --- /dev/null +++ b/src/BaGet.Identity.Api/Models/Packages/MavenManageForm.cs @@ -0,0 +1,20 @@ +namespace BaGet.Identity.Models.Packages; + +/// The form of the Maven management handlers: the chosen version and what the handler needs. +public sealed class MavenManageForm +{ + /// The user or organization (AddOwner, RemoveOwner). + public string? OwnerName { get; set; } + + /// The version whose files are listed, and the one a handler acts on (DeleteFile, DeleteVersion, Cleanup). + public string? Version { get; set; } + + /// The file to delete (DeleteFile). + public string? FileName { get; set; } + + /// How many snapshot builds to keep (Cleanup). + public string? Keep { get; set; } + + /// The caller's password, for the deleting handlers. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Api/Models/Packages/NpmManageDeprecateForm.cs b/src/BaGet.Identity.Api/Models/Packages/NpmManageDeprecateForm.cs new file mode 100644 index 000000000..50cf4b73c --- /dev/null +++ b/src/BaGet.Identity.Api/Models/Packages/NpmManageDeprecateForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Models.Packages; + +/// The form of Deprecate and Undeprecate. +public sealed class NpmManageDeprecateForm +{ + /// The version. + public string? Version { get; set; } + + /// The deprecation message (Deprecate only). + public string? Message { get; set; } +} diff --git a/src/BaGet.Identity.Api/Models/Packages/NpmManageOwnerForm.cs b/src/BaGet.Identity.Api/Models/Packages/NpmManageOwnerForm.cs new file mode 100644 index 000000000..651a2c109 --- /dev/null +++ b/src/BaGet.Identity.Api/Models/Packages/NpmManageOwnerForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Models.Packages; + +/// The form of the npm management handlers that name an owner. +public sealed class NpmManageOwnerForm +{ + /// The user or organization. + public string? OwnerName { get; set; } +} diff --git a/src/BaGet.Identity.Api/Models/Packages/NpmManageTagForm.cs b/src/BaGet.Identity.Api/Models/Packages/NpmManageTagForm.cs new file mode 100644 index 000000000..a826528ce --- /dev/null +++ b/src/BaGet.Identity.Api/Models/Packages/NpmManageTagForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Models.Packages; + +/// The form of SetTag. +public sealed class NpmManageTagForm +{ + /// The dist-tag. + public string? Tag { get; set; } + + /// The version it points at (not used by RemoveTag). + public string? Version { get; set; } +} diff --git a/src/BaGet.Identity.Api/Models/Packages/NpmManageUnpublishForm.cs b/src/BaGet.Identity.Api/Models/Packages/NpmManageUnpublishForm.cs new file mode 100644 index 000000000..3af30d2c0 --- /dev/null +++ b/src/BaGet.Identity.Api/Models/Packages/NpmManageUnpublishForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Models.Packages; + +/// The form of Unpublish (one version) and UnpublishAll (the version is ignored); the password confirms. +public sealed class NpmManageUnpublishForm +{ + /// The version (Unpublish only). + public string? Version { get; set; } + + /// The caller's password. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Api/Models/Packages/ScanArtifactForm.cs b/src/BaGet.Identity.Api/Models/Packages/ScanArtifactForm.cs new file mode 100644 index 000000000..4037c2ea2 --- /dev/null +++ b/src/BaGet.Identity.Api/Models/Packages/ScanArtifactForm.cs @@ -0,0 +1,14 @@ +namespace BaGet.Identity.Models.Packages; + +/// The body of the scan twin's POST: the artifact and version to scan, and where the link back goes. +public sealed class ScanArtifactForm +{ + /// The artifact name (NuGet id, npm name, Maven group:artifact, Docker image). + public string? Name { get; set; } + + /// The version (Docker: the manifest digest). + public string? Version { get; set; } + + /// Where the link back goes (a local address only). + public string? ReturnUrl { get; set; } +} diff --git a/src/BaGet.Identity.Api/README.md b/src/BaGet.Identity.Api/README.md new file mode 100644 index 000000000..f812bb33f --- /dev/null +++ b/src/BaGet.Identity.Api/README.md @@ -0,0 +1,59 @@ +# Extension.BaGet.Identity.Api + +User accounts, package owners, organizations and per-user API keys for +[BaGet Extension](https://pieroviano.github.io/BaGet/), as web APIs: the JSON twins (`/api/ui`) of the account and administration screens, the form models they bind +and `AddBaGetAccounts`. The screens themselves (view controllers and views) are in `Extension.BaGet.Identity.FrontEnd`. + +```powershell +dotnet add package Extension.BaGet.Identity.Api +``` + +## Usage + +```csharp +services.AddBaGetWebApplication(ConfigureBaGetApplication); +services.AddBaGetAccounts(configuration); +``` + +`AddBaGetAccounts` reads `Accounts:Enabled` **while registering**, so the configuration must be complete before it +runs. Disabled, it adds an empty authentication setup and only the global `ApiKey` authenticates. + +| Package | Holds | +|---|---| +| `Extension.BaGet.Identity.Api` (this) | `/api/ui` twins, form models, `AddBaGetAccounts`; no view controller, no view | +| `Extension.BaGet.Api.Base` | What twins and screens share: twin bases, `?handler=` selection, `[UiApi]`, `[RepositoryPage]`, `UiApiSecurityFilter`, `RequestPrincipalResolver` | +| `Extension.BaGet.Identity.FrontEnd` | The screens: view controllers and views | +| `Extension.BaGet.Identity.Application` | Use cases, DTOs, business services (`BaGet.Identity.Application.*`; no MVC reference) | + +`MaintenanceAwareSignInManager` (Application) lets a sign-in complete while the read-only `MaintenanceGate` is closed (it skips the +failed-attempt counter reset; a wrong password is still refused), so administrators can reach the Settings page. + +| Setting | Value | +|---|---| +| `Accounts:Enabled` | Off by default. On: callers authenticate with the global `ApiKey` if set, otherwise their own key | +| `Accounts:AllowRegistration` | Local sign-up from the sign-in page (default `true`) | +| `Accounts:RequireApproval` | A self-registered account (also first external sign-in) cannot sign in until an administrator approves it on `/admin/users` or `/admin/users/{name}` (or `baget account approve`); promoting a user approves it too (default `false`) | +| `Accounts:CreateDefaultAdministrator` | A server with no users creates `Admin` with a default password to change at first sign-in (default `true`) | +| `Accounts:InitialAdministrators` | `;`-separated existing users promoted while there is no administrator | +| `Accounts:OpenIdConnect:Authority`, `ClientId`, `ClientSecret`, `DisplayName` | External OpenID Connect provider (e.g. Entra ID); provider id `oidc` | +| `Accounts:OpenIdConnectProviders::*` | More named OpenID Connect providers (callback `/signin-oidc-`), with extra scopes and parameters, claim names and an opt-in administrator / group mapping ([configuration](https://pieroviano.github.io/BaGet/configuration/#several-providers)); restart-required | +| `Email:Smtp:*` | Optional SMTP for confirmation and password-reset mail (MailKit) | +| `Site:PublicUrl` | Required for email links; without it email is suppressed | + +## Screens + +Every screen is a controller action and a view, in `Extension.BaGet.Identity.FrontEnd` (the package ships **no `@page` file**). URLs and `?handler=` form posts are unchanged from the Razor Pages era; a screen is identified by its controller and default GET action (`asp-controller`/`asp-action`, `Url.Action`, `RedirectToAction`), not by a page name. The old page-model types were removed (breaking for code that referenced them). + +| Folder | Role | +|---|---| +| `Controllers/UI` | The JSON twins (`/api/ui`, see [UI API](https://pieroviano.github.io/BaGet/ui-api/)). Each names its screen with `[UiApi("AdminUsers", "Index")]` (view controller without the suffix + default GET action). Account self-service and package-ownership twins are screen only (403 over HTTP), except the public profile | +| `Models/Packages` | Form models of the package manage screens (npm, Maven, Docker, scan), bound by the twins and the view controllers | +| `Extensions` | `AddBaGetAccounts` | + +## Layout + +One type per file, no nested types, namespace = `BaGet.Identity` + folder (`CodeLayoutTests`). + +## Links + +[Configuration](https://pieroviano.github.io/BaGet/configuration/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Identity.Application/BaGet.Identity.Application.csproj b/src/BaGet.Identity.Application/BaGet.Identity.Application.csproj new file mode 100644 index 000000000..95a9a0785 --- /dev/null +++ b/src/BaGet.Identity.Application/BaGet.Identity.Application.csproj @@ -0,0 +1,37 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's account and administration use cases: business services, the screen result and the screen gate, with no MVC or Razor dependency. + BaGet.Identity.Application + enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Identity.Application/Email/BackgroundEmailQueue.cs b/src/BaGet.Identity.Application/Email/BackgroundEmailQueue.cs new file mode 100644 index 000000000..cb8778359 --- /dev/null +++ b/src/BaGet.Identity.Application/Email/BackgroundEmailQueue.cs @@ -0,0 +1,24 @@ +using System; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace BaGet.Identity.Application.Email; + +/// +/// Sends email off the request path, so that how long a page takes does not depend on +/// whether anything was sent: "forgot password" must not reveal which accounts exist. +/// +public class BackgroundEmailQueue +{ + private readonly Channel> _channel = Channel.CreateBounded>( + new BoundedChannelOptions(1000) { FullMode = BoundedChannelFullMode.DropWrite, SingleReader = true }); + + /// + /// Queue work, run with a scope's services. False when the queue is full. + /// + public bool TryEnqueue(Func work) => _channel.Writer.TryWrite(work); + + internal System.Collections.Generic.IAsyncEnumerable> ReadAllAsync(CancellationToken cancellationToken) + => _channel.Reader.ReadAllAsync(cancellationToken); +} diff --git a/src/BaGet.Identity.Application/Email/BackgroundEmailService.cs b/src/BaGet.Identity.Application/Email/BackgroundEmailService.cs new file mode 100644 index 000000000..438901183 --- /dev/null +++ b/src/BaGet.Identity.Application/Email/BackgroundEmailService.cs @@ -0,0 +1,45 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Email; + +internal sealed class BackgroundEmailService : BackgroundService +{ + private readonly BackgroundEmailQueue _queue; + private readonly IServiceScopeFactory _scopes; + private readonly ILogger _logger; + + public BackgroundEmailService(BackgroundEmailQueue queue, IServiceScopeFactory scopes, ILogger logger) + { + _queue = queue; + _scopes = scopes; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + await foreach (var work in _queue.ReadAllAsync(stoppingToken)) + { + try + { + using var scope = _scopes.CreateScope(); + await work(scope.ServiceProvider); + } + catch (Exception e) + { + _logger.LogError(e, "Could not send a queued email."); + } + } + } + catch (OperationCanceledException) + { + // Shutting down. + } + } +} diff --git a/src/BaGet.Identity.Application/Email/EmailLinkPolicy.cs b/src/BaGet.Identity.Application/Email/EmailLinkPolicy.cs new file mode 100644 index 000000000..70d1259c0 --- /dev/null +++ b/src/BaGet.Identity.Application/Email/EmailLinkPolicy.cs @@ -0,0 +1,56 @@ +using System; +using BaGet.Core; + +namespace BaGet.Identity.Application.Email; + +/// +/// Where the links in account emails may point. A link in a password-reset or confirmation +/// email must never be built from a request's Host header unless that header is +/// known to be one of the server's own: otherwise anyone can request a reset for a victim +/// with a forged Host and have the victim's mail carry a link to the attacker. +/// +public static class EmailLinkPolicy +{ + /// + /// Fails startup on a that is set but is not an + /// absolute http or https URL. + /// + public static void ValidatePublicUrl(string? publicUrl) + { + if (string.IsNullOrWhiteSpace(publicUrl)) return; + + if (!TryParsePublicUrl(publicUrl, out _)) + { + throw new InvalidOperationException( + $"The 'Site:PublicUrl' config is invalid: '{publicUrl}'. Use an absolute http or https URL " + + "such as \"https://packages.example.com\"."); + } + } + + public static bool TryParsePublicUrl(string? publicUrl, out Uri? uri) + { + uri = null; + if (string.IsNullOrWhiteSpace(publicUrl)) return false; + + if (!Uri.TryCreate(publicUrl.Trim(), UriKind.Absolute, out var parsed)) return false; + if (parsed.Scheme != Uri.UriSchemeHttp && parsed.Scheme != Uri.UriSchemeHttps) return false; + if (string.IsNullOrEmpty(parsed.Host)) return false; + + uri = parsed; + + return true; + } + + /// + /// Links can be built only from the configured public URL. The request's host and scheme + /// are attacker-influenced (a forged Host, a spoofed X-Forwarded-Proto) even when + /// "AllowedHosts" restricts the host, so they are never used. + /// + public static bool CanBuildLinks(string? publicUrl) => TryParsePublicUrl(publicUrl, out _); + + public const string UnavailableWarning = + "Email is configured, but \"Site:PublicUrl\" is not set, so links in emails cannot be trusted to point " + + "at this server. Email, and everything that needs it (password recovery, email confirmation, " + + "contact owners), is switched off. Set \"Site:PublicUrl\" (for example " + + "\"https://packages.example.com\") to enable it."; +} diff --git a/src/BaGet.Identity.Application/Email/NoOpEmailSender.cs b/src/BaGet.Identity.Application/Email/NoOpEmailSender.cs new file mode 100644 index 000000000..f711eb953 --- /dev/null +++ b/src/BaGet.Identity.Application/Email/NoOpEmailSender.cs @@ -0,0 +1,33 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Email; + +/// +/// Registered while email is not configured. Nothing that needs email is offered in that +/// case, so reaching this is a bug in the caller; it is logged instead of pretending to send. +/// +internal sealed class NoOpEmailSender : IEmailSender, IEmailMessageSender +{ + private readonly ILogger _logger; + + public NoOpEmailSender(ILogger logger) => _logger = logger; + + public Task SendConfirmationLinkAsync(BaGetUser user, string email, string confirmationLink) => Skip(); + + public Task SendPasswordResetLinkAsync(BaGetUser user, string email, string resetLink) => Skip(); + + public Task SendPasswordResetCodeAsync(BaGetUser user, string email, string resetCode) => Skip(); + + public Task SendAsync(string to, string? replyTo, string? replyToName, string subject, string textBody, CancellationToken cancellationToken) + => Skip(); + + private Task Skip() + { + _logger.LogWarning("An email was requested but \"Email:Smtp\" is not configured; nothing was sent."); + return Task.CompletedTask; + } +} diff --git a/src/BaGet.Identity.Application/Email/PasswordResetLinkSender.cs b/src/BaGet.Identity.Application/Email/PasswordResetLinkSender.cs new file mode 100644 index 000000000..24adf9661 --- /dev/null +++ b/src/BaGet.Identity.Application/Email/PasswordResetLinkSender.cs @@ -0,0 +1,78 @@ +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Email; + +/// +/// Mails a user a password reset link. The one implementation behind "forgot password" and the +/// administrator's "email link": a page builds the link template (see ), +/// then this fills in the user and a fresh token off the request path. +/// +public class PasswordResetLinkSender +{ + /// Where the user's id goes in a link template. + public const string UserIdPlaceholder = "USERIDPLACEHOLDER"; + + /// Where the encoded token goes in a link template. + public const string CodePlaceholder = "CODEPLACEHOLDER"; + + private readonly UserManager _users; + private readonly IEmailSender _sender; + private readonly ILogger _logger; + + /// Creates the sender. + public PasswordResetLinkSender(UserManager users, IEmailSender sender, ILogger logger) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _sender = sender ?? throw new ArgumentNullException(nameof(sender)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// The route values of the reset page's link, with the placeholders to fill in later. + public static object Template => new { userId = UserIdPlaceholder, code = CodePlaceholder }; + + /// + /// Queue the mail to be sent off the request path. False when the queue is full. + /// + /// The request's services. + /// The user to mail. + /// The link built from . + public static bool TryEnqueue(IServiceProvider requestServices, string userId, string template) + => requestServices.GetRequiredService() + .TryEnqueue(services => services.GetRequiredService().SendAsync(userId, template)); + + /// + /// Mail the link. Does nothing for a user that no longer exists or has no address; a failure + /// to send is logged, not thrown. + /// + public async Task SendAsync(string userId, string template, CancellationToken cancellationToken = default) + { + var user = await _users.FindByIdAsync(userId); + if (user == null || string.IsNullOrEmpty(user.Email)) return; + + var token = await _users.GeneratePasswordResetTokenAsync(user); + var link = template + .Replace(UserIdPlaceholder, Uri.EscapeDataString(user.Id)) + .Replace(CodePlaceholder, EncodeToken(token)); + + try + { + await _sender.SendPasswordResetLinkAsync(user, user.Email, link); + } + catch (Exception e) + { + _logger.LogError(e, "Could not send a password reset link."); + } + } + + /// Identity's tokens carry characters that do not survive a URL, so they travel encoded. + internal static string EncodeToken(string token) + => WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token)); +} diff --git a/src/BaGet.Identity.Application/Email/SmtpEmailSender.cs b/src/BaGet.Identity.Application/Email/SmtpEmailSender.cs new file mode 100644 index 000000000..20f71bd38 --- /dev/null +++ b/src/BaGet.Identity.Application/Email/SmtpEmailSender.cs @@ -0,0 +1,131 @@ +using System; +using System.Linq; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using MailKit.Net.Smtp; +using MailKit.Security; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using MimeKit; + +namespace BaGet.Identity.Application.Email; + +/// +/// Sends Identity's emails over SMTP with MailKit. A failure is logged and then +/// rethrown, so a caller can say "could not send" and never reports success. +/// +internal sealed class SmtpEmailSender : IEmailSender, IEmailMessageSender +{ + private readonly IOptions _options; + private readonly ILogger _logger; + + public SmtpEmailSender(IOptions options, ILogger logger) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public Task SendConfirmationLinkAsync(BaGetUser user, string email, string confirmationLink) + => SendAsync(email, "Confirm your email", LinkBody("Confirm your email address:", confirmationLink)); + + public Task SendPasswordResetLinkAsync(BaGetUser user, string email, string resetLink) + => SendAsync(email, "Reset your password", LinkBody("Reset your password:", resetLink)); + + public Task SendPasswordResetCodeAsync(BaGetUser user, string email, string resetCode) + => SendAsync(email, "Reset your password", $"

Your password reset code is {WebUtility.HtmlEncode(resetCode)}.

"); + + /// + /// A user's message as plain text. The subject is fixed text chosen by the caller, control + /// characters are dropped from it and from the name, and addresses are parsed and encoded + /// by MimeKit, which keeps line breaks out of headers. + /// + public Task SendAsync( + string to, + string? replyTo, + string? replyToName, + string subject, + string textBody, + CancellationToken cancellationToken) + => SendAsync(BuildContactMessage(to, replyTo, replyToName, subject, textBody), subject, cancellationToken); + + internal MimeMessage BuildContactMessage(string to, string? replyTo, string? replyToName, string? subject, string textBody) + { + var message = new MimeMessage(); + #pragma warning disable CS8604 + message.From.Add(MailboxAddress.Parse(_options.Value.Smtp.From)); + #pragma warning restore CS8604 + message.To.Add(MailboxAddress.Parse(to)); + if (!string.IsNullOrEmpty(replyTo)) + { + message.ReplyTo.Add(new MailboxAddress(StripControl(replyToName), replyTo)); + } + + #pragma warning disable CS8601 + message.Subject = StripControl(subject); + #pragma warning restore CS8601 + message.Body = new TextPart("plain") { Text = textBody }; + + return message; + } + + private static string? StripControl(string? value) + => value == null ? null : new string(value.Where(c => !char.IsControl(c)).ToArray()); + + internal static string LinkBody(string text, string link) + { + var encoded = WebUtility.HtmlEncode(link); + + return $"

{WebUtility.HtmlEncode(text)}

{encoded}

"; + } + + internal MimeMessage BuildMessage(string to, string subject, string htmlBody) + { + var message = new MimeMessage(); + #pragma warning disable CS8604 + message.From.Add(MailboxAddress.Parse(_options.Value.Smtp.From)); + #pragma warning restore CS8604 + message.To.Add(MailboxAddress.Parse(to)); + message.Subject = subject; + message.Body = new BodyBuilder { HtmlBody = htmlBody }.ToMessageBody(); + + return message; + } + + private Task SendAsync(string to, string subject, string htmlBody) + => SendAsync(BuildMessage(to, subject, htmlBody), subject, CancellationToken.None); + + private async Task SendAsync(MimeMessage message, string subject, CancellationToken cancellationToken) + { + var smtp = _options.Value.Smtp; + + try + { + + using var client = new SmtpClient(); + var security = !smtp.EnableSsl ? SecureSocketOptions.None + : smtp.Port == 465 ? SecureSocketOptions.SslOnConnect + : SecureSocketOptions.StartTls; + + #pragma warning disable CS8604 + await client.ConnectAsync(smtp.Host, smtp.Port, security, cancellationToken); + #pragma warning restore CS8604 + if (!string.IsNullOrEmpty(smtp.UserName)) + { + #pragma warning disable CS8604 + await client.AuthenticateAsync(smtp.UserName, smtp.Password, cancellationToken); + #pragma warning restore CS8604 + } + + await client.SendAsync(message, cancellationToken); + await client.DisconnectAsync(quit: true, cancellationToken); + } + catch (Exception e) + { + _logger.LogError(e, "Could not send the email \"{Subject}\" through {Host}:{Port}.", subject, smtp.Host, smtp.Port); + throw; + } + } +} diff --git a/src/BaGet.Identity.Application/Extensions/AdminUseCasesServiceCollectionExtensions.cs b/src/BaGet.Identity.Application/Extensions/AdminUseCasesServiceCollectionExtensions.cs new file mode 100644 index 000000000..ce63fb9ca --- /dev/null +++ b/src/BaGet.Identity.Application/Extensions/AdminUseCasesServiceCollectionExtensions.cs @@ -0,0 +1,47 @@ +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using BaGet.Identity.Application.UseCases.Access; +using BaGet.Identity.Application.UseCases.Admin; +using BaGet.Identity.Application.UseCases.Packages; +using BaGet.Identity.Application.UseCases.Policies; + +namespace BaGet.Identity.Application.Extensions; + +/// Registration of the use cases of the account and administration screens. +public static class AdminUseCasesServiceCollectionExtensions +{ + /// + /// Registers and the use cases of the administration screens. Called by AddBaGetAccounts after its + /// Accounts:Enabled check: the use cases depend on the account services, which exist only while accounts are enabled, so a JSON twin + /// resolves its use case inside the action (after the screen gate), never in its constructor. + /// + public static IServiceCollection AddBaGetAdminUseCases(this IServiceCollection services) + { + services.AddHttpContextAccessor(); + services.TryAddScoped(); + + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + return services; + } +} diff --git a/src/BaGet.Identity.Application/Extensions/IdentityApplicationServiceCollectionExtensions.cs b/src/BaGet.Identity.Application/Extensions/IdentityApplicationServiceCollectionExtensions.cs new file mode 100644 index 000000000..737ed1fe5 --- /dev/null +++ b/src/BaGet.Identity.Application/Extensions/IdentityApplicationServiceCollectionExtensions.cs @@ -0,0 +1,45 @@ +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Services.Accounts; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using BaGet.Identity.Application.UseCases.Account; +using BaGet.Identity.Application.UseCases.Packages; + +namespace BaGet.Identity.Application.Extensions; + +/// Registration of what the Application project provides whether or not accounts are enabled. +public static class IdentityApplicationServiceCollectionExtensions +{ + /// + /// Registers the screen gate. Called by AddBaGetAccounts (which stays the entry point of a host); the account services themselves are + /// registered there only while accounts are enabled. + /// + public static IServiceCollection AddBaGetIdentityApplication(this IServiceCollection services) + { + services.TryAddScoped(); + + return services; + } + + /// + /// Registers the use cases of the account and administration screens that exist only while accounts are enabled (they need the user store). + /// Called by AddBaGetAccounts after its Enabled check, together with the host's . + /// + public static IServiceCollection AddBaGetIdentityUseCases(this IServiceCollection services) + { + services.TryAddSingleton(OpenIdConnectProviderSet.Empty); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + return services; + } +} diff --git a/src/BaGet.Identity.Application/Links/AccountLinks.cs b/src/BaGet.Identity.Application/Links/AccountLinks.cs new file mode 100644 index 000000000..f1aa155a4 --- /dev/null +++ b/src/BaGet.Identity.Application/Links/AccountLinks.cs @@ -0,0 +1,91 @@ +using System; +using System.Linq; +using BaGet.Core; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Email; +using BaGet.Identity.Application.Security; + +namespace BaGet.Identity.Application.Links; + +/// +/// The absolute links the account emails carry. Built only from Site:PublicUrl, never from the request's host or scheme (see +/// ), so a use case that has no request URL helper still writes the same links the screens always wrote. +/// +public static class AccountLinks +{ + /// The address of the confirmation page (/account/confirmemail). + public const string ConfirmEmailPath = "/account/confirmemail"; + + /// The address of the new-password page (/account/resetpassword). + public const string ResetPasswordPath = "/account/resetpassword"; + + /// + /// The link to (an application-relative path starting with /) with the query values in order. Throws + /// when the server has no valid public URL: nothing is mailed then. + /// + public static string Build(IOptions site, string path, params (string Name, string? Value)[] query) + { + if (site == null) throw new ArgumentNullException(nameof(site)); + + path = SpaPath(site.Value.SpaLinkBase, path); + + // An application hosted elsewhere is linked by its own absolute address; everything else lives under the site's public URL. + var absolute = path.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || path.StartsWith("https://", StringComparison.OrdinalIgnoreCase); + Uri? root = null; + if (!absolute && !EmailLinkPolicy.TryParsePublicUrl(site.Value.PublicUrl, out root)) + { + throw new InvalidOperationException(EmailLinkPolicy.UnavailableWarning); + } + + var queryString = string.Join( + "&", + query.Where(q => q.Value != null).Select(q => Uri.EscapeDataString(q.Name) + "=" + Uri.EscapeDataString(q.Value!))); + + return (absolute ? string.Empty : root?.GetLeftPart(UriPartial.Path).TrimEnd('/')) + path + (queryString.Length == 0 ? string.Empty : "?" + queryString); + } + + /// The route of the single-page application that stands for (Frontend:SpaLinks); the screen's path when it serves emails. + public static string SpaPath(string? spaLinkBase, string path) + { + if (spaLinkBase == null) return path; + + var route = path switch + { + ConfirmEmailPath => "confirm-email", + ResetPasswordPath => "reset-password", + "/account/login" => "sign-in", + _ => null, + }; + + return route == null ? path : spaLinkBase.TrimEnd('/') + "/" + route; + } + + /// + /// The absolute link to a screen for an email when emails link to the single-page application: its route under the base path with the screen's route values + /// as the query. Null when the screen has no route there (the caller builds the screen's own link). + /// + public static string? ForScreen(IOptions site, Screens.ScreenRef screen, object values) + { + if (site.Value.SpaLinkBase == null) return null; + + var path = screen.Equals(Screens.ScreenCatalog.AccountResetPassword) ? ResetPasswordPath + : screen.Equals(Screens.ScreenCatalog.AccountConfirmEmail) ? ConfirmEmailPath + : screen.Equals(Screens.ScreenCatalog.AccountLogin) ? "/account/login" + : null; + if (path == null) return null; + + var query = values.GetType().GetProperties() + .Select(p => (Name: p.Name, Value: p.GetValue(values)?.ToString())) + .ToArray(); + + return Build(site, path, query); + } + + /// The confirmation link of a new account's address, or (with ) of a change of address. + public static string ConfirmEmail(IOptions site, string userId, string token, string? email = null) + => Build(site, ConfirmEmailPath, ("userId", userId), ("email", email), ("code", AccountConfirmation.EncodeToken(token))); + + /// The template of the password-reset link: the user id and the code are filled in later (). + public static string ResetPasswordTemplate(IOptions site) + => Build(site, ResetPasswordPath, ("userId", PasswordResetLinkSender.UserIdPlaceholder), ("code", PasswordResetLinkSender.CodePlaceholder)); +} diff --git a/src/BaGet.Identity.Application/Links/RepositoryPageLinks.cs b/src/BaGet.Identity.Application/Links/RepositoryPageLinks.cs new file mode 100644 index 000000000..31338b579 --- /dev/null +++ b/src/BaGet.Identity.Application/Links/RepositoryPageLinks.cs @@ -0,0 +1,56 @@ +using System; +using System.Linq; +using BaGet.Core; + +namespace BaGet.Identity.Application.Links; + +/// +/// App-relative (~/) addresses of a package's pages in a given repository. The one place that decides +/// where a package page of a repository lives, so that pages that list packages of several repositories (the +/// account blockers, the administrator lists) link to the right one and a change of page routing is a change here. +/// +/// +/// The default repository's pages are at the root; any other repository's are under r/{name}/, like its +/// protocol routes. Pass the result through Url.Content to honour the path base. +/// +public static class RepositoryPageLinks +{ + /// The package page of . + /// The repository; null or the default's name for the root pages. + /// The package ID. + /// The repository's format: an npm package has its own pages (npm-packages/{name}), a Maven artifact too (maven-artifacts/{group}/{artifact}). + public static string Package(string? repositoryName, string? id, RepositoryFormat format = RepositoryFormat.NuGet) + => format == RepositoryFormat.Npm + ? Prefix(repositoryName) + "npm-packages/" + NpmPath(id) + : format == RepositoryFormat.Maven + ? Prefix(repositoryName) + "maven-artifacts/" + MavenPath(id) + : format == RepositoryFormat.Docker + ? Prefix(repositoryName) + "docker-images/" + NpmPath(id) + : Prefix(repositoryName) + "packages/" + Uri.EscapeDataString(id ?? string.Empty); + + /// The management page of . + /// The repository; null or the default's name for the root pages. + /// The package ID. + /// The repository's format. + public static string Manage(string? repositoryName, string? id, RepositoryFormat format = RepositoryFormat.NuGet) + => format == RepositoryFormat.Npm + ? Prefix(repositoryName) + "npm-manage/" + NpmPath(id) + : format == RepositoryFormat.Maven + ? Prefix(repositoryName) + "maven-manage/" + MavenPath(id) + : format == RepositoryFormat.Docker + ? Prefix(repositoryName) + "docker-manage/" + NpmPath(id) + : Package(repositoryName, id) + "/manage"; + + // A scoped name keeps its slash in the address (the pages take the rest of the path). + private static string NpmPath(string? id) + => string.Join("/", (id ?? string.Empty).Split('/').Select(Uri.EscapeDataString)); + + // A Maven "group:artifact" is two path segments (group, artifact) in the address. + private static string MavenPath(string? id) + => string.Join("/", (id ?? string.Empty).Split(':').Select(Uri.EscapeDataString)); + + private static string Prefix(string? repositoryName) + => string.IsNullOrEmpty(repositoryName) || repositoryName == Repository.DefaultName + ? "~/" + : "~/r/" + Uri.EscapeDataString(repositoryName) + "/"; +} diff --git a/src/BaGet.Identity.Application/Models/Access/AccessViewModel.cs b/src/BaGet.Identity.Application/Models/Access/AccessViewModel.cs new file mode 100644 index 000000000..7fbe59058 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/AccessViewModel.cs @@ -0,0 +1,20 @@ +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Access; + +/// +/// What every access-control screen (groups, permission targets, projects) shows besides its own data: the outcome of the last +/// action, why it was refused, whether the signed-in user is a server administrator (rather than only a project administrator) +/// and what the password confirmation partial needs. +/// +public abstract class AccessViewModel : ConfirmationModel, IFlashModel +{ + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } + + /// Whether the signed-in user is a server administrator. + public bool IsServerAdministrator { get; internal set; } +} diff --git a/src/BaGet.Identity.Application/Models/Access/AuditQuery.cs b/src/BaGet.Identity.Application/Models/Access/AuditQuery.cs new file mode 100644 index 000000000..cfdf36968 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/AuditQuery.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Access; + +/// The audit log's filter. +/// The user name that made the change. +/// Part of what the change was done to. +/// First day, yyyy-MM-dd. +/// Last day, yyyy-MM-dd. +public sealed record AuditQuery(string? Actor, string? Subject, string? From, string? To); diff --git a/src/BaGet.Identity.Application/Models/Access/AuditViewModel.cs b/src/BaGet.Identity.Application/Models/Access/AuditViewModel.cs new file mode 100644 index 000000000..e31ae6db2 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/AuditViewModel.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// What the access audit screen (/admin/audit) shows: the filter and the matching entries. +public sealed class AuditViewModel +{ + /// The user name that made the change. + public string? ActorFilter { get; set; } + + /// Part of what the change was done to (a group, target, project or repository name). + public string? Subject { get; set; } + + /// First day, yyyy-MM-dd. + public string? From { get; set; } + + /// Last day, yyyy-MM-dd. + public string? To { get; set; } + + /// The matching entries. + public IReadOnlyList Entries { get; internal set; } = Array.Empty(); + + /// Why the filter was not applied, if a date could not be read. + public string? FilterError { get; internal set; } +} diff --git a/src/BaGet.Identity.Application/Models/Access/GrantForm.cs b/src/BaGet.Identity.Application/Models/Access/GrantForm.cs new file mode 100644 index 000000000..cbf71ab64 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/GrantForm.cs @@ -0,0 +1,11 @@ +using System.Text.Json.Serialization; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// Giving a principal the ticked actions through a permission target, replacing an earlier grant to it. +/// User, group or organization. +/// The principal's name. +/// The ticked names (Read, Annotate, Deploy, Delete, Manage); none removes the grant. +/// The administrator's password, asked again. +public sealed record GrantForm([property: JsonConverter(typeof(JsonStringEnumConverter))] PrincipalType? PrincipalType, string? PrincipalName, string[]? Actions, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Access/GroupCreation.cs b/src/BaGet.Identity.Application/Models/Access/GroupCreation.cs new file mode 100644 index 000000000..4aa261582 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/GroupCreation.cs @@ -0,0 +1,10 @@ +namespace BaGet.Identity.Application.Models.Access; + +// Enum members read their names (like the answers write them): a body says "Group", not 2. +// The bodies of the access-control screens' writes (groups, permission targets, projects). A page posts them as form fields (the view controllers bind the +// same names and build these), the JSON API takes them as the request body; the use cases never see how they arrived. + +/// A new group. +/// The group's name. +/// What the group is for, or null. +public sealed record GroupCreation(string? Name, string? Description); diff --git a/src/BaGet.Identity.Application/Models/Access/GroupDetailViewModel.cs b/src/BaGet.Identity.Application/Models/Access/GroupDetailViewModel.cs new file mode 100644 index 000000000..7d07249f2 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/GroupDetailViewModel.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// What the group screen (/admin/groups/{name}) shows: the group, its members and the member search. +public sealed class GroupDetailViewModel : AccessViewModel +{ + /// The group name (route). + public string? Name { get; set; } + + /// User-name search for the member picker (contains). + public string? Q { get; set; } + + /// The group. + public GroupDetails? Group { get; internal set; } + + /// The users found by , not yet members. + public IReadOnlyList Found { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Access/GroupMemberChange.cs b/src/BaGet.Identity.Application/Models/Access/GroupMemberChange.cs new file mode 100644 index 000000000..26bab3432 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/GroupMemberChange.cs @@ -0,0 +1,8 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// Adding a user to a group or removing them. +/// The user's id (). +/// The administrator's password, asked again. +public sealed record GroupMemberChange(string? UserId, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Access/GroupRename.cs b/src/BaGet.Identity.Application/Models/Access/GroupRename.cs new file mode 100644 index 000000000..8527646a2 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/GroupRename.cs @@ -0,0 +1,5 @@ +namespace BaGet.Identity.Application.Models.Access; + +/// Renaming a group. +/// The new name. +public sealed record GroupRename(string? NewName); diff --git a/src/BaGet.Identity.Application/Models/Access/GroupsViewModel.cs b/src/BaGet.Identity.Application/Models/Access/GroupsViewModel.cs new file mode 100644 index 000000000..d44d6b506 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/GroupsViewModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// What the groups screen (/admin/groups) shows: the groups and the new-group form. +public sealed class GroupsViewModel : AccessViewModel +{ + /// The new group name. + public string? Name { get; set; } + + /// The new group description. + public string? Description { get; set; } + + /// The groups. + public IReadOnlyList Groups { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Access/PermissionDetailViewModel.cs b/src/BaGet.Identity.Application/Models/Access/PermissionDetailViewModel.cs new file mode 100644 index 000000000..7d7b0b94d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/PermissionDetailViewModel.cs @@ -0,0 +1,43 @@ +using System.Text.Json.Serialization; +using BaGet.Core; +using BaGet.Identity.Application.Models.Policies; + +namespace BaGet.Identity.Application.Models.Access; + +/// What the permission target screen (/admin/permissions/{name}) shows: the patterns, the preview and the grants. +public sealed class PermissionDetailViewModel : AccessViewModel +{ + /// The target name (route). + public string? Name { get; set; } + + /// Repository names or globs, one per line. + public string? RepositoryPatterns { get; set; } + + /// Package ID globs the target applies to, one per line. + public string? IncludePatterns { get; set; } + + /// Package ID globs the target leaves out, one per line. + public string? ExcludePatterns { get; set; } + + /// A package ID to test the patterns with. + public string? TestPackage { get; set; } + + /// The kind of principal in the grant form. + public PrincipalType PrincipalType { get; set; } = PrincipalType.Group; + + /// The user, group or organization name in the grant form. + public string? PrincipalName { get; set; } + + /// The target. + public TargetDetails? Target { get; internal set; } + + /// What the patterns select. + public PatternPreview? Preview { get; internal set; } + + /// The actions ticked in the grant form. + public AccessAction FormActions { get; internal set; } + + /// The model of the pattern fields partial. + [JsonIgnore] + public PatternFieldsView Fields => new(RepositoryPatterns, IncludePatterns, ExcludePatterns, TestPackage, Preview); +} diff --git a/src/BaGet.Identity.Application/Models/Access/PermissionTargetForm.cs b/src/BaGet.Identity.Application/Models/Access/PermissionTargetForm.cs new file mode 100644 index 000000000..ef17dbe1f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/PermissionTargetForm.cs @@ -0,0 +1,25 @@ +using System.Text.Json.Serialization; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// The fields of the permission-target form (new target, or the patterns of an existing one) and its test box. +/// The new target's name (ignored for an existing target: the route names it). +/// Repository names or * globs, one per line. +/// Package ID globs the target applies to, one per line; none means all. +/// Package ID globs the target leaves out, one per line. +/// For a new target: the project that administers it, or null. +/// A package ID to test the patterns with. +/// For an existing target: the principal kind in the grant form (kept across a preview). +/// For an existing target: the principal name in the grant form (kept across a preview). +/// The administrator's password (saving the patterns of an existing target). +public sealed record PermissionTargetForm( + string? Name = null, + string? RepositoryPatterns = null, + string? IncludePatterns = null, + string? ExcludePatterns = null, + string? Project = null, + string? TestPackage = null, + [property: JsonConverter(typeof(JsonStringEnumConverter))] PrincipalType? PrincipalType = null, + string? PrincipalName = null, + string? Password = null); diff --git a/src/BaGet.Identity.Application/Models/Access/PermissionsViewModel.cs b/src/BaGet.Identity.Application/Models/Access/PermissionsViewModel.cs new file mode 100644 index 000000000..fed961d1a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/PermissionsViewModel.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; +using BaGet.Core; +using BaGet.Identity.Application.Models.Policies; + +namespace BaGet.Identity.Application.Models.Access; + +/// What the permission targets screen (/admin/permissions) shows: the targets and the new-target form. +public sealed class PermissionsViewModel : AccessViewModel +{ + /// The new target name. + public string? Name { get; set; } + + /// Repository names or * globs, one per line. + public string? RepositoryPatterns { get; set; } + + /// Package ID globs the target applies to, one per line; none means all. + public string? IncludePatterns { get; set; } + + /// Package ID globs the target leaves out, one per line. + public string? ExcludePatterns { get; set; } + + /// The project that administers the target, if any. + public string? Project { get; set; } + + /// A package ID to test the patterns with. + public string? TestPackage { get; set; } + + /// The targets. + public IReadOnlyList Targets { get; internal set; } = Array.Empty(); + + /// The projects a target can belong to. + public IReadOnlyList Projects { get; internal set; } = Array.Empty(); + + /// The preview of the form patterns. + public PatternPreview? Preview { get; internal set; } + + /// The model of the pattern fields partial. + [JsonIgnore] + public PatternFieldsView Fields => new(RepositoryPatterns, IncludePatterns, ExcludePatterns, TestPackage, Preview); +} diff --git a/src/BaGet.Identity.Application/Models/Access/PrincipalRemoval.cs b/src/BaGet.Identity.Application/Models/Access/PrincipalRemoval.cs new file mode 100644 index 000000000..282232c93 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/PrincipalRemoval.cs @@ -0,0 +1,10 @@ +using System.Text.Json.Serialization; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// Removing a principal's grant or project role. +/// User, group or organization. +/// The principal's id. +/// The administrator's password, asked again. +public sealed record PrincipalRemoval([property: JsonConverter(typeof(JsonStringEnumConverter))] PrincipalType Type, string? PrincipalId, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Access/ProjectCreation.cs b/src/BaGet.Identity.Application/Models/Access/ProjectCreation.cs new file mode 100644 index 000000000..7770b4bab --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/ProjectCreation.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Access; + +/// A new project. +/// The project's name. +/// A name to show, or null. +public sealed record ProjectCreation(string? Name, string? DisplayName); diff --git a/src/BaGet.Identity.Application/Models/Access/ProjectDetailViewModel.cs b/src/BaGet.Identity.Application/Models/Access/ProjectDetailViewModel.cs new file mode 100644 index 000000000..0b1131cdb --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/ProjectDetailViewModel.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; +using BaGet.Core; +using BaGet.Identity.Application.Models.Policies; + +namespace BaGet.Identity.Application.Models.Access; + +/// What the project screen (/admin/projects/{name}) shows: repositories, members and the project targets. +public sealed class ProjectDetailViewModel : AccessViewModel +{ + /// The project name (route). + public string? Name { get; set; } + + /// The project. + public ProjectDetails? Project { get; internal set; } + + /// The NuGet repositories not yet in this project, for the assignment picker. + public IReadOnlyList Assignable { get; internal set; } = Array.Empty(); + + /// The new target name. + public string? TargetName { get; set; } + + /// Repository globs of the new target, one per line (they only ever reach the project repositories). + public string? RepositoryPatterns { get; set; } + + /// Include globs of the new target. + public string? IncludePatterns { get; set; } + + /// Exclude globs of the new target. + public string? ExcludePatterns { get; set; } + + /// A package ID to test the patterns with. + public string? TestPackage { get; set; } + + /// What the new target patterns select. + public PatternPreview? Preview { get; internal set; } + + /// The model of the pattern fields partial. + [JsonIgnore] + public PatternFieldsView Fields => new(RepositoryPatterns, IncludePatterns, ExcludePatterns, TestPackage, Preview); +} diff --git a/src/BaGet.Identity.Application/Models/Access/ProjectMemberForm.cs b/src/BaGet.Identity.Application/Models/Access/ProjectMemberForm.cs new file mode 100644 index 000000000..9b77ca709 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/ProjectMemberForm.cs @@ -0,0 +1,11 @@ +using System.Text.Json.Serialization; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// Giving a user or group a role in a project. +/// User or group. +/// The principal's name. +/// The role. +/// The administrator's password, asked again. +public sealed record ProjectMemberForm([property: JsonConverter(typeof(JsonStringEnumConverter))] PrincipalType Type, string? PrincipalName, [property: JsonConverter(typeof(JsonStringEnumConverter))] ProjectRole Role, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Access/ProjectRepositoryForm.cs b/src/BaGet.Identity.Application/Models/Access/ProjectRepositoryForm.cs new file mode 100644 index 000000000..364f9a00e --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/ProjectRepositoryForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Access; + +/// Putting a repository in a project or taking it out. +/// The repository's name. +/// The administrator's password, asked again. +public sealed record ProjectRepositoryForm(string? Repository, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Access/ProjectTargetForm.cs b/src/BaGet.Identity.Application/Models/Access/ProjectTargetForm.cs new file mode 100644 index 000000000..be41b4c8f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/ProjectTargetForm.cs @@ -0,0 +1,9 @@ +namespace BaGet.Identity.Application.Models.Access; + +/// The fields of a project's new permission target and its test box. +/// The new target's name. +/// Repository globs, one per line (they only ever reach the project's repositories). +/// Package ID globs the target applies to, one per line. +/// Package ID globs the target leaves out, one per line. +/// A package ID to test the patterns with. +public sealed record ProjectTargetForm(string? TargetName, string? RepositoryPatterns, string? IncludePatterns, string? ExcludePatterns, string? TestPackage); diff --git a/src/BaGet.Identity.Application/Models/Access/ProjectsViewModel.cs b/src/BaGet.Identity.Application/Models/Access/ProjectsViewModel.cs new file mode 100644 index 000000000..db69f6865 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Access/ProjectsViewModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Access; + +/// What the projects screen (/admin/projects) shows: the projects the user may open and the new-project form. +public sealed class ProjectsViewModel : AccessViewModel +{ + /// The new project name. + public string? Name { get; set; } + + /// The new project display name. + public string? DisplayName { get; set; } + + /// The projects the signed-in user may open. + public IReadOnlyList Projects { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Account/AccountAccessViewModel.cs b/src/BaGet.Identity.Application/Models/Account/AccountAccessViewModel.cs new file mode 100644 index 000000000..725f1f98d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/AccountAccessViewModel.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using BaGet.Identity.Application.Models.Repositories; + +namespace BaGet.Identity.Application.Models.Account; + +/// The "My access" screen: the signed-in user's own effective permissions. +public sealed class AccountAccessViewModel +{ + /// A package ID to evaluate the grants for; empty means the repository as a whole. + public string? Package { get; set; } + + /// The repositories where the user holds some action. + public IReadOnlyList Rows { get; set; } = Array.Empty(); + + /// The projects the user administers. + public IReadOnlyList AdministeredProjects { get; set; } = Array.Empty(); + + /// Whether the configured database has an access model at all. + public bool ModelAvailable { get; set; } = true; +} diff --git a/src/BaGet.Identity.Application/Models/Account/AccountApiKey.cs b/src/BaGet.Identity.Application/Models/Account/AccountApiKey.cs new file mode 100644 index 000000000..2acedfff2 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/AccountApiKey.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Account; + +/// One API key as the screen lists it: never the key itself or its hash (only the creation response shows a new key, once). +public sealed class AccountApiKey +{ + /// The key's id (the number the revoke button posts). + public int Key { get; set; } + + /// What the key is for. + public string? Description { get; set; } + + /// What the key may do. + public IReadOnlyList Scopes { get; set; } = Array.Empty(); + + /// The package IDs the key applies to. + public string? PackageGlobPattern { get; set; } + + /// When it was created. + public DateTime Created { get; set; } + + /// When it expires; null = never. + public DateTime? Expires { get; set; } + + /// The listing row of . + public static AccountApiKey From(ApiKey key) => new() + { + Key = key.Key, + Description = key.Description, + Scopes = key.Scopes ?? Array.Empty(), + PackageGlobPattern = key.PackageGlobPattern, + Created = key.Created, + Expires = key.Expires, + }; +} diff --git a/src/BaGet.Identity.Application/Models/Account/ApiKeyForm.cs b/src/BaGet.Identity.Application/Models/Account/ApiKeyForm.cs new file mode 100644 index 000000000..e13009764 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ApiKeyForm.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the new-key form posts (and the body of POST /api/ui/account/apikeys). +public class ApiKeyForm +{ + /// The password, asked again. Needed over /api/ui (a session token or the cookie with an antiforgery header); the screen's form does not post it. + public string? Password { get; set; } + + /// What the key is for. + [StringLength(AbstractContext.MaxApiKeyDescriptionLength)] + public string? Description { get; set; } + + /// The scopes of the new key. + public List Scopes { get; set; } = new(); + + /// The package IDs the key applies to. + [Display(Name = "Package glob pattern")] + public string PackageGlobPattern { get; set; } = "*"; + + /// Days until the key expires; none = never. + [Range(1, 3650)] + [Display(Name = "Expires after (days)")] + public int? ExpiresInDays { get; set; } = 365; + + /// The keys of the repositories the new key is limited to; none (the default) means every repository. + public List RepositoryKeys { get; set; } = new(); +} diff --git a/src/BaGet.Identity.Application/Models/Account/ApiKeysViewModel.cs b/src/BaGet.Identity.Application/Models/Account/ApiKeysViewModel.cs new file mode 100644 index 000000000..4c7adc44d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ApiKeysViewModel.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.Models.Account; + +/// +/// The API keys screen: the new-key form's fields it repeats and the user's keys. A request binds , never this type, +/// so the outputs cannot be set from outside. +/// +public sealed class ApiKeysViewModel : ApiKeyForm +{ + /// + /// The repositories offered in the picker: those the user can read. Empty (picker hidden) where the server holds + /// the default repository only. + /// + public IReadOnlyList Repositories { get; set; } = Array.Empty(); + + /// The user's keys. + public IReadOnlyList Keys { get; set; } = Array.Empty(); + + /// The names of the repositories each key (by key id) is limited to. + public IReadOnlyDictionary> KeyRepositories { get; set; } = new Dictionary>(); + + /// The key just created. Shown once: only its hash is kept. + public string? CreatedKey { get; set; } + + /// + /// The scopes the new-key form offers: the package scopes, plus (the REST API under + /// /api/v1) for an administrator. + /// + public IReadOnlyList AllScopes { get; set; } = ApiKeyScopes.All; + + /// Where the key may be used: the repositories it is limited to, or "all repositories". + public string DescribeRepositories(AccountApiKey key) + => ApiKeyService.DescribeRepositories(KeyRepositories.GetValueOrDefault(key.Key)); + + /// What the key can do and on which package IDs. + public static string Describe(AccountApiKey key) + => string.Join(", ", key.Scopes) + " on " + key.PackageGlobPattern; +} diff --git a/src/BaGet.Identity.Application/Models/Account/ConfirmEmailViewModel.cs b/src/BaGet.Identity.Application/Models/Account/ConfirmEmailViewModel.cs new file mode 100644 index 000000000..896ef04ed --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ConfirmEmailViewModel.cs @@ -0,0 +1,14 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// The result of following the link of a confirmation email. +public sealed class ConfirmEmailViewModel +{ + /// Whether the link was valid. + public bool Succeeded { get; set; } + + /// Whether the link changed the address of an existing account. + public bool EmailChanged { get; set; } + + /// Whether the account still waits for an administrator (Accounts:RequireApproval) after the confirmation. + public bool PendingApproval { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/ExternalLoginStatus.cs b/src/BaGet.Identity.Application/Models/Account/ExternalLoginStatus.cs new file mode 100644 index 000000000..21671d63a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ExternalLoginStatus.cs @@ -0,0 +1,7 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// A configured external provider as the account settings list it for one user. +/// The provider id. +/// The provider's name. +/// Whether the account has a linked login at this provider. +public sealed record ExternalLoginStatus(string Id, string DisplayName, bool Linked); diff --git a/src/BaGet.Identity.Application/Models/Account/ExternalProviderInfo.cs b/src/BaGet.Identity.Application/Models/Account/ExternalProviderInfo.cs new file mode 100644 index 000000000..7f4003d30 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ExternalProviderInfo.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// An external sign-in provider as a screen offers it (one button per provider). +/// The provider id: the value a form or /api/ui/session/external/{provider} names it by. +/// The name on the button. +public sealed record ExternalProviderInfo(string Id, string DisplayName); diff --git a/src/BaGet.Identity.Application/Models/Account/ForgotPasswordForm.cs b/src/BaGet.Identity.Application/Models/Account/ForgotPasswordForm.cs new file mode 100644 index 000000000..2c50792a8 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ForgotPasswordForm.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the "forgot password" form posts. +public class ForgotPasswordForm +{ + /// The user name or email address. + [Required] + [Display(Name = "User name or email")] + public string? Identifier { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/ForgotPasswordViewModel.cs b/src/BaGet.Identity.Application/Models/Account/ForgotPasswordViewModel.cs new file mode 100644 index 000000000..77f6a9239 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ForgotPasswordViewModel.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// The "forgot password" screen. A request binds , never this type. +public sealed class ForgotPasswordViewModel : ForgotPasswordForm +{ + /// Whether the request was answered (always the same answer, see the use case). + public bool Sent { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/LoginForm.cs b/src/BaGet.Identity.Application/Models/Account/LoginForm.cs new file mode 100644 index 000000000..81e639dc5 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/LoginForm.cs @@ -0,0 +1,24 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the sign-in form posts (and the body of POST /api/ui/account/login). +public class LoginForm +{ + /// The user name. + [Required] + [Display(Name = "User name")] + public string? UserName { get; set; } + + /// The password. Never echoed: a screen's model leaves it empty. + [Required] + [DataType(DataType.Password)] + public string? Password { get; set; } + + /// Whether the session outlives the browser. + [Display(Name = "Remember me")] + public bool RememberMe { get; set; } + + /// Where to go after signing in; only a local URL is followed. + public string? ReturnUrl { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/LoginViewModel.cs b/src/BaGet.Identity.Application/Models/Account/LoginViewModel.cs new file mode 100644 index 000000000..fbf7fa46b --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/LoginViewModel.cs @@ -0,0 +1,29 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// +/// The sign-in screen: the form fields it repeats and what it shows. A request never binds this type (the form is ), so +/// the outputs cannot be set from outside; is always empty. +/// +public sealed class LoginViewModel : LoginForm +{ + /// Whether the registration link is shown. + public bool AllowRegistration { get; set; } + + /// Whether sign-in with an external provider is offered (any provider in ). + public bool HasExternalProvider { get; set; } + + /// The first provider's display name (kept for clients that offer one button); see . + public string? ExternalProviderName { get; set; } + + /// The configured external providers, one sign-in button each. + public System.Collections.Generic.IReadOnlyList ExternalProviders { get; set; } = System.Array.Empty(); + + /// Whether mail is configured (the forgot-password link is shown). + public bool EmailIsConfigured { get; set; } + + /// The refusal to show. + public string? Error { get; set; } + + /// The notice to show. + public string? Notice { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/ProfileViewModel.cs b/src/BaGet.Identity.Application/Models/Account/ProfileViewModel.cs new file mode 100644 index 000000000..eb6d92b4c --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ProfileViewModel.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Account; + +/// A user's or an organization's public page: the packages it owns. +public sealed class ProfileViewModel +{ + /// The account's name. + public string? Name { get; set; } + + /// Whether the account is an organization. + public bool IsOrganization { get; set; } + + /// The owned packages with their downloads. + public IReadOnlyList Packages { get; set; } = Array.Empty(); + + /// The members of an organization. + public IReadOnlyList Members { get; set; } = Array.Empty(); + + /// Whether the profile is the signed-in user's own. + public bool IsCurrentUser { get; set; } + + /// The account's avatar address, or null when Gravatar is off. + public string? AvatarUrl { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/ReauthenticateForm.cs b/src/BaGet.Identity.Application/Models/Account/ReauthenticateForm.cs new file mode 100644 index 000000000..e3335c5da --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ReauthenticateForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// What the "sign in again" button posts. +public class ReauthenticateForm +{ + /// Where to go after the provider answered; only a local URL is followed. + public string? ReturnUrl { get; set; } + + /// The id of the linked provider to sign in again with; empty takes the only linked one (several: the screen offers the choice). + public string? Provider { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/ReauthenticateView.cs b/src/BaGet.Identity.Application/Models/Account/ReauthenticateView.cs new file mode 100644 index 000000000..60e7da068 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ReauthenticateView.cs @@ -0,0 +1,4 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// What the "sign in again" prompt shows. +public record ReauthenticateView(bool Done, bool Available, string ReturnUrl); diff --git a/src/BaGet.Identity.Application/Models/Account/ReauthenticateViewModel.cs b/src/BaGet.Identity.Application/Models/Account/ReauthenticateViewModel.cs new file mode 100644 index 000000000..b82f9902d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ReauthenticateViewModel.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// The "confirm it is you" screen of an account without a password. A request binds , never this type. +public sealed class ReauthenticateViewModel : ReauthenticateForm +{ + /// The refusal to show. + public string? Error { get; set; } + + /// The linked providers to pick from when the account has several (one button each); null otherwise. + public System.Collections.Generic.IReadOnlyList? Providers { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/RecoveryCodeLoginForm.cs b/src/BaGet.Identity.Application/Models/Account/RecoveryCodeLoginForm.cs new file mode 100644 index 000000000..d95ac354d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/RecoveryCodeLoginForm.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the recovery-code form posts. +public class RecoveryCodeLoginForm +{ + /// The recovery code. + [Required] + [Display(Name = "Recovery code")] + public string? RecoveryCode { get; set; } + + /// Where to go after signing in; only a local URL is followed. + public string? ReturnUrl { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/RecoveryCodeLoginViewModel.cs b/src/BaGet.Identity.Application/Models/Account/RecoveryCodeLoginViewModel.cs new file mode 100644 index 000000000..1f29bd7c3 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/RecoveryCodeLoginViewModel.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// The second step of signing in with a recovery code. A request binds , never this type. +public sealed class RecoveryCodeLoginViewModel : RecoveryCodeLoginForm +{ + /// The refusal to show. + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/RegisterForm.cs b/src/BaGet.Identity.Application/Models/Account/RegisterForm.cs new file mode 100644 index 000000000..6bd3adc67 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/RegisterForm.cs @@ -0,0 +1,31 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the registration form posts. +public class RegisterForm +{ + /// The wanted user name. + [Required] + [Display(Name = "User name")] + public string? UserName { get; set; } + + /// The email address. + [EmailAddress] + public string? Email { get; set; } + + /// The password. Never echoed. + [Required] + [DataType(DataType.Password)] + public string? Password { get; set; } + + /// The password again. Never echoed. + [Required] + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + [Compare(nameof(Password), ErrorMessage = "The passwords do not match.")] + public string? ConfirmPassword { get; set; } + + /// Where to go after signing in; only a local URL is followed. + public string? ReturnUrl { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/RegisterViewModel.cs b/src/BaGet.Identity.Application/Models/Account/RegisterViewModel.cs new file mode 100644 index 000000000..f97461052 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/RegisterViewModel.cs @@ -0,0 +1,17 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// The registration screen. A request binds , never this type; the passwords are always empty here. +public sealed class RegisterViewModel : RegisterForm +{ + /// Whether the account was created but waits for an administrator (Accounts:RequireApproval). + public bool AwaitingApproval { get; set; } + + /// Whether a confirmation link was mailed. + public bool ConfirmationSent { get; set; } + + /// Whether the screen asks for an email address. + public bool EmailRequired { get; set; } + + /// Over /api/ui only: the tokens of the new account when it can sign in at once (no cookie is set for an HTTP caller). Null on the screen. + public Session.SessionModel? Session { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/ResetPasswordForm.cs b/src/BaGet.Identity.Application/Models/Account/ResetPasswordForm.cs new file mode 100644 index 000000000..69e15fefe --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ResetPasswordForm.cs @@ -0,0 +1,31 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the new-password form behind a reset link posts. +public class ResetPasswordForm +{ + /// The account named by the link. + public string? UserId { get; set; } + + /// The encoded reset token of the link. + public string? Code { get; set; } + + /// The new password. Never echoed. + [Required] + [DataType(DataType.Password)] + [Display(Name = "New password")] + public string? Password { get; set; } + + /// The new password again. Never echoed. + [Required] + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + [Compare(nameof(Password), ErrorMessage = "The passwords do not match.")] + public string? ConfirmPassword { get; set; } + + /// Whether the link carries a user and a token. + [JsonIgnore] + public bool LinkIsUsable => !string.IsNullOrEmpty(UserId) && !string.IsNullOrEmpty(Code); +} diff --git a/src/BaGet.Identity.Application/Models/Account/ResetPasswordViewModel.cs b/src/BaGet.Identity.Application/Models/Account/ResetPasswordViewModel.cs new file mode 100644 index 000000000..5aa637517 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/ResetPasswordViewModel.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// The screen behind the link of a password reset email. A request binds , never this type. +public sealed class ResetPasswordViewModel : ResetPasswordForm +{ + /// The refusal to show. + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/TwoFactorLoginForm.cs b/src/BaGet.Identity.Application/Models/Account/TwoFactorLoginForm.cs new file mode 100644 index 000000000..3a102b6f7 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/TwoFactorLoginForm.cs @@ -0,0 +1,18 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the authenticator-code form posts. +public class TwoFactorLoginForm +{ + /// The code from the authenticator app. + [Required] + [Display(Name = "Authenticator code")] + public string? Code { get; set; } + + /// Whether the session outlives the browser. + public bool RememberMe { get; set; } + + /// Where to go after signing in; only a local URL is followed. + public string? ReturnUrl { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/TwoFactorLoginViewModel.cs b/src/BaGet.Identity.Application/Models/Account/TwoFactorLoginViewModel.cs new file mode 100644 index 000000000..7b6e6bb32 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/TwoFactorLoginViewModel.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Account; + +/// The second step of signing in: an authenticator code. A request binds , never this type. +public sealed class TwoFactorLoginViewModel : TwoFactorLoginForm +{ + /// The refusal to show. + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/TwoFactorViewModel.cs b/src/BaGet.Identity.Application/Models/Account/TwoFactorViewModel.cs new file mode 100644 index 000000000..a1feb10da --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/TwoFactorViewModel.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Account; + +/// What the two-factor authentication screen shows. +public sealed class TwoFactorViewModel +{ + /// Whether two-factor authentication is on. + public bool TwoFactorEnabled { get; set; } + + /// The key to type into an authenticator that cannot scan the QR code. + public string? SharedKey { get; set; } + + /// The QR code of the setup link, an SVG built from the user's own key. + public string? QrCodeSvg { get; set; } + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; set; } + + /// Whether an external provider is configured to sign in again with. + public bool CanReauthenticate { get; set; } + + /// How many recovery codes are unused. + public int RecoveryCodesLeft { get; set; } + + /// Whether the account has a password (else it signs in through a provider). + public bool HasPassword { get; set; } = true; + + /// The new recovery codes. Shown once, when two-factor authentication is turned on. + public IReadOnlyList RecoveryCodes { get; set; } = Array.Empty(); + + /// The refusal to show. + public string? Error { get; set; } + + /// The success message to show. + public string? Message { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Account/UserAccountInfo.cs b/src/BaGet.Identity.Application/Models/Account/UserAccountInfo.cs new file mode 100644 index 000000000..132d6d6ee --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Account/UserAccountInfo.cs @@ -0,0 +1,11 @@ +using System; + +namespace BaGet.Identity.Application.Models.Account; + +/// The account an administrator looks at, without anything that signs in as it (no password hash, security stamp or tokens). +/// The user name. +/// The email address, or null. +/// When the account was created. +/// Whether it is a server administrator. +/// Whether it waits for an administrator to enable it. +public sealed record UserAccountInfo(string? UserName, string? Email, DateTime Created, bool IsAdministrator, bool PendingApproval); diff --git a/src/BaGet.Identity.Application/Models/Operations/AbuseForm.cs b/src/BaGet.Identity.Application/Models/Operations/AbuseForm.cs new file mode 100644 index 000000000..707258a9d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/AbuseForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Operations; + +/// A decision on an abuse report. +/// The report's number. +/// Whether the list to come back to shows the resolved reports too. +public sealed record AbuseForm(int Key, bool All); diff --git a/src/BaGet.Identity.Application/Models/Operations/AbuseViewModel.cs b/src/BaGet.Identity.Application/Models/Operations/AbuseViewModel.cs new file mode 100644 index 000000000..a886d4c81 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/AbuseViewModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Operations; + +/// What the abuse reports screen (/admin/abuse) shows: the reports of every repository. +public sealed class AbuseViewModel : IFlashModel +{ + /// Show the resolved reports too. + public bool All { get; set; } + + /// Whether reports are stored with the configured database. + public bool IsSupported { get; internal set; } + + /// The reports, newest first. + public IReadOnlyList Items { get; internal set; } = Array.Empty(); + + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Operations/OperationForm.cs b/src/BaGet.Identity.Application/Models/Operations/OperationForm.cs new file mode 100644 index 000000000..77649ef7a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/OperationForm.cs @@ -0,0 +1,7 @@ +namespace BaGet.Identity.Application.Models.Operations; + +/// Starting a maintenance operation. +/// The operation's name (catalog-rebuild). +/// The repository it runs on. +/// The administrator's password (asked for operations that delete data). +public sealed record OperationForm(string? Operation, string? Repository, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Operations/OperationRow.cs b/src/BaGet.Identity.Application/Models/Operations/OperationRow.cs new file mode 100644 index 000000000..2cb5b9fc2 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/OperationRow.cs @@ -0,0 +1,9 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Operations; + +/// One row of the operations screen: an operation on a repository. +/// The operation. +/// The repository it runs on. +/// The status of its last run, or null. +public sealed record OperationRow(IAdminOperation Operation, RepositoryInfo Repository, AdminJobStatus? Status); diff --git a/src/BaGet.Identity.Application/Models/Operations/OperationsViewModel.cs b/src/BaGet.Identity.Application/Models/Operations/OperationsViewModel.cs new file mode 100644 index 000000000..71cac511c --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/OperationsViewModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Operations; + +/// What the operations screen (/admin/operations) shows: the maintenance operations and the status of each. +public sealed class OperationsViewModel : ConfirmationModel, IFlashModel +{ + /// The operations available on this server, for every repository. + public IReadOnlyList Rows { get; internal set; } = Array.Empty(); + + /// Whether any job is running (the page refreshes itself). + public bool AnyRunning => Rows.Any(r => r.Status?.State == AdminJobState.Running); + + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Operations/SubmissionForm.cs b/src/BaGet.Identity.Application/Models/Operations/SubmissionForm.cs new file mode 100644 index 000000000..107c071d8 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/SubmissionForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Operations; + +/// A decision on a stuck submission of the validation queue. +/// The submission. +/// The administrator's password (asked to release or reject). +public sealed record SubmissionForm(string? SubmissionId, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Operations/ValidationStatusViewModel.cs b/src/BaGet.Identity.Application/Models/Operations/ValidationStatusViewModel.cs new file mode 100644 index 000000000..e55ef6003 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/ValidationStatusViewModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Operations; + +/// What the validation status screen (/packages/{id}/validation) shows; filled by the screen's workflow. +public sealed class ValidationStatusViewModel +{ + /// The package ID from the address. + public string? Id { get; internal set; } + + /// The newest submission of each version, newest version first. + public IReadOnlyList Submissions { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Operations/ValidationSubmission.cs b/src/BaGet.Identity.Application/Models/Operations/ValidationSubmission.cs new file mode 100644 index 000000000..bea9e9e85 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/ValidationSubmission.cs @@ -0,0 +1,7 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Operations; + +/// One version's newest validation submission and the verdict of every step. +public sealed record ValidationSubmission(string Version, string? SubmissionId, string Status, IReadOnlyList Steps); diff --git a/src/BaGet.Identity.Application/Models/Operations/ValidationViewModel.cs b/src/BaGet.Identity.Application/Models/Operations/ValidationViewModel.cs new file mode 100644 index 000000000..0a9b42192 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Operations/ValidationViewModel.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Operations; + +/// What the validation queue screen (/admin/validation) shows: pending and quarantined submissions. +public sealed class ValidationViewModel : ConfirmationModel, IFlashModel +{ + /// Whether validation can be administered here. + public bool IsSupported { get; internal set; } + + /// The pending and quarantined submissions. + public IReadOnlyList Submissions { get; internal set; } = Array.Empty(); + + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Organizations/AccountOrganization.cs b/src/BaGet.Identity.Application/Models/Organizations/AccountOrganization.cs new file mode 100644 index 000000000..9d889f1ce --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/AccountOrganization.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Organizations; + +/// One organization with its members. +public class AccountOrganization +{ + /// The organization's name. + public string? Name { get; set; } + + /// Whether the current user administers it. + public bool IsAdmin { get; set; } + + /// The members, by user name. + public IReadOnlyList? Members { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Organizations/AccountOrganizationMember.cs b/src/BaGet.Identity.Application/Models/Organizations/AccountOrganizationMember.cs new file mode 100644 index 000000000..ca0b56949 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/AccountOrganizationMember.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Organizations; + +/// One member of an organization (a flat record, so the screen's JSON names its fields). +/// The member's user name. +/// Whether the member administers the organization. +public sealed record AccountOrganizationMember(string UserName, bool IsAdmin); diff --git a/src/BaGet.Identity.Application/Models/Organizations/AdminOrganizationsViewModel.cs b/src/BaGet.Identity.Application/Models/Organizations/AdminOrganizationsViewModel.cs new file mode 100644 index 000000000..1c5ca88a2 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/AdminOrganizationsViewModel.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using BaGet.Identity.Application.Services.Organizations; + +namespace BaGet.Identity.Application.Models.Organizations; + +/// What the organizations screen (/admin/organizations) lists: every organization with its members and packages. +public sealed class AdminOrganizationsViewModel +{ + /// The organizations, by name. + public IReadOnlyList Organizations { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Organizations/OrganizationDetailViewModel.cs b/src/BaGet.Identity.Application/Models/Organizations/OrganizationDetailViewModel.cs new file mode 100644 index 000000000..926ccbe92 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/OrganizationDetailViewModel.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Organizations; + +/// What the organization screen (/admin/organizations/{name}) shows: the organization, its members and the last action. +public sealed class OrganizationDetailViewModel : ConfirmationModel, IFlashModel +{ + /// The organization's name (route). + public string? Name { get; set; } + + /// The organization. + public Organization? Organization { get; internal set; } + + /// Its members, by name. + public IReadOnlyList Members { get; internal set; } = Array.Empty(); + + /// How many package IDs it owns, in every repository. + public int OwnedPackageIds { get; internal set; } + + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Organizations/OrganizationMemberForm.cs b/src/BaGet.Identity.Application/Models/Organizations/OrganizationMemberForm.cs new file mode 100644 index 000000000..a711b3aa8 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/OrganizationMemberForm.cs @@ -0,0 +1,7 @@ +namespace BaGet.Identity.Application.Models.Organizations; + +/// Adding a member to an organization, changing their administrator flag or removing them. +/// The member's user name. +/// Whether the member administers the organization (ignored when removing). +/// The administrator's password. +public sealed record OrganizationMemberForm(string? UserName, bool IsAdmin, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Organizations/OrganizationMemberRow.cs b/src/BaGet.Identity.Application/Models/Organizations/OrganizationMemberRow.cs new file mode 100644 index 000000000..432839029 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/OrganizationMemberRow.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Organizations; + +/// A member as the organization page lists them. +/// The user name. +/// Whether the member administers the organization. +public record OrganizationMemberRow(string? UserName, bool IsAdmin); diff --git a/src/BaGet.Identity.Application/Models/Organizations/OrganizationRenameForm.cs b/src/BaGet.Identity.Application/Models/Organizations/OrganizationRenameForm.cs new file mode 100644 index 000000000..e689d7000 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/OrganizationRenameForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Organizations; + +/// Renaming an organization. +/// The new name. +/// The administrator's password. +public sealed record OrganizationRenameForm(string? NewName, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Organizations/OrganizationsViewModel.cs b/src/BaGet.Identity.Application/Models/Organizations/OrganizationsViewModel.cs new file mode 100644 index 000000000..dbfa3d396 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Organizations/OrganizationsViewModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Organizations; + +/// The signed-in user's organizations screen. +public sealed class OrganizationsViewModel +{ + /// The organizations the user belongs to. + public IReadOnlyList Organizations { get; set; } = Array.Empty(); + + /// The answer to the last action. + public string? Message { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/AccountPackagesViewModel.cs b/src/BaGet.Identity.Application/Models/Packages/AccountPackagesViewModel.cs new file mode 100644 index 000000000..6c5ad52ca --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/AccountPackagesViewModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Identity.Application.Models.Packages; + +/// The "My packages" screen: the packages the user owns in each repository. +public sealed class AccountPackagesViewModel +{ + /// The owned packages of each repository that has any, default first. + public IReadOnlyList Groups { get; set; } = Array.Empty(); + + /// Whether the user owns nothing in any repository. + public bool IsEmpty => Groups.Count == 0; + + /// Whether the list needs repository headings: more than the default repository holds packages of the user. + public bool ShowRepositoryNames => Groups.Any(g => !g.Repository.IsDefault); +} diff --git a/src/BaGet.Identity.Application/Models/Packages/AdminPackageRow.cs b/src/BaGet.Identity.Application/Models/Packages/AdminPackageRow.cs new file mode 100644 index 000000000..fea618b9a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/AdminPackageRow.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Packages; + +/// A package ID as the administrator pages list it. +/// The ID summarised across its versions. +/// The names of its owners; empty for an ownerless ID. +/// The repository the ID is in; ownership and versions are per repository. +public record AdminPackageRow( + OwnedPackage Package, + IReadOnlyList Owners, + string RepositoryName = Repository.DefaultName); diff --git a/src/BaGet.Identity.Application/Models/Packages/AdminPackagesViewModel.cs b/src/BaGet.Identity.Application/Models/Packages/AdminPackagesViewModel.cs new file mode 100644 index 000000000..30c115e35 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/AdminPackagesViewModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Packages; + +/// What the ownerless packages screen (/admin/packages) shows: the package IDs nobody owns, in every repository. +public sealed class AdminPackagesViewModel +{ + /// How many IDs a page lists. + public const int PageSize = 50; + + /// One-based page number (the p query value). + public int PageNumber { get; set; } = 1; + + /// The ownerless IDs on this page. + public IReadOnlyList Packages { get; internal set; } = Array.Empty(); + + /// Whether a Repository column is worth showing: some listed ID is outside the default repository. + public bool ShowRepository => Packages.Any(r => r.RepositoryName != Repository.DefaultName); + + /// The number of pages. + public int PageCount { get; internal set; } = 1; +} diff --git a/src/BaGet.Identity.Application/Models/Packages/ContactOwnersForm.cs b/src/BaGet.Identity.Application/Models/Packages/ContactOwnersForm.cs new file mode 100644 index 000000000..06e807f45 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/ContactOwnersForm.cs @@ -0,0 +1,15 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// +/// The fields of the contact-owners form as the screen receives them (a page's form post or the JSON body of the twin). It carries no +/// validation attributes: the use case validates by itself ( holds the rules), so a page's model +/// binding does not report the same error a second time. +/// +public sealed class ContactOwnersForm +{ + /// The message to send to the owners. + public string? Message { get; set; } + + /// Whether the sender also gets a copy. + public bool CopyToSelf { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/ContactOwnersViewModel.cs b/src/BaGet.Identity.Application/Models/Packages/ContactOwnersViewModel.cs new file mode 100644 index 000000000..5ea6779bf --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/ContactOwnersViewModel.cs @@ -0,0 +1,37 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Packages; + +/// +/// The contact-owners screen (/packages/{id}/contact-owners): the two form fields (, +/// , bound on POST) and what the screen shows; filled by the screen's workflow. +/// +public sealed class ContactOwnersViewModel +{ + /// The longest message the form accepts, in characters. + public const int MaxMessageLength = 4000; + + /// The message to send to the owners. + [Required] + [StringLength(MaxMessageLength)] + [Display(Name = "Message")] + public string? Message { get; set; } + + /// Whether the sender also gets a copy. + [Display(Name = "Send me a copy")] + public bool CopyToSelf { get; set; } + + /// The package ID as stored, which is the only text that reaches the subject. + public string? PackageId { get; internal set; } + + /// Whether the message was sent. + public bool Sent { get; internal set; } + + /// Why the message was not sent, or null. + public string? Error { get; internal set; } + + /// + /// Replies come to the sender's address, so there must be one, and it must be confirmed: an unconfirmed address could be anyone's. + /// + public bool SenderHasEmail { get; internal set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/DockerManageViewModel.cs b/src/BaGet.Identity.Application/Models/Packages/DockerManageViewModel.cs new file mode 100644 index 000000000..69bd33c65 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/DockerManageViewModel.cs @@ -0,0 +1,28 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Packages; + +/// What the Docker image management screen (/docker-manage/{**image}) shows; filled by the screen's workflow. +public sealed class DockerManageViewModel +{ + /// The image name from the address (it may contain slashes). + public string? Image { get; internal set; } + + /// The image, or null before it is loaded (or after it was deleted). + public OciImageInfo? Info { get; internal set; } + + /// The outcome of the last action. + public string? Message { get; internal set; } + + /// Whether reports a refusal. + public bool Failed { get; internal set; } + + /// Whether the user has a password to confirm with. + public bool HasPassword { get; internal set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; internal set; } + + /// Whether an external provider is available to sign in again with. + public bool CanReauthenticate { get; internal set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/MavenManageViewModel.cs b/src/BaGet.Identity.Application/Models/Packages/MavenManageViewModel.cs new file mode 100644 index 000000000..f8498e227 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/MavenManageViewModel.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Packages; + +/// What the Maven artifact management screen (/maven-manage/{group}/{artifact}) shows; filled by the screen's workflow. +public sealed class MavenManageViewModel +{ + /// The group id from the address. + public string? Group { get; internal set; } + + /// The artifact id from the address. + public string? Artifact { get; internal set; } + + /// The version whose files are listed (?version=), or null. + public string? Version { get; internal set; } + + /// The artifact, or null before it is loaded (or after its last version went). + public MavenArtifactInfo? Info { get; internal set; } + + /// The chosen version with its files, or null. + public MavenVersionDetail? Selected { get; internal set; } + + /// The artifact's owners. + public IReadOnlyList Owners { get; internal set; } = Array.Empty(); + + /// The outcome of the last action. + public string? Message { get; internal set; } + + /// Whether reports a refusal. + public bool Failed { get; internal set; } + + /// Whether the signed-in user is an administrator. + public bool IsAdministrator { get; internal set; } + + /// Whether the user manages the artifact only as an administrator (they are not an owner). + public bool ActingAsAdministrator { get; internal set; } + + /// Whether the user has a password to confirm with. + public bool HasPassword { get; internal set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; internal set; } + + /// Whether an external provider is available to sign in again with. + public bool CanReauthenticate { get; internal set; } + + /// group:artifact. + public string Name => MavenNames.ArtifactName(Group ?? string.Empty, Artifact ?? string.Empty); +} diff --git a/src/BaGet.Identity.Application/Models/Packages/NpmManageViewModel.cs b/src/BaGet.Identity.Application/Models/Packages/NpmManageViewModel.cs new file mode 100644 index 000000000..08246d990 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/NpmManageViewModel.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Packages; + +/// What the npm package management screen (/npm-manage/{*id}) shows; filled by the screen's workflow. +public sealed class NpmManageViewModel +{ + /// The package name from the address. + public string? Id { get; internal set; } + + /// The package, or null before it is loaded. + public NpmPackageInfo? Package { get; internal set; } + + /// The package's owners. + public IReadOnlyList Owners { get; internal set; } = Array.Empty(); + + /// The outcome of the last action. + public string? Message { get; internal set; } + + /// Whether reports a refusal. + public bool Failed { get; internal set; } + + /// Whether the signed-in user is an administrator. + public bool IsAdministrator { get; internal set; } + + /// Whether the user manages the package only as an administrator (they are not an owner). + public bool ActingAsAdministrator { get; internal set; } + + /// Whether the user has a password to confirm with. + public bool HasPassword { get; internal set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; internal set; } + + /// Whether an external provider is available to sign in again with. + public bool CanReauthenticate { get; internal set; } + + /// The address npm is configured with for this repository. + public string RegistryUrl { get; internal set; } = string.Empty; + + /// How long after publishing a version its owner may unpublish it with Deploy alone. + public TimeSpan UnpublishWindow { get; internal set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/OwnedPackage.cs b/src/BaGet.Identity.Application/Models/Packages/OwnedPackage.cs new file mode 100644 index 000000000..2f135d480 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/OwnedPackage.cs @@ -0,0 +1,20 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// +/// One owned package ID, summarised across its versions. +/// +public class OwnedPackage +{ + public string? Id { get; set; } + + /// + /// The highest version, listed or not, or null when no version remains. + /// + public string? LatestVersion { get; set; } + + public bool LatestVersionIsListed { get; set; } + + public int VersionCount { get; set; } + + public long Downloads { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/OwnedVersion.cs b/src/BaGet.Identity.Application/Models/Packages/OwnedVersion.cs new file mode 100644 index 000000000..4c948f7f5 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/OwnedVersion.cs @@ -0,0 +1,17 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// +/// The columns the summary needs, and nothing else. +/// +internal class OwnedVersion +{ + public string? Id { get; set; } + + public string? NormalizedVersion { get; set; } + + public string? OriginalVersion { get; set; } + + public bool Listed { get; set; } + + public long Downloads { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageDeprecateForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageDeprecateForm.cs new file mode 100644 index 000000000..56e4d17e1 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageDeprecateForm.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of Deprecate. +public sealed class PackageManageDeprecateForm +{ + /// The version. + public string? Version { get; set; } + + /// The reasons (at least one of Legacy, CriticalBugs, Other). + public List? Reasons { get; set; } + + /// Free text, optional. + public string? Message { get; set; } + + /// The package to use instead, optional. + public string? AlternatePackageId { get; set; } + + /// The versions of it that may be used, optional (needs ). + public string? AlternateVersionRange { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageDeprecation.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageDeprecation.cs new file mode 100644 index 000000000..663207d38 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageDeprecation.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Packages; + +/// A version's deprecation. +/// Why (Legacy, CriticalBugs, Other). +/// Free text, or null. +/// The package to use instead, or null. +/// The versions of it that may be used, or null. +public sealed record PackageManageDeprecation(IReadOnlyList Reasons, string? Message, string? AlternatePackageId, string? AlternateVersionRange); diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageHardDeleteForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageHardDeleteForm.cs new file mode 100644 index 000000000..0ad0a6b33 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageHardDeleteForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of a permanent deletion of a version (administrators; the password confirms). +public sealed class PackageManageHardDeleteForm +{ + /// The version. + public string? Version { get; set; } + + /// The caller's password. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageOwner.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageOwner.cs new file mode 100644 index 000000000..e15dcaf28 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageOwner.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// An owner of a package ID. +/// The user or organization name. +/// Whether the ID is reserved for this owner. +public sealed record PackageManageOwner(string? OwnerName, bool IsVerified); diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageOwnerForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageOwnerForm.cs new file mode 100644 index 000000000..f5d6a9d6f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageOwnerForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of a handler that names an owner. +public sealed class PackageManageOwnerForm +{ + /// The user or organization. + public string? OwnerName { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManagePasswordForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManagePasswordForm.cs new file mode 100644 index 000000000..247ced1fc --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManagePasswordForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of a handler that only asks for the password. +public sealed class PackageManagePasswordForm +{ + /// The caller's password. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageRemoveVulnerabilityForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageRemoveVulnerabilityForm.cs new file mode 100644 index 000000000..93c530a10 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageRemoveVulnerabilityForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of RemoveVulnerability. +public sealed class PackageManageRemoveVulnerabilityForm +{ + /// The version. + public string? Version { get; set; } + + /// The vulnerability's key. + public int Key { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageReport.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageReport.cs new file mode 100644 index 000000000..d15f107ac --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageReport.cs @@ -0,0 +1,9 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// An open abuse report. +/// The report's key (what ResolveReport takes). +/// The reported version. +/// The reason given. +/// The details given. +/// Where to reply, if the reporter gave an address. +public sealed record PackageManageReport(int Key, string? PackageVersion, string? Reason, string? Details, string? ReporterEmail); diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageReportForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageReportForm.cs new file mode 100644 index 000000000..48567fb19 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageReportForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of ResolveReport. +public sealed class PackageManageReportForm +{ + /// The report's key. + public int Key { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageScreen.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageScreen.cs new file mode 100644 index 000000000..a016ecd46 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageScreen.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Packages; + +/// +/// What the package management screen (/packages/{id}/manage) shows, as plain data (the JSON model of /api/ui/packages/{id}/manage). +/// The page's own ManageViewModel is built from it for the view. +/// +public sealed class PackageManageScreen +{ + /// The package ID from the address. + public string? Id { get; set; } + + /// The ID's owners. + public IReadOnlyList Owners { get; set; } = Array.Empty(); + + /// The ID's versions, newest first, unlisted ones included. + public IReadOnlyList Versions { get; set; } = Array.Empty(); + + /// The open abuse reports against the ID. + public IReadOnlyList Reports { get; set; } = Array.Empty(); + + /// The outcome of the last action. + public string? Message { get; set; } + + /// Whether validation has submissions for the ID. + public bool HasValidation { get; set; } + + /// Whether the ID is verified (reserved). + public bool IsVerified => Owners.Any(o => o.IsVerified); + + /// The PDBs indexed from each version's symbol package, by normalized version. + public IReadOnlyDictionary> Symbols { get; set; } + = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + /// Whether the database records symbols per package version. + public bool SymbolsSupported { get; set; } + + /// The severity names a vulnerability can have, by their protocol number. + public IReadOnlyList SeverityNames { get; set; } = Array.Empty(); + + /// Whether the caller is an administrator. + public bool IsAdministrator { get; set; } + + /// Whether the caller manages this ID only as an administrator (not as an owner). + public bool ActingAsAdministrator { get; set; } + + /// Whether the caller has a password to confirm with. + public bool HasPassword { get; set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; set; } + + /// Whether an external provider is available to sign in again with. + public bool CanReauthenticate { get; set; } + + /// What a deletion does on this server. + public PackageDeletionBehavior DeletionBehavior { get; set; } + + /// Whether the server refuses writes. + public bool IsReadOnlyMode { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageSymbol.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageSymbol.cs new file mode 100644 index 000000000..a1578cd66 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageSymbol.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// An indexed PDB of a version. +/// The PDB file name. +/// Its signature key. +public sealed record PackageManageSymbol(string FileName, string Key); diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageVerifiedForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageVerifiedForm.cs new file mode 100644 index 000000000..acdfd9dac --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageVerifiedForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of SetVerified. +public sealed class PackageManageVerifiedForm +{ + /// Whether the ID is verified. + public bool Verified { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageVersion.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageVersion.cs new file mode 100644 index 000000000..133a0b21d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageVersion.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Packages; + +/// One version of the ID. +/// The version as published (original text). +/// The normalized version, which the forms post back. +/// The download count. +/// Whether the version is listed. +/// Its deprecation, or null. +/// Its vulnerabilities. +public sealed record PackageManageVersion( + string Version, + string? NormalizedVersion, + long Downloads, + bool Listed, + PackageManageDeprecation? Deprecation, + IReadOnlyList Vulnerabilities); diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageVersionForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageVersionForm.cs new file mode 100644 index 000000000..93fd8da59 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageVersionForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of a handler that names a version. +public sealed class PackageManageVersionForm +{ + /// The (normalized) version. + public string? Version { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageVulnerability.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageVulnerability.cs new file mode 100644 index 000000000..584141a0b --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageVulnerability.cs @@ -0,0 +1,9 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// A vulnerability recorded for a version. +/// The row's key (what RemoveVulnerability takes). +/// The advisory. +/// 0 low, 1 moderate, 2 high, 3 critical. +/// The affected range, or null. +/// Null for a manual entry, osv for one the scanner wrote (not editable here). +public sealed record PackageManageVulnerability(int Key, string? AdvisoryUrl, int Severity, string? VersionRange, string? Source); diff --git a/src/BaGet.Identity.Application/Models/Packages/PackageManageVulnerabilityForm.cs b/src/BaGet.Identity.Application/Models/Packages/PackageManageVulnerabilityForm.cs new file mode 100644 index 000000000..472b4ec19 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackageManageVulnerabilityForm.cs @@ -0,0 +1,17 @@ +namespace BaGet.Identity.Application.Models.Packages; + +/// The form of AddVulnerability. +public sealed class PackageManageVulnerabilityForm +{ + /// The version. + public string? Version { get; set; } + + /// The advisory URL. + public string? AdvisoryUrl { get; set; } + + /// 0 low, 1 moderate, 2 high, 3 critical. + public int Severity { get; set; } + + /// The affected range, optional. + public string? VersionRange { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/PackagesModel.cs b/src/BaGet.Identity.Application/Models/Packages/PackagesModel.cs new file mode 100644 index 000000000..66b1f1330 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/PackagesModel.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.Models.Packages; + +/// +/// The package IDs a user owns, directly or through an organization, summarised per repository: the rows of the My packages +/// and the administrators' package screens. Ownership is per repository, so the IDs are grouped by the repositories the user +/// may read (); a repository where the user owns nothing is not listed. +/// +public static class PackagesModel +{ + /// + /// Every owned ID's versions, in one query, projected to the four columns the page + /// shows. The page cost must not grow with how successful a publisher the user is: + /// a per-ID + /// would be six round trips each - it eagerly loads the dependencies, package types, + /// target frameworks, deprecation and vulnerabilities of every version - to compute + /// three numbers from them. + /// + /// + /// Read through , which is what + /// already requires: + /// this page cannot work on a database without one either way, so routing it through + /// bought nothing. + /// + internal static async Task> ListVersionsAsync( + IContext context, + IReadOnlyList? ids, + CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var lowered = ids.Select(id => id.ToLowerInvariant()).ToList(); + #pragma warning restore CS8604 + + // Unlisted versions included: they are the owner's own, and an ID whose versions + // are all unlisted would otherwise look empty. + #pragma warning disable CS8602, CS8604 + return await context.Packages + .AsNoTracking() + .Where(p => lowered.Contains(p.Id.ToLower())) + .Select(p => new OwnedVersion + { + Id = p.Id, + NormalizedVersion = p.NormalizedVersionString, + OriginalVersion = p.OriginalVersionString, + Listed = p.Listed, + Downloads = p.Downloads, + }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + } + + // A Maven repository keeps its own tables too: the owned ids are group:artifact, summarised one artifact at a time. + internal static async Task> SummariseMavenAsync(IMavenRepository maven, IReadOnlyList ids, CancellationToken cancellationToken) + { + var owned = new List(ids.Count); + foreach (var id in ids) + { + var found = MavenNames.TryParseArtifactName(id, out var groupId, out var artifactId); + var artifact = found ? await maven.GetArtifactAsync(groupId, artifactId, cancellationToken) : null; + owned.Add(new OwnedPackage + { + Id = artifact?.Name ?? id, + LatestVersion = artifact?.Latest?.Version, + LatestVersionIsListed = artifact != null, + VersionCount = artifact?.Versions.Count ?? 0, + Downloads = 0, + }); + } + + return owned; + } + + // An npm repository keeps its own tables: the summary comes from the registry, one package at a time (a user owns few). + internal static async Task> SummariseNpmAsync(INpmRegistry registry, IReadOnlyList ids, CancellationToken cancellationToken) + { + var owned = new List(ids.Count); + foreach (var id in ids) + { + var package = await registry.GetPackageAsync(id.ToLowerInvariant(), cancellationToken); + owned.Add(new OwnedPackage + { + Id = package?.Name ?? id, + LatestVersion = package?.Latest?.Version, + LatestVersionIsListed = package != null, + VersionCount = package?.Versions.Count ?? 0, + Downloads = 0, + }); + } + + return owned; + } + + /// + /// The highest version is decided here rather than in the query: version ordering is + /// SemVer's, which no database sorts correctly. + /// + internal static List Summarise(IReadOnlyList? ids, List versions) + { + #pragma warning disable CS8621, CS8714 + var byId = versions + .GroupBy(v => v.Id, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + #pragma warning restore CS8621, CS8714 + + #pragma warning disable CS8602 + var owned = new List(ids.Count); + #pragma warning restore CS8602 + foreach (var id in ids) + { + if (!byId.TryGetValue(id, out var found)) found = new List(); + + #pragma warning disable CS8604 + var latest = found + .OrderByDescending(v => NuGetVersion.Parse(v.OriginalVersion ?? v.NormalizedVersion)) + .FirstOrDefault(); + #pragma warning restore CS8604 + + #pragma warning disable CS8604 + owned.Add(new OwnedPackage + { + Id = latest?.Id ?? id, + LatestVersion = latest == null + ? null + : NuGetVersion.Parse(latest.OriginalVersion ?? latest.NormalizedVersion).ToNormalizedString(), + LatestVersionIsListed = latest?.Listed ?? false, + VersionCount = found.Count, + Downloads = found.Sum(v => v.Downloads), + }); + #pragma warning restore CS8604 + } + + return owned; + } +} diff --git a/src/BaGet.Identity.Application/Models/Packages/RepositoryPackages.cs b/src/BaGet.Identity.Application/Models/Packages/RepositoryPackages.cs new file mode 100644 index 000000000..39456c15f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/RepositoryPackages.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Packages; + +/// +/// The packages the user owns in one repository. +/// +public sealed record RepositoryPackages(RepositoryInfo Repository, IReadOnlyList Packages); diff --git a/src/BaGet.Identity.Application/Models/Packages/UserPackagesViewModel.cs b/src/BaGet.Identity.Application/Models/Packages/UserPackagesViewModel.cs new file mode 100644 index 000000000..6d90d2f03 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Packages/UserPackagesViewModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Packages; + +/// What the user packages screen (/admin/users/{name}/packages) shows: the package IDs one user owns. +public sealed class UserPackagesViewModel +{ + /// The user name, from the route. + public string? Name { get; set; } + + /// The user's packages. + public IReadOnlyList Packages { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Policies/PatternFieldsView.cs b/src/BaGet.Identity.Application/Models/Policies/PatternFieldsView.cs new file mode 100644 index 000000000..e4eb62f4a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/PatternFieldsView.cs @@ -0,0 +1,9 @@ +namespace BaGet.Identity.Application.Models.Policies; + +/// What the pattern fields partial (_PatternFields) shows. +/// The repository patterns, one per line. +/// The include patterns, one per line. +/// The exclude patterns, one per line. +/// The test box package ID. +/// What the patterns select, or null before the first preview. +public sealed record PatternFieldsView(string? Repositories, string? Include, string? Exclude, string? TestPackage, PatternPreview? Preview); diff --git a/src/BaGet.Identity.Application/Models/Policies/PatternPreview.cs b/src/BaGet.Identity.Application/Models/Policies/PatternPreview.cs new file mode 100644 index 000000000..1f13edf54 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/PatternPreview.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// The result of previewing repository and package patterns. +/// The NuGet repositories whose names match the repository patterns. +/// The package ID typed in the test box, if any. +/// Whether the target would apply to , and why. +public sealed record PatternPreview(IReadOnlyList Repositories, string? TestPackage, PatternTest? Test); diff --git a/src/BaGet.Identity.Application/Models/Policies/PolicyViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/PolicyViewModel.cs new file mode 100644 index 000000000..d123a59fd --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/PolicyViewModel.cs @@ -0,0 +1,16 @@ +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Policies; + +/// +/// Shared shape of the policy screens (retention, scanning, replication): the password confirmation partial's inputs and the +/// outcome of the last action, which AdminControllerBase.Flash carries across a redirect. +/// +public abstract class PolicyViewModel : ConfirmationModel, IFlashModel +{ + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ReplicationBody.cs b/src/BaGet.Identity.Application/Models/Policies/ReplicationBody.cs new file mode 100644 index 000000000..df9aef4d3 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ReplicationBody.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Policies; + +/// Creating, saving or testing a replication, or any write of it that asks the password. +/// The settings (Form.* on the page). The peer's API key is write only: no answer carries it. +/// The administrator's password. +public sealed record ReplicationBody(ReplicationForm? Form, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Policies/ReplicationConfigViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/ReplicationConfigViewModel.cs new file mode 100644 index 000000000..b7eb014b8 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ReplicationConfigViewModel.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What one replication's screen (/admin/replication/{key}) shows. +public sealed class ReplicationConfigViewModel : PolicyViewModel +{ + /// The configuration's key (route). + public int Key { get; set; } + + /// The settings, as edited. + public ReplicationForm Form { get; set; } = new(); + + /// The configuration with the names of what it uses. + public ReplicationConfigView? View { get; internal set; } + + /// The log, newest first. + public IReadOnlyList Runs { get; internal set; } = Array.Empty(); + + /// What this process knows of the last job (a refusal that wrote no log entry shows here). + public ReplicationJobStatus? Job { get; internal set; } + + /// The result of the last connection test on this request, or null. + public ReplicationTestResult? Test { get; internal set; } + + /// How many items the local repository holds, or null when it could not be listed. + public int? LocalItems { get; internal set; } + + /// Whether a run is going here (the page refreshes itself). + public bool Running => Job?.Running == true; + + /// The local repositories a replication can name. + public IReadOnlyList Repositories { get; internal set; } = Array.Empty(); + + /// The newest run that ended without finishing everything, which Resume continues; null when there is none. + public ReplicationRun? Resumable + { + get + { + var last = Runs.FirstOrDefault(); + + return last != null && last.Status is ReplicationRunStatus.Failed or ReplicationRunStatus.Interrupted ? last : null; + } + } +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ReplicationFieldsView.cs b/src/BaGet.Identity.Application/Models/Policies/ReplicationFieldsView.cs new file mode 100644 index 000000000..5e8189116 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ReplicationFieldsView.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the replication fields partial shows. +/// The values. +/// The local repositories to choose from. +/// Prefix of the element ids, so two forms on one page do not clash. +/// Whether a key is stored (the field then says so). +public sealed record ReplicationFieldsView(ReplicationForm Form, IReadOnlyList Repositories, string IdPrefix, bool HasApiKey); diff --git a/src/BaGet.Identity.Application/Models/Policies/ReplicationForm.cs b/src/BaGet.Identity.Application/Models/Policies/ReplicationForm.cs new file mode 100644 index 000000000..8e3ea76a3 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ReplicationForm.cs @@ -0,0 +1,80 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// +/// What the replication form posts (Form.*): a as a person types it. The peer's API key is write +/// only: it is never filled back into a page; an empty field keeps the stored key. +/// +public sealed class ReplicationForm +{ + public string? Name { get; set; } + + public string? Repository { get; set; } + + /// Push or Pull. + [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] + public ReplicationDirection Direction { get; set; } = ReplicationDirection.Push; + + public string? PeerUrl { get; set; } + + public string? PeerRepository { get; set; } = BaGet.Core.Repository.DefaultName; + + /// The peer's API key (write only). + public string? ApiKey { get; set; } + + /// Forget the stored key. + public bool ClearApiKey { get; set; } + + public bool Enabled { get; set; } = true; + + public bool OnDeploy { get; set; } + + public int? ScheduleMinutes { get; set; } + + public bool PropagateDeletes { get; set; } + + [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] + public ReplicationConflict Conflict { get; set; } = ReplicationConflict.TargetWins; + + /// A copy without the peer's API key: what a screen's model carries back, so the key typed in a request is never echoed (JSON included). + public ReplicationForm WithoutSecret() => new() + { + Name = Name, + Repository = Repository, + Direction = Direction, + PeerUrl = PeerUrl, + PeerRepository = PeerRepository, + ApiKey = null, + ClearApiKey = ClearApiKey, + Enabled = Enabled, + OnDeploy = OnDeploy, + ScheduleMinutes = ScheduleMinutes, + PropagateDeletes = PropagateDeletes, + Conflict = Conflict, + }; + + /// The administration's input for configuration (0 creates). + public ReplicationInput ToInput(int key) + => new(key, Name, Repository, Direction, PeerUrl, PeerRepository, ApiKey, ClearApiKey, Enabled, OnDeploy, ScheduleMinutes, PropagateDeletes, Conflict); + + /// The form filled in from a stored configuration (without its key). + public static ReplicationForm From(ReplicationConfigView view) + { + var c = view.Config; + + return new ReplicationForm + { + Name = c.Name, + Repository = view.Repository, + Direction = c.Direction, + PeerUrl = c.PeerUrl, + PeerRepository = c.PeerRepository, + Enabled = c.Enabled, + OnDeploy = c.OnDeploy, + ScheduleMinutes = c.ScheduleMinutes, + PropagateDeletes = c.PropagateDeletes, + Conflict = c.Conflict, + }; + } +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ReplicationViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/ReplicationViewModel.cs new file mode 100644 index 000000000..7dfe38ded --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ReplicationViewModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the replications screen (/admin/replication) shows: every replication and the form that creates one. +public sealed class ReplicationViewModel : PolicyViewModel +{ + /// The new replication. + public ReplicationForm Form { get; set; } = new(); + + /// Every replication. + public IReadOnlyList Replications { get; internal set; } = Array.Empty(); + + /// The local repositories a replication can name. + public IReadOnlyList Repositories { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionFieldsView.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionFieldsView.cs new file mode 100644 index 000000000..e6e9e1436 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionFieldsView.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the policy fields partial shows. +/// The values. +/// The repositories to choose from. +/// The projects to choose from. +/// Prefix of the element ids, so two forms on one page do not clash. +public sealed record RetentionFieldsView(RetentionPolicyForm Form, IReadOnlyList Repositories, IReadOnlyList Projects, string IdPrefix); diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionHoldForm.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionHoldForm.cs new file mode 100644 index 000000000..ddaeba26f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionHoldForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Policies; + +/// Placing a legal hold. +/// The repository of the hold. +/// The artifact name. +/// The version; empty for every version. +/// Why (a case number, a ticket). +public sealed record RetentionHoldForm(string? HoldRepository, string? HoldName, string? HoldVersion, string? Reason); diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionHoldRemoval.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionHoldRemoval.cs new file mode 100644 index 000000000..fdf0b6376 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionHoldRemoval.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Policies; + +/// Lifting a legal hold. +/// The hold's number. +/// The administrator's password. +public sealed record RetentionHoldRemoval(int Key, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionHoldsViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionHoldsViewModel.cs new file mode 100644 index 000000000..04fdc5ef6 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionHoldsViewModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the legal holds screen (/admin/retention/holds) shows. +public sealed class RetentionHoldsViewModel : PolicyViewModel +{ + /// Only the holds of this repository (query). + public string? Repository { get; set; } + + /// The repository of the new hold. + public string? HoldRepository { get; set; } + + /// The artifact name of the new hold. + public string? HoldName { get; set; } + + /// The version of the new hold; empty for every version. + public string? HoldVersion { get; set; } + + /// Why (a case number, a ticket). + public string? Reason { get; set; } + + /// The holds. + public IReadOnlyList Holds { get; internal set; } = Array.Empty(); + + /// The repositories a hold can name. + public IReadOnlyList Repositories { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyBody.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyBody.cs new file mode 100644 index 000000000..8512169ac --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyBody.cs @@ -0,0 +1,9 @@ +namespace BaGet.Identity.Application.Models.Policies; + +// The bodies of the retention, scanning and replication screens' writes. A page posts them as form fields (the view controllers bind the same +// names and build these), the JSON API takes them as the request body; the use cases never see how they arrived. + +/// Creating or saving a retention policy, or any write of it that asks the password. +/// The rules (Form.* on the page). +/// The administrator's password. +public sealed record RetentionPolicyBody(RetentionPolicyForm? Form, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyForm.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyForm.cs new file mode 100644 index 000000000..bc5a27079 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyForm.cs @@ -0,0 +1,74 @@ +using System; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// +/// What the policy form posts (Form.*): the rules of a in the units a person types +/// (the cache limit in MiB). turns it into the administration's input. +/// +public sealed class RetentionPolicyForm +{ + public string? Name { get; set; } + + /// repository or project. + public string? ScopeKind { get; set; } = "repository"; + + /// The repository or project name. + public string? ScopeName { get; set; } + + public bool Enabled { get; set; } + + public string? NamePatterns { get; set; } + + public int? KeepLast { get; set; } + + public int? OlderThanDays { get; set; } + + public int? UnusedDays { get; set; } + + public bool PrereleaseOnly { get; set; } + + /// The remote cache limit in MiB. + public long? CacheLimitMb { get; set; } + + public int? UntaggedAfterDays { get; set; } + + public bool CollectGarbage { get; set; } + + public int? ScheduleHours { get; set; } + + /// The administration's input for policy (0 creates). + public RetentionPolicyInput ToInput(int key) + { + var project = string.Equals(ScopeKind, "project", StringComparison.Ordinal); + long? limit = CacheLimitMb is long mb ? (mb > long.MaxValue / (1024 * 1024) ? long.MaxValue : mb * 1024 * 1024) : null; + + return new RetentionPolicyInput( + key, Name, project ? null : ScopeName, project ? ScopeName : null, Enabled, NamePatterns, + KeepLast, OlderThanDays, UnusedDays, PrereleaseOnly, limit, UntaggedAfterDays, CollectGarbage, ScheduleHours); + } + + /// The form filled in from a stored policy. + public static RetentionPolicyForm From(RetentionPolicyView view) + { + var p = view.Policy; + + return new RetentionPolicyForm + { + Name = p.Name, + ScopeKind = p.ProjectKey != null ? "project" : "repository", + ScopeName = view.Repository ?? view.Project, + Enabled = p.Enabled, + NamePatterns = p.NamePatterns, + KeepLast = p.KeepLast, + OlderThanDays = p.OlderThanDays, + UnusedDays = p.UnusedDays, + PrereleaseOnly = p.PrereleaseOnly, + CacheLimitMb = p.CacheLimitBytes is long bytes ? (bytes + 1024 * 1024 - 1) / (1024 * 1024) : null, + UntaggedAfterDays = p.UntaggedAfterDays, + CollectGarbage = p.CollectGarbage, + ScheduleHours = p.ScheduleHours, + }; + } +} diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyViewModel.cs new file mode 100644 index 000000000..164d694a4 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionPolicyViewModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What one retention policy's screen (/admin/retention/{key}) shows. +public sealed class RetentionPolicyViewModel : PolicyViewModel +{ + /// The policy's key (route). + public int Key { get; set; } + + /// The rules, as edited. + public RetentionPolicyForm Form { get; set; } = new(); + + /// The policy with the names of what it applies to. + public RetentionPolicyView? View { get; internal set; } + + /// The last run since the server started (a dry run's report included), or null. + public RetentionJobStatus? Status { get; internal set; } + + /// Whether a run is in progress (the page refreshes itself). + public bool Running => Status?.State == RetentionJobState.Running; + + /// The repositories a policy can name. + public IReadOnlyList Repositories { get; internal set; } = Array.Empty(); + + /// The names of the projects a policy can name. + public IReadOnlyList ProjectNames { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Policies/RetentionViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/RetentionViewModel.cs new file mode 100644 index 000000000..67af5bd31 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/RetentionViewModel.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the retention policies screen (/admin/retention) shows: every policy and the form that creates one. +public sealed class RetentionViewModel : PolicyViewModel +{ + /// The new policy. + public RetentionPolicyForm Form { get; set; } = new(); + + /// Every policy. + public IReadOnlyList Policies { get; internal set; } = Array.Empty(); + + /// The repositories a policy can name. + public IReadOnlyList Repositories { get; internal set; } = Array.Empty(); + + /// The names of the projects a policy can name. + public IReadOnlyList ProjectNames { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanPolicyBody.cs b/src/BaGet.Identity.Application/Models/Policies/ScanPolicyBody.cs new file mode 100644 index 000000000..92f8ee17a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanPolicyBody.cs @@ -0,0 +1,13 @@ +namespace BaGet.Identity.Application.Models.Policies; + +/// Saving the scanning policy of a repository or project (empty values remove it). +/// Warn from this severity (0 to 3, or empty). +/// Refuse downloads from this severity. +/// Refuse deploys from this severity. +/// Refuse downloads of versions that were not scanned. +/// The administrator's password. +public sealed record ScanPolicyBody(string? Warn, string? BlockDownload, string? BlockDeploy, bool BlockUnscanned, string? Password) +{ + /// The fields the policy editor edits. + public ScanPolicyFields ToFields() => new() { Warn = Warn, BlockDownload = BlockDownload, BlockDeploy = BlockDeploy, BlockUnscanned = BlockUnscanned }; +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanPolicyFields.cs b/src/BaGet.Identity.Application/Models/Policies/ScanPolicyFields.cs new file mode 100644 index 000000000..6873645fd --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanPolicyFields.cs @@ -0,0 +1,51 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// +/// The scanning policy fields as the form posts them: a severity is the text of a number 0 (low) to 3 (critical), or empty for +/// "off". Shared by the repository and the project policy pages. +/// +public sealed class ScanPolicyFields +{ + /// Warn from this severity. + public string? Warn { get; set; } + + /// Refuse downloads from this severity. + public string? BlockDownload { get; set; } + + /// Refuse deploys from this severity. + public string? BlockDeploy { get; set; } + + /// Refuse downloads of versions that were not scanned. + public bool BlockUnscanned { get; set; } + + /// The fields showing (empty ones for none). + public static ScanPolicyFields From(ScanPolicy? policy) => new() + { + Warn = policy?.WarnSeverity?.ToString(System.Globalization.CultureInfo.InvariantCulture), + BlockDownload = policy?.BlockDownloadSeverity?.ToString(System.Globalization.CultureInfo.InvariantCulture), + BlockDeploy = policy?.BlockDeploySeverity?.ToString(System.Globalization.CultureInfo.InvariantCulture), + BlockUnscanned = policy?.BlockUnscanned ?? false, + }; + + /// The values the fields stand for. + /// A severity is not 0 to 3 or empty. + public ScanPolicyValues ToValues() + { + var values = new ScanPolicyValues(Parse(Warn, "warn"), Parse(BlockDownload, "block download"), Parse(BlockDeploy, "block deploy"), BlockUnscanned); + + return values.Validate() is { } problem ? throw new AccessModelException(problem) : values; + } + + private static int? Parse(string? text, string label) + { + if (string.IsNullOrWhiteSpace(text)) return null; + if (!int.TryParse(text, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var value)) + { + throw new AccessModelException($"The {label} severity is not valid."); + } + + return value; + } +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanPolicyFormView.cs b/src/BaGet.Identity.Application/Models/Policies/ScanPolicyFormView.cs new file mode 100644 index 000000000..706d6ff0c --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanPolicyFormView.cs @@ -0,0 +1,9 @@ +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the policy form partial needs. +/// The current values. +/// The password confirmation input. +/// A prefix for the input ids on the page. +public sealed record ScanPolicyFormView(ScanPolicyFields Fields, ConfirmPasswordView Confirmation, string Idprefix); diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanProjectViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/ScanProjectViewModel.cs new file mode 100644 index 000000000..a0e01744f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanProjectViewModel.cs @@ -0,0 +1,21 @@ +using System.Text.Json.Serialization; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the scanning policy of a project (/admin/scanning/projects/{name}) shows. +public sealed class ScanProjectViewModel : PolicyViewModel +{ + /// The project's name (route). + public string? Name { get; set; } + + /// The project. + public ProjectDetails? Project { get; internal set; } + + /// The policy stored for the project, or null. + public ScanPolicy? Own { get; internal set; } + + /// The fields of the policy editor (for the view; the JSON carries ). + [JsonIgnore] + public ScanPolicyFormView PolicyForm => new(ScanPolicyFields.From(Own), Confirmation("scan-project-password"), "scan-project"); +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanRepositoryViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/ScanRepositoryViewModel.cs new file mode 100644 index 000000000..fe069aa33 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanRepositoryViewModel.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the scanning dashboard of one repository (/admin/scanning/{name}) shows. +public sealed class ScanRepositoryViewModel : PolicyViewModel +{ + /// Versions listed per page. + public const int PageSize = 50; + + /// The repository's name (route). + public string? Name { get; set; } + + /// The lowest severity listed (0 low ... 3 critical). + public int MinSeverity { get; set; } + + /// The page of the list, from 1. + public int PageNumber { get; set; } = 1; + + /// The repository. + public RepositoryInfo? Repository { get; internal set; } + + /// The counts. + public ScanSummary? Summary { get; internal set; } + + /// The policy in force and where it comes from. + public EffectiveScanPolicy Effective { get; internal set; } = EffectiveScanPolicy.None; + + /// The policy stored for this repository itself, or null. + public ScanPolicy? Own { get; internal set; } + + /// The versions with findings on this page. + public IReadOnlyList Findings { get; internal set; } = Array.Empty(); + + /// Whether there is another page. + public bool HasMore { get; internal set; } + + /// The last run of the repository scan, or null. + public AdminJobStatus? Job { get; internal set; } + + /// The fields of the policy editor (for the view; the JSON carries ). + [JsonIgnore] + public ScanPolicyFormView PolicyForm => new(ScanPolicyFields.From(Own), Confirmation("scan-policy-password"), "scan-policy"); + + /// The package screen of each finding's version (by ), when its format has one. + public IReadOnlyDictionary PackageLinks { get; internal set; } = new Dictionary(); + + /// Turns a into an address; set by the view controller (the use case knows no routes). + [JsonIgnore] + public Func? LinkResolver { get; set; } + + /// The page of a version in its format (the repository's package page), for the findings list. + public string? PackageUrl(ScanResult result) + => PackageLinks.TryGetValue(result.Key, out var link) ? LinkResolver?.Invoke(link) : null; +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/ScanViewModel.cs new file mode 100644 index 000000000..eb9bca45c --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanViewModel.cs @@ -0,0 +1,31 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the Scan now screen (/scan-artifact) shows; filled by the screen's workflow. +public sealed class ScanViewModel +{ + /// The artifact name (NuGet id, npm name, Maven group:artifact, Docker image). + public string? Name { get; internal set; } + + /// The version (Docker: the manifest digest). + public string? Version { get; internal set; } + + /// Where the link back goes: the package page the user came from (a local address only). + public string? ReturnUrl { get; internal set; } + + /// What happened, for the screen to show. + public string? Message { get; internal set; } + + /// Whether reports a refusal. + public bool Failed { get; internal set; } + + /// The result just stored, with its findings, or null. + public ScanResult? Result { get; internal set; } + + /// The scanner status of the repository, for the explanation when it cannot run. + public ScanEngineStatus? Engine { get; internal set; } + + /// The address the link back leads to (the return address when it is local, else the home page). + public string BackUrl { get; internal set; } = "/"; +} diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanningProjectRow.cs b/src/BaGet.Identity.Application/Models/Policies/ScanningProjectRow.cs new file mode 100644 index 000000000..8ad9caa64 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanningProjectRow.cs @@ -0,0 +1,8 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// One project of the scanning overview. +/// The project. +/// Whether it has a scanning policy of its own. +public sealed record ScanningProjectRow(ProjectSummary Project, bool HasPolicy); diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanningRepositoryRow.cs b/src/BaGet.Identity.Application/Models/Policies/ScanningRepositoryRow.cs new file mode 100644 index 000000000..4c9d8da4a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanningRepositoryRow.cs @@ -0,0 +1,9 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// One repository of the scanning overview. +/// The repository. +/// Its scan counts. +/// The policy in force. +public sealed record ScanningRepositoryRow(RepositoryInfo Repository, ScanSummary Summary, EffectiveScanPolicy Policy); diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanningSettingsView.cs b/src/BaGet.Identity.Application/Models/Policies/ScanningSettingsView.cs new file mode 100644 index 000000000..e8245254e --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanningSettingsView.cs @@ -0,0 +1,11 @@ +using System; + +namespace BaGet.Identity.Application.Models.Policies; + +/// The scanning options the overview shows. +/// Whether artifacts are scanned. +/// Whether a stored version is queued for a scan at once. +/// The OSV API root. +/// The offline copy of the OSV data, or null. +/// The age after which an artifact is scanned again (zero or negative: never). +public sealed record ScanningSettingsView(bool Enabled, bool ScanOnDeploy, string OsvUrl, string? OsvOfflinePath, TimeSpan RescanInterval); diff --git a/src/BaGet.Identity.Application/Models/Policies/ScanningViewModel.cs b/src/BaGet.Identity.Application/Models/Policies/ScanningViewModel.cs new file mode 100644 index 000000000..02585c9ee --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Policies/ScanningViewModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Policies; + +/// What the vulnerability scanning overview (/admin/scanning) shows. +public sealed class ScanningViewModel +{ + /// + /// The scanning options in force, for the view. Not serialised: the options class holds the scanner's registry credential; the JSON carries + /// , the values the screen shows. + /// + [JsonIgnore] + public ScanningOptions Options { get; internal set; } = new(); + + /// The scanning options the screen shows (no credential). + public ScanningSettingsView Settings { get; internal set; } = new(false, true, string.Empty, null, TimeSpan.Zero); + + /// Whether Trivy is configured (container images are scanned). + public bool TrivyConfigured { get; internal set; } + + /// The repositories that can hold artifacts (virtual ones hold none). + public IReadOnlyList Repositories { get; internal set; } = Array.Empty(); + + /// The projects. + public IReadOnlyList Projects { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/FormatRow.cs b/src/BaGet.Identity.Application/Models/Repositories/FormatRow.cs new file mode 100644 index 000000000..81c3245e0 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/FormatRow.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// One format with what it offers, as the formats screen lists it. +/// The format module. +/// How many repositories use it. +/// The capabilities its services implement. +public sealed record FormatRow(IFormatModule Module, int Repositories, IReadOnlyList Capabilities); diff --git a/src/BaGet.Identity.Application/Models/Repositories/FormatsViewModel.cs b/src/BaGet.Identity.Application/Models/Repositories/FormatsViewModel.cs new file mode 100644 index 000000000..b798950d6 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/FormatsViewModel.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// What the formats screen (/admin/formats) lists: the package formats this server can host. +public sealed class FormatsViewModel +{ + /// The formats. + public IReadOnlyList Rows { get; internal set; } = Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RemoteFormModel.cs b/src/BaGet.Identity.Application/Models/Repositories/RemoteFormModel.cs new file mode 100644 index 000000000..107694778 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RemoteFormModel.cs @@ -0,0 +1,87 @@ +using System.Text.Json.Serialization; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// +/// The fields of a remote repository's upstream settings as the create and edit pages post them (prefix +/// Remote). The password is never rendered back: a blank one on save keeps the stored one. +/// +public class RemoteFormModel +{ + /// + /// For display: the format of the repository being edited (an npm repository has no protocol choice and a different URL and + /// credential wording). Never read back: the repository's own format decides. + /// + [JsonConverter(typeof(JsonStringEnumConverter))] + public RepositoryFormat Format { get; set; } = RepositoryFormat.NuGet; + + /// The upstream URL (V3 index.json or V2 feed, or an npm registry's base URL). + public string? Url { get; set; } + + /// The upstream's protocol (NuGet only; an npm repository speaks the npm registry protocol). + [JsonConverter(typeof(JsonStringEnumConverter))] + public RemoteProtocol Protocol { get; set; } = RemoteProtocol.V3; + + /// The HTTP Basic user name, if the upstream needs one. + public string? Username { get; set; } + + /// + /// The HTTP Basic password or token; blank keeps the stored one. Input only: a screen never sends it back (the use cases clear it from every model they return). + /// + public string? Password { get; set; } + + /// Remove the stored password on save. + public bool ClearPassword { get; set; } + + /// How long the upstream's answers are reused, in seconds (0 = ask every time). + public int MetadataTtlSeconds { get; set; } = 600; + + /// How long "not found" is remembered, in seconds (0 = ask every time). + public int NegativeTtlSeconds { get; set; } = 60; + + /// The download timeout in seconds. + public int DownloadTimeoutSeconds { get; set; } = 600; + + /// Never contact the upstream. + public bool Offline { get; set; } + + /// Keep what is fetched (off = pass-through). + public bool StoreLocally { get; set; } = true; + + /// For display: whether a password is stored. + public bool HasPassword { get; set; } + + /// For display: URL, protocol and timeout are fixed because Mirror:* sets them. + public bool EndpointFromMirror { get; set; } + + /// The settings these fields describe. + public RemoteRepositorySettings ToSettings() => new() + { + Url = Url?.Trim(), + Protocol = Protocol, + Username = string.IsNullOrWhiteSpace(Username) ? null : Username.Trim(), + Password = string.IsNullOrEmpty(Password) ? null : Password, + MetadataTtlSeconds = MetadataTtlSeconds, + NegativeTtlSeconds = NegativeTtlSeconds, + DownloadTimeoutSeconds = DownloadTimeoutSeconds, + Offline = Offline, + StoreLocally = StoreLocally, + }; + + /// The fields for an existing remote repository. + public static RemoteFormModel From(RemoteRepositoryDetail detail) => new() + { + Format = detail.Repository.Format, + Url = detail.Settings.Url, + Protocol = detail.Settings.Protocol, + Username = detail.Settings.Username, + MetadataTtlSeconds = detail.Settings.MetadataTtlSeconds, + NegativeTtlSeconds = detail.Settings.NegativeTtlSeconds, + DownloadTimeoutSeconds = detail.Settings.DownloadTimeoutSeconds, + Offline = detail.Settings.Offline, + StoreLocally = detail.Settings.StoreLocally, + HasPassword = detail.HasPassword, + EndpointFromMirror = detail.IsMirror, + }; +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoriesViewModel.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoriesViewModel.cs new file mode 100644 index 000000000..f3524986f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoriesViewModel.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// +/// What the repositories screen (/admin/repositories) shows: the repositories with their feed addresses, the list filter and +/// the create forms. The posted fields of the create forms (, ) live here too, so a refused +/// creation shows again what was typed (the typed upstream password excepted: it is never sent back). +/// +public sealed class RepositoriesViewModel : ConfirmationModel, IFlashMessage +{ + private IReadOnlyDictionary _feeds = new Dictionary(); + private IReadOnlyDictionary _bases = new Dictionary(); + private IReadOnlyDictionary> _links = new Dictionary>(); + + /// The name for the repository to create. + public string? Name { get; set; } + + /// The upstream settings for the remote repository to create. + public RemoteFormModel Remote { get; set; } = new(); + + /// The repositories. + public IReadOnlyList Repositories { get; internal set; } = Array.Empty(); + + /// Whether the database can hold more than the default repository. + public bool CanCreate { get; internal set; } + + /// + public string? Message { get; set; } + + /// Why the last action was refused. + public string? Error { get; internal set; } + + /// The format to keep selected after a refused creation. + public string? Format { get; internal set; } + + /// The format the list is narrowed to (?format=), or null. + public string? FilterFormat { get; internal set; } + + /// The kind the list is narrowed to (?kind=), or null. + public string? FilterKind { get; internal set; } + + /// The name fragment the list is narrowed to (?q=), or null. + public string? FilterName { get; internal set; } + + /// Every format this server knows, for the list filter. + public IReadOnlyList AllFormats { get; internal set; } = Array.Empty(); + + /// The formats a remote repository can be created for. + public IReadOnlyList RemoteFormats { get; internal set; } = Array.Empty(); + + /// The formats a virtual repository can be created for. + public IReadOnlyList VirtualFormats { get; internal set; } = Array.Empty(); + + /// The formats other than NuGet that can be created here, with their form fields. + public IReadOnlyList OtherFormats { get; internal set; } = Array.Empty(); + + /// The virtual repositories that have a deploy repository, so take uploads (a remote one takes none). + public IReadOnlyList Deployable { get; internal set; } = Array.Empty(); + + /// The feed address of each repository, by repository name. + public IReadOnlyDictionary Feeds { get => _feeds; internal set => _feeds = value; } + + /// The base address of each repository (where its format's routes start, ends with a slash), by repository name. + public IReadOnlyDictionary BaseUrls { get => _bases; internal set => _bases = value; } + + /// The links its format contributes for each repository (browse, upload...), without the upload link where it takes none, by repository name. + public IReadOnlyDictionary> Links { get => _links; internal set => _links = value; } + + /// The feed address of , by its format's . + public string FeedUrl(RepositorySummary repository) => _feeds.TryGetValue(repository.Name, out var url) ? url : string.Empty; + + /// The base address of , which a link given by a path () is appended to. + public string BaseUrl(RepositorySummary repository) => _bases.TryGetValue(repository.Name, out var url) ? url : string.Empty; + + /// The links its format contributes for (browse, upload...), without the upload link where it takes none. + public IReadOnlyList LinksOf(RepositorySummary repository) + => _links.TryGetValue(repository.Name, out var links) ? links : Array.Empty(); +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoryAccessRow.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoryAccessRow.cs new file mode 100644 index 000000000..529aefbd2 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoryAccessRow.cs @@ -0,0 +1,8 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// One repository with what a user may do there and the grants behind it (the account and user pages). +/// The repository. +/// What the user may do there and which grants say so. +public sealed record RepositoryAccessRow(RepositoryInfo Repository, AccessExplanation Explanation); diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoryCreateForm.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoryCreateForm.cs new file mode 100644 index 000000000..17d2cb9e7 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoryCreateForm.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// +/// The body of the create forms of the repositories screen (POST /api/ui/admin/repositories and its create/... handlers). Which fields +/// a handler reads is stated on its use case method; the others are ignored. +/// +public sealed class RepositoryCreateForm +{ + /// The name of the repository to create. + public string? Name { get; set; } + + /// The format (Npm, Maven, Docker...); blank is NuGet where a format may be omitted. + public string? Format { get; set; } + + /// The upstream of a remote repository. + public RemoteFormModel Remote { get; set; } = new(); + + /// + /// Whether requests without credentials may read the repository. Null: the default (a local or virtual repository is readable by anyone; a remote + /// one only when it has no credentials). + /// + public bool? AnonymousRead { get; set; } + + /// The administrator's password (creating a remote repository asks for it). + public string? Password { get; set; } + + /// The format's own create fields ( to value) of a local repository of a format other than NuGet. + public IDictionary? Fields { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoryDeleteViewModel.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoryDeleteViewModel.cs new file mode 100644 index 000000000..186664660 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoryDeleteViewModel.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// What the delete-repository screen (/admin/repositories/{name}/delete) shows. +public sealed class RepositoryDeleteViewModel +{ + /// The repository's name (route). + public string? Name { get; set; } + + /// The repository. + public RepositorySummary? Repository { get; internal set; } + + /// The virtual repositories that list this repository as a member (the deletion is refused while there are any). + public IReadOnlyList ReferencedBy { get; internal set; } = new List(); + + /// Why the deletion was refused. + public string? Error { get; internal set; } +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditForm.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditForm.cs new file mode 100644 index 000000000..83b1b2db6 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditForm.cs @@ -0,0 +1,25 @@ +namespace BaGet.Identity.Application.Models.Repositories; + +/// +/// The fields the repository screen's forms post (every handler binds the same set). The upstream fields come with the Remote. prefix. +/// +public sealed class RepositoryEditForm +{ + /// Whether requests without credentials may read the repository. + public bool AnonymousRead { get; set; } + + /// The upstream fields of a remote repository. + public RemoteFormModel Remote { get; set; } = new(); + + /// The package id to resolve in the preview. + public string? PreviewPackageId { get; set; } + + /// The package version to resolve in the preview. + public string? PreviewVersion { get; set; } + + /// The package id to purge from the cache. + public string? PackageId { get; set; } + + /// The version to purge (blank = every version). + public string? PackageVersion { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditRequest.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditRequest.cs new file mode 100644 index 000000000..1b2375317 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditRequest.cs @@ -0,0 +1,47 @@ +namespace BaGet.Identity.Application.Models.Repositories; + +/// +/// The body of every action of the repository screen (/api/ui/admin/repositories/{name}/...), the JSON twin of what the page's forms post. Which fields +/// an action reads is stated on its use case method; the others are ignored. +/// +public sealed class RepositoryEditRequest +{ + /// Whether requests without credentials may read the repository. + public bool AnonymousRead { get; set; } + + /// The upstream fields of a remote repository. + public RemoteFormModel Remote { get; set; } = new(); + + /// The package id to resolve in the preview. + public string? PreviewPackageId { get; set; } + + /// The package version to resolve in the preview. + public string? PreviewVersion { get; set; } + + /// The package id to purge from the cache. + public string? PackageId { get; set; } + + /// The version to purge (blank = every version). + public string? PackageVersion { get; set; } + + /// The administrator's password (saving, testing and purging a remote repository ask for it). + public string? Password { get; set; } + + /// The member to add, remove or move. + public string? Member { get; set; } + + /// up or down. + public string? Direction { get; set; } + + /// The member that receives uploads (blank: none). + public string? Deploy { get; set; } + + /// The versions a Maven repository accepts (Releases, Snapshots, Both). + public string? Policy { get; set; } + + /// Whether a Maven release may be redeployed (Yes/No). + public string? Redeploy { get; set; } + + /// How many snapshot builds a Maven repository keeps. + public string? SnapshotBuilds { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditViewModel.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditViewModel.cs new file mode 100644 index 000000000..177c0d212 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoryEditViewModel.cs @@ -0,0 +1,93 @@ +using BaGet.Identity.Application.Screens; +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// +/// What the repository screen (/admin/repositories/{name}) shows: the repository, its access summary and, by kind, its +/// upstream and cache (remote), members and preview (virtual) or Maven settings. The posted fields (anonymous read, upstream, preview +/// and purge inputs) live here too, so a refused action shows again what was typed. +/// +public sealed class RepositoryEditViewModel : ConfirmationModel, IFlashMessage +{ + /// The repository's name (route). + public string? Name { get; set; } + + /// Whether requests without credentials may read the repository. + public bool AnonymousRead { get; set; } + + /// The repository. + public RepositorySummary? Repository { get; internal set; } + + /// The upstream fields of a remote repository. + public RemoteFormModel Remote { get; set; } = new(); + + /// The remote repository's upstream, null for the other kinds. + public RemoteRepositoryDetail? RemoteDetail { get; internal set; } + + /// The settings of a local Maven repository, null for the other repositories. + public MavenRepositorySettings? MavenSettings { get; internal set; } + + /// What a remote repository stores and remembers. + public RemoteCacheOverview? Cache { get; internal set; } + + /// The virtual repository's members and deploy repository, null for the other kinds. + public VirtualRepositoryDetail? VirtualDetail { get; internal set; } + + /// The repositories that can still be added to a virtual repository. + public IReadOnlyList MemberCandidates { get; internal set; } = Array.Empty(); + + /// The virtual repositories that list this repository as a member. + public IReadOnlyList ReferencedBy { get; internal set; } = Array.Empty(); + + /// The package id to resolve in the preview. + public string? PreviewPackageId { get; set; } + + /// The package version to resolve in the preview. + public string? PreviewVersion { get; set; } + + /// Where the previewed package version would come from. + public ResolutionPreview? Preview { get; internal set; } + + /// The outcome of "Test connection". + public RemoteConnectionResult? TestResult { get; internal set; } + + /// + public string? Message { get; set; } + + /// Why the last action was refused. + public string? Error { get; internal set; } + + /// The package id to purge from the cache. + public string? PackageId { get; set; } + + /// The version to purge (blank = every version). + public string? PackageVersion { get; set; } + + /// Who effectively holds each action in the repository; null for the default repository when the database has no access model. + public RepositoryAccessSummary? Access { get; internal set; } + + /// The screen of the repository's format that lists its packages (Home/Index for NuGet, NpmBrowse/Packages for npm). + public ScreenRef BrowseScreen { get; internal set; } = ScreenCatalog.Index; + + /// The repository's feed address. + public string FeedUrl { get; internal set; } = string.Empty; + + /// For the default repository: the remote repository it fetches through, when Mirror:Enabled. + public RemoteRepositoryDetail? MirrorRepository { get; internal set; } + + /// Whether Mirror:Enabled makes the default repository fetch through . + public bool MirrorActive { get; internal set; } + + /// The name of what a package is called in this repository's format (shown in the labels). + public string PackageWord => Repository?.Format switch { RepositoryFormat.Npm => "package name", RepositoryFormat.Maven => "artifact (group:artifact)", RepositoryFormat.Docker => "image name", _ => "package id" }; + + /// What the "version" of a package is called in this repository's format (a Docker image has a tag or a digest). + public string VersionWord => Repository?.Format == RepositoryFormat.Docker ? "Tag or digest" : "Version"; + + /// The label of the field that names a package (a Docker image is an image name). + public string PackageLabel => Repository?.Format switch { RepositoryFormat.Npm => "Package name", RepositoryFormat.Maven => "Artifact (group:artifact)", RepositoryFormat.Docker => "Image name", _ => "Package id" }; +} diff --git a/src/BaGet.Identity.Application/Models/Repositories/RepositoryFormatChoice.cs b/src/BaGet.Identity.Application/Models/Repositories/RepositoryFormatChoice.cs new file mode 100644 index 000000000..5bfb2cc04 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Repositories/RepositoryFormatChoice.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Repositories; + +/// A package format a repository can be created for, with the extra fields its create form asks (the JSON form of an ). +/// The format. +/// Its name for people (npm, Maven). +/// What the administrator fills in to create a local repository of it, besides the name. +public sealed record RepositoryFormatChoice(RepositoryFormat Format, string DisplayName, IReadOnlyList CreateFields) +{ + /// The choice for . + public static RepositoryFormatChoice Of(IFormatModule module) + => new(module.Format, module.DisplayName, module.CreateFields); +} diff --git a/src/BaGet.Identity.Application/Models/Session/AntiforgeryTokenModel.cs b/src/BaGet.Identity.Application/Models/Session/AntiforgeryTokenModel.cs new file mode 100644 index 000000000..dbfdcf231 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/AntiforgeryTokenModel.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.Models.Session; + +/// What GET /api/ui/antiforgery answers: the request token to send with a cookie session. +public class AntiforgeryTokenModel +{ + /// The header to send the token in (X-XSRF-TOKEN). + public string? HeaderName { get; set; } + + /// The request token. It is bound to the signed-in user: ask again after signing in or out. + public string? RequestToken { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionCookieForm.cs b/src/BaGet.Identity.Application/Models/Session/SessionCookieForm.cs new file mode 100644 index 000000000..9d4eadc4a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionCookieForm.cs @@ -0,0 +1,23 @@ +namespace BaGet.Identity.Application.Models.Session; + +/// +/// The body of POST /api/ui/session/cookie (a same-origin client that signs in with the cookie): the password step (, +/// ), or, when the account has two-factor, the second step ( with or ). +/// +public class SessionCookieForm +{ + /// The username (password step). + public string? UserName { get; set; } + + /// The password (password step). + public string? Password { get; set; } + + /// The twoFactorTicket of the password step (second step). + public string? Ticket { get; set; } + + /// A code of the authenticator app (second step). + public string? Code { get; set; } + + /// A recovery code (second step). + public string? RecoveryCode { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionExchangeForm.cs b/src/BaGet.Identity.Application/Models/Session/SessionExchangeForm.cs new file mode 100644 index 000000000..bc0b879fc --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionExchangeForm.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Session; + +/// The body of POST /api/ui/session/exchange. +public class SessionExchangeForm +{ + /// The exchange_token of the external sign-in's redirect. + [Required] + public string? ExchangeToken { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionModel.cs b/src/BaGet.Identity.Application/Models/Session/SessionModel.cs new file mode 100644 index 000000000..b43a82790 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionModel.cs @@ -0,0 +1,40 @@ +using System; + +namespace BaGet.Identity.Application.Models.Session; + +/// What /api/ui/session answers: a pair of tokens, or the ticket for the second factor of a sign-in. +public class SessionModel +{ + /// Authenticates requests to /api/ui (Authorization: Bearer); null while . + public string? AccessToken { get; set; } + + /// When the access token stops being accepted (UTC). + public DateTime? ExpiresAt { get; set; } + + /// Exchanged for a new pair at /api/ui/session/refresh; each refresh returns a new one and the old one stays valid until it expires. + public string? RefreshToken { get; set; } + + /// When the refresh token stops being accepted (UTC). + public DateTime? RefreshExpiresAt { get; set; } + + /// The signed-in user's name. + public string? UserName { get; set; } + + /// The password was right but the account asks for a second factor: post the and a code to /api/ui/session/two-factor or /recovery-code. + public bool TwoFactorRequired { get; set; } + + /// Proves the password step; valid for five minutes, and useless without a code. + public string? TwoFactorTicket { get; set; } + + /// When the ticket stops being accepted (UTC). + public DateTime? TwoFactorTicketExpiresAt { get; set; } + + /// External sign-in only: a single-use-in-practice token (60 seconds) to exchange for the real ones at POST /api/ui/session/exchange. + public string? ExchangeToken { get; set; } + + /// When the exchange token stops being accepted (UTC). + public DateTime? ExchangeExpiresAt { get; set; } + + /// Something to tell the user when there are no tokens yet (external sign-in: the account was created and awaits approval or a confirmed email address). + public string? Notice { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionProvidersModel.cs b/src/BaGet.Identity.Application/Models/Session/SessionProvidersModel.cs new file mode 100644 index 000000000..4a690cab6 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionProvidersModel.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using BaGet.Identity.Application.Models.Account; + +namespace BaGet.Identity.Application.Models.Session; + +/// The external sign-in providers a client can offer (GET /api/ui/session/providers): one button each, started at /api/ui/session/external/{id}. +public sealed class SessionProvidersModel +{ + /// The configured providers, empty when there is none. + public IReadOnlyList Providers { get; set; } = new List(); +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionRecoveryCodeForm.cs b/src/BaGet.Identity.Application/Models/Session/SessionRecoveryCodeForm.cs new file mode 100644 index 000000000..6153b8ec8 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionRecoveryCodeForm.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Session; + +/// The body of POST /api/ui/session/recovery-code: the ticket of the password step and one of the account's recovery codes (each works once). +public class SessionRecoveryCodeForm +{ + /// The twoFactorTicket the password step answered. + [Required] + public string? Ticket { get; set; } + + /// A recovery code. + [Required] + public string? RecoveryCode { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionRefreshForm.cs b/src/BaGet.Identity.Application/Models/Session/SessionRefreshForm.cs new file mode 100644 index 000000000..d7d70637a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionRefreshForm.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Session; + +/// The body of POST /api/ui/session/refresh. +public class SessionRefreshForm +{ + /// The refreshToken of the last answer. + [Required] + public string? RefreshToken { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionSignInForm.cs b/src/BaGet.Identity.Application/Models/Session/SessionSignInForm.cs new file mode 100644 index 000000000..2d2d85fc8 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionSignInForm.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Session; + +/// The body of POST /api/ui/session: the same credentials as the sign-in page. +public class SessionSignInForm +{ + /// The user name. + [Required] + public string? UserName { get; set; } + + /// The password. + [Required] + [DataType(DataType.Password)] + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionSignOutForm.cs b/src/BaGet.Identity.Application/Models/Session/SessionSignOutForm.cs new file mode 100644 index 000000000..d437ff53b --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionSignOutForm.cs @@ -0,0 +1,14 @@ +namespace BaGet.Identity.Application.Models.Session; + +/// The body of POST /api/ui/session/sign-out. +public class SessionSignOutForm +{ + /// The refresh token to end the session with when the request carries no access token. + public string? RefreshToken { get; set; } + + /// + /// Also ends every other session of the account (cookie sessions and tokens) by changing its security stamp. Without it nothing is + /// revoked: the tokens are stateless, so the client simply forgets them, and they expire. + /// + public bool Everywhere { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Session/SessionTwoFactorForm.cs b/src/BaGet.Identity.Application/Models/Session/SessionTwoFactorForm.cs new file mode 100644 index 000000000..1922eced1 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Session/SessionTwoFactorForm.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; + +namespace BaGet.Identity.Application.Models.Session; + +/// The body of POST /api/ui/session/two-factor: the ticket of the password step and a code of the authenticator app. +public class SessionTwoFactorForm +{ + /// The twoFactorTicket the password step answered. + [Required] + public string? Ticket { get; set; } + + /// The code from the authenticator app. + [Required] + public string? Code { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Settings/AdminSettingsViewModel.cs b/src/BaGet.Identity.Application/Models/Settings/AdminSettingsViewModel.cs new file mode 100644 index 000000000..25539e408 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/AdminSettingsViewModel.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Serialization; +using BaGet.Core; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Settings; + +/// What the server settings screen (/admin/settings) shows: every registered setting by section and the state of the last save. +public sealed class AdminSettingsViewModel : ConfirmationModel, IFlashMessage +{ + private IReadOnlyDictionary _ids = new Dictionary(); + + /// The settings grouped by section; the top-level keys come first, under the empty key. Not serialised: is the same with the keys. + [JsonIgnore] + public IReadOnlyList> Sections { get; internal set; } = Array.Empty>(); + + /// The same sections as , each with its key and DOM id, as the JSON carries them. + public IReadOnlyList SectionList + => Sections.Select(group => new SettingsSection(group.Key, SectionId(group.Key), group.ToList())).ToList(); + + /// The file the settings are saved to. + public string? OverridesPath { get; internal set; } + + /// The keys changed since startup that only apply after a restart. + public IReadOnlyList PendingRestart { get; internal set; } = Array.Empty(); + + /// Why the last save was refused. + public IReadOnlyList Errors { get; internal set; } = Array.Empty(); + + /// The section the belong to. + public string? ErrorSection { get; internal set; } + + /// The per-source log levels (Serilog:MinimumLevel:Override) shown under the Serilog section. + public IReadOnlyList LogLevels { get; internal set; } = Array.Empty(); + + /// The level names offered for a source. + public IReadOnlyList LogLevelNames => LogLevelOverrides.Levels; + + /// The named OpenID Connect providers (Accounts:OpenIdConnectProviders) shown in the "Sign-in providers" panel of the Accounts section. No secret is carried. + public IReadOnlyList SignInProviders { get; internal set; } = Array.Empty(); + + /// Why the overrides file could not be read, or null. + public string? LoadError { get; internal set; } + + /// The state of each telemetry signal for the Telemetry section, or null when the host exports no telemetry. + public IReadOnlyList? TelemetrySignals { get; internal set; } + + /// + /// True when this host exports telemetry (registers ). When false the Telemetry + /// section stays editable (the settings file may be shared with a host that does export) but a note says it has no effect here. + /// + public bool HostExportsTelemetry => TelemetrySignals != null; + + /// The outcome of the last "Test connection", or null. Shown in the Telemetry section; never saved. + public TelemetryTestOutcome? TelemetryTest { get; internal set; } + + /// + /// Whether the running database is relational, so a change of database can copy the data (the "Copy all data" option of the + /// Database section). + /// + public bool CanCopyDatabase { get; internal set; } + + /// The Database:Type values a copy can target; the option is hidden for any other type. + public IReadOnlyList CopyTargetTypes { get; internal set; } = Array.Empty(); + + /// The state of the database copy, if one was requested since startup. + public DatabaseCopyStatus CopyStatus { get; internal set; } = null!; + + /// + /// The DOM id (slug) of the section shown; every other section is rendered hidden. Chosen by the workflow: the failed + /// section, else the Telemetry section after "Test connection", else the ?section= value, else the first section. The URL + /// fragment is only known to the browser, so the page's script applies it on load unless . + /// + public string SelectedId { get; internal set; } = string.Empty; + + /// True when the server picked the section for a reason the URL fragment must not override (a failed save, a connection test). + public bool SelectionLocked { get; internal set; } + + /// + public string? Message { get; set; } + + internal void SetIds(IReadOnlyDictionary ids) => _ids = ids; + + internal IEnumerable Ids => _ids.Values; + + internal bool TryGetId(string key, out string id) => _ids.TryGetValue(key, out id!); + + /// + /// The stable DOM id of a section: general for the empty key, else the key with every character other than letters, + /// digits, - and _ replaced by - (made unique, ignoring case, if two keys collapse to the same id). Used by + /// the nav, the form, the fragment and the redirect after a save. + /// + public string SectionId(string key) => _ids.TryGetValue(key ?? string.Empty, out var id) ? id : BuildId(key ?? string.Empty); + + internal static string BuildId(string key) + { + if (key.Length == 0) return "general"; + + var chars = key.Select(c => char.IsAsciiLetterOrDigit(c) || c == '-' || c == '_' ? c : '-').ToArray(); + return new string(chars); + } +} diff --git a/src/BaGet.Identity.Application/Models/Settings/ClusterViewModel.cs b/src/BaGet.Identity.Application/Models/Settings/ClusterViewModel.cs new file mode 100644 index 000000000..9c77426aa --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/ClusterViewModel.cs @@ -0,0 +1,10 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Settings; + +/// What the cluster screen (/admin/cluster) shows: nodes, leases, shared state and health. +public sealed class ClusterViewModel +{ + /// The status read for the screen. + public ClusterStatus Status { get; internal set; } = null!; +} diff --git a/src/BaGet.Identity.Application/Models/Settings/DatabaseCopyStatusView.cs b/src/BaGet.Identity.Application/Models/Settings/DatabaseCopyStatusView.cs new file mode 100644 index 000000000..0528279b9 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/DatabaseCopyStatusView.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Settings; + +/// +/// The progress of the database copy as the Settings page polls it (?handler=CopyStatus): the properties are those the page's script reads +/// (phase as the phase name, active, finished, succeeded, restartRequired ...). Holds no connection string. +/// +/// The stage, by name. +/// A copy is queued or running. +/// The copy ended, either way. +/// The copy succeeded. +/// The settings are saved and the process must restart to use them. +/// The table being copied, or null. +/// Rows of the table copied so far. +/// Rows of the table in the source. +/// Tables completed. +/// Tables to copy. +/// Rows copied over all tables. +/// Rows to copy over all tables. +/// A one-line summary of the current state. +/// Why the copy was refused or failed. +public sealed record DatabaseCopyStatusView( + string Phase, + bool Active, + bool Finished, + bool Succeeded, + bool RestartRequired, + string? Table, + long TableRowsCopied, + long TableRowsTotal, + int TablesDone, + int TablesTotal, + long RowsCopied, + long RowsTotal, + string? Message, + IReadOnlyList Errors) +{ + /// The page's view of . + public static DatabaseCopyStatusView Of(DatabaseCopyStatus status) + => new( + status.Phase.ToString(), + status.IsActive, + status.IsFinished, + status.Phase == DatabaseCopyPhase.Succeeded, + status.RestartRequired, + status.Table, + status.TableRowsCopied, + status.TableRowsTotal, + status.TablesDone, + status.TablesTotal, + status.RowsCopied, + status.RowsTotal, + status.Message, + status.Errors); +} diff --git a/src/BaGet.Identity.Application/Models/Settings/LogLevelForm.cs b/src/BaGet.Identity.Application/Models/Settings/LogLevelForm.cs new file mode 100644 index 000000000..ffc3a168b --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/LogLevelForm.cs @@ -0,0 +1,7 @@ +namespace BaGet.Identity.Application.Models.Settings; + +/// Setting or removing the lowest level logged for one source. +/// The source (a namespace prefix). +/// The level (ignored when removing). +/// The administrator's password. +public sealed record LogLevelForm(string? Source, string? Level, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Settings/RemoveSignInProviderForm.cs b/src/BaGet.Identity.Application/Models/Settings/RemoveSignInProviderForm.cs new file mode 100644 index 000000000..6ec92e553 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/RemoveSignInProviderForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Settings; + +/// Removing a named OpenID Connect provider saved on the Settings screen. +/// The provider id. +/// The administrator's password. +public sealed record RemoveSignInProviderForm(string? Id, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Settings/SettingsSection.cs b/src/BaGet.Identity.Application/Models/Settings/SettingsSection.cs new file mode 100644 index 000000000..a5148dd45 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/SettingsSection.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.Models.Settings; + +/// One section of the settings screen: its key (empty for the top-level keys), its DOM id and its settings. +/// The section's key; empty for the settings that sit at the top level. +/// The stable DOM id (). +/// The settings of the section; a sensitive one never carries its value. +public sealed record SettingsSection(string Key, string Id, IReadOnlyList Settings); diff --git a/src/BaGet.Identity.Application/Models/Settings/SettingsViewModel.cs b/src/BaGet.Identity.Application/Models/Settings/SettingsViewModel.cs new file mode 100644 index 000000000..e6356b9aa --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/SettingsViewModel.cs @@ -0,0 +1,38 @@ +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.Models.Settings; + +/// What the account settings screen shows (change email, change password, delete the account). +public sealed class SettingsViewModel +{ + /// The account's email address. + public string? Email { get; set; } + + /// Whether the address is confirmed. + public bool EmailConfirmed { get; set; } + + /// Whether the account has a password (else it signs in through a provider). + public bool HasPassword { get; set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; set; } + + /// Whether an external provider is configured to sign in again with. + public bool CanReauthenticate { get; set; } + + /// Whether mail is configured. + public bool CanSendEmail { get; set; } + + /// Every configured external provider with whether this account has linked a login at it (empty when there is none). + public System.Collections.Generic.IReadOnlyList ExternalLogins { get; set; } + = System.Array.Empty(); + + /// The success message to show. + public string? Message { get; set; } + + /// The refusal to show. + public string? Error { get; set; } + + /// Why the account cannot be deleted yet, when it cannot. + public DeletionBlockers? Blockers { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Settings/SignInProviderForm.cs b/src/BaGet.Identity.Application/Models/Settings/SignInProviderForm.cs new file mode 100644 index 000000000..0de7a9bb0 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/SignInProviderForm.cs @@ -0,0 +1,54 @@ +namespace BaGet.Identity.Application.Models.Settings; + +/// +/// What the "Sign-in providers" panel of the Settings screen posts to add or edit a named OpenID Connect provider (the body of +/// POST /api/ui/admin/settings/save-provider). The id is the key and cannot change once created; a blank secret keeps the saved one. +/// and are one name=value per line. +/// +public sealed class SignInProviderForm +{ + /// The provider id (lower-case letters, digits and -, 1 to 32). + public string? Id { get; set; } + + /// The name on the sign-in button. + public string? DisplayName { get; set; } + + /// The issuer address. + public string? Authority { get; set; } + + /// The client id. + public string? ClientId { get; set; } + + /// The client secret; blank keeps the saved one. Never sent back. + public string? ClientSecret { get; set; } + + /// Extra scopes, separated by spaces or semicolons. + public string? Scopes { get; set; } + + /// Extra authorization request parameters, one name=value per line. + public string? Parameters { get; set; } + + /// The claim holding the user name. + public string? UserNameClaim { get; set; } + + /// The claim holding the email address. + public string? EmailClaim { get; set; } + + /// The claim saying the address is verified. + public string? EmailVerifiedClaim { get; set; } + + /// The claim that decides the administrator flag (the provider becomes authoritative for it). + public string? AdministratorClaim { get; set; } + + /// The value of that claim that makes a user an administrator. + public string? AdministratorValue { get; set; } + + /// The claim holding the user's groups. + public string? GroupClaim { get; set; } + + /// Claim value to BaGet group, one value=group per line. + public string? GroupMappings { get; set; } + + /// The administrator's password, asked again. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Settings/SignInProviderView.cs b/src/BaGet.Identity.Application/Models/Settings/SignInProviderView.cs new file mode 100644 index 000000000..c1079c85a --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Settings/SignInProviderView.cs @@ -0,0 +1,56 @@ +namespace BaGet.Identity.Application.Models.Settings; + +/// A named OpenID Connect provider as the Settings screen lists it. The client secret is never carried, only whether one is set. +public sealed class SignInProviderView +{ + /// The provider id. + public string Id { get; set; } = string.Empty; + + /// The name on the sign-in button. + public string? DisplayName { get; set; } + + /// The issuer address. + public string? Authority { get; set; } + + /// The client id. + public string? ClientId { get; set; } + + /// Whether a client secret is set. + public bool HasSecret { get; set; } + + /// Extra scopes. + public string? Scopes { get; set; } + + /// Extra request parameters, one name=value per line. + public string? Parameters { get; set; } + + /// The claim holding the user name. + public string? UserNameClaim { get; set; } + + /// The claim holding the email address. + public string? EmailClaim { get; set; } + + /// The claim saying the address is verified. + public string? EmailVerifiedClaim { get; set; } + + /// The claim that decides the administrator flag. + public string? AdministratorClaim { get; set; } + + /// The value of that claim that makes a user an administrator. + public string? AdministratorValue { get; set; } + + /// The claim holding the user's groups. + public string? GroupClaim { get; set; } + + /// Claim value to BaGet group, one value=group per line. + public string? GroupMappings { get; set; } + + /// Whether the overrides file holds it, so this screen can edit or remove it; false when a configuration file or the environment sets it. + public bool Editable { get; set; } + + /// Whether the running server has a handler for it (false: saved or removed since startup). + public bool Active { get; set; } + + /// Whether what is saved differs from what the running server uses, so a restart is needed. + public bool PendingRestart { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Shared/AccessUnavailableViewModel.cs b/src/BaGet.Identity.Application/Models/Shared/AccessUnavailableViewModel.cs new file mode 100644 index 000000000..96869d050 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Shared/AccessUnavailableViewModel.cs @@ -0,0 +1,10 @@ +namespace BaGet.Identity.Application.Models.Shared; + +/// What the "access control unavailable" screen (/admin/access-unavailable) says: why, as the JSON carries it (the page has fixed text). +/// Why the access screens are not available. +public sealed record AccessUnavailableViewModel(string Reason) +{ + /// The standard reason. + public static AccessUnavailableViewModel Standard { get; } = new( + "The configured database has no tables for groups, permission targets and projects. Use SQLite, SQL Server, PostgreSQL or MySQL to manage access here."); +} diff --git a/src/BaGet.Identity.Application/Models/Shared/ConfirmPasswordView.cs b/src/BaGet.Identity.Application/Models/Shared/ConfirmPasswordView.cs new file mode 100644 index 000000000..74020d167 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Shared/ConfirmPasswordView.cs @@ -0,0 +1,9 @@ +namespace BaGet.Identity.Application.Models.Shared; + +/// What the password confirmation partial needs. +/// The input's id. +/// Whether the administrator has a password to type. +/// For an account without a password: it signed in again a moment ago. +/// Whether a provider is available to sign in again with. +/// The page to come back to after signing in again. +public record ConfirmPasswordView(string Id, bool HasPassword, bool Reauthenticated, bool CanReauthenticate, string ReturnPage); diff --git a/src/BaGet.Identity.Application/Models/Shared/ConfirmationModel.cs b/src/BaGet.Identity.Application/Models/Shared/ConfirmationModel.cs new file mode 100644 index 000000000..86ed5b18f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Shared/ConfirmationModel.cs @@ -0,0 +1,24 @@ +namespace BaGet.Identity.Application.Models.Shared; + +/// +/// What a screen that asks the administrator's password again needs to render the confirmation partial: whether there is a +/// password to type, or else a recent provider sign-in. Shared base of the view models of the admin screens. +/// +public abstract class ConfirmationModel +{ + /// Whether the signed in administrator has a password to confirm with. + public bool HasPassword { get; internal set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; internal set; } + + /// Whether an external provider is available to sign in again with. + public bool CanReauthenticate { get; internal set; } + + /// The page to come back to after signing in again (the model of the confirmation partial). + public string ReturnPage { get; internal set; } = string.Empty; + + /// The model of the password confirmation partial, with for the input. + public ConfirmPasswordView Confirmation(string id) + => new(id, HasPassword, Reauthenticated, CanReauthenticate, ReturnPage); +} diff --git a/src/BaGet.Identity.Application/Models/Shared/IFlashMessage.cs b/src/BaGet.Identity.Application/Models/Shared/IFlashMessage.cs new file mode 100644 index 000000000..910448de7 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Shared/IFlashMessage.cs @@ -0,0 +1,10 @@ +namespace BaGet.Identity.Application.Models.Shared; + +/// +/// A view model that carries the outcome of the last action across a redirect ([TempData] Message). AdminControllerBase.Flash moves the value to and from TempData. +/// +public interface IFlashMessage +{ + /// Outcome of the last action. + string? Message { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Shared/IFlashModel.cs b/src/BaGet.Identity.Application/Models/Shared/IFlashModel.cs new file mode 100644 index 000000000..f78b94726 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Shared/IFlashModel.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Shared; + +/// A that also carries why the last action was refused ([TempData] Error). +public interface IFlashModel : IFlashMessage +{ + /// Why the last action was refused. + string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Shared/PasswordForm.cs b/src/BaGet.Identity.Application/Models/Shared/PasswordForm.cs new file mode 100644 index 000000000..b60f016a0 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Shared/PasswordForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Models.Shared; + +// The bodies of the administration screens' writes. A page posts them as form fields (the view controllers bind the same names and build these), +// the JSON API takes them as the request body; the use cases never see how they arrived. + +/// A write that only asks the administrator's password again (approve an account, delete an organization). +/// The administrator's password. +public sealed record PasswordForm(string? Password); diff --git a/src/BaGet.Identity.Application/Models/Shared/ScreenLink.cs b/src/BaGet.Identity.Application/Models/Shared/ScreenLink.cs new file mode 100644 index 000000000..284f82608 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Shared/ScreenLink.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; +using BaGet.Identity.Application.Screens; + +namespace BaGet.Identity.Application.Models.Shared; + +/// A screen as a client links to it: the screen (controller and action) and its route values; the view turns it into an address. +/// The screen (). +/// Route values; a null value (repo of the default repository) is kept. +public sealed record ScreenLink(ScreenRef Screen, IReadOnlyDictionary RouteValues); diff --git a/src/BaGet.Identity.Application/Models/Users/DeleteUserViewModel.cs b/src/BaGet.Identity.Application/Models/Users/DeleteUserViewModel.cs new file mode 100644 index 000000000..c541a314f --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/DeleteUserViewModel.cs @@ -0,0 +1,29 @@ +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.Models.Users; + +/// What the delete-user screen (/admin/users/{name}/delete) shows: what the deletion would remove or change. +public sealed class DeleteUserViewModel : ConfirmationModel +{ + /// Shown when permanent package deletion is asked for in read-only mode. + public const string ReadOnlyMessage = "The server is read-only, so packages cannot be deleted. Leave them without owners, or turn read-only mode off."; + + /// The user to delete (route). + public string? Name { get; set; } + + /// "keep" (default) or "delete": what to do with the IDs only this user owns. + public string SoleOwned { get; set; } = "keep"; + + /// What the deletion would remove or change. + public AdminDeletionPreview? Preview { get; internal set; } + + /// Whether the user is the server's only administrator. + public bool LastAdministrator { get; internal set; } + + /// Read-only mode: the account may go, but package files are not deleted. + public bool IsReadOnlyMode { get; internal set; } + + /// Why the deletion was refused. + public string? Error { get; internal set; } +} diff --git a/src/BaGet.Identity.Application/Models/Users/UserDeletionForm.cs b/src/BaGet.Identity.Application/Models/Users/UserDeletionForm.cs new file mode 100644 index 000000000..7ba3aada9 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/UserDeletionForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Users; + +/// Deleting an account. +/// "keep" (default) or "delete": what to do with the package IDs only this user owns. +/// The administrator's password. +public sealed record UserDeletionForm(string? SoleOwned, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Users/UserDetailViewModel.cs b/src/BaGet.Identity.Application/Models/Users/UserDetailViewModel.cs new file mode 100644 index 000000000..beeab25de --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/UserDetailViewModel.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Users; + +/// What the user detail screen (/admin/users/{name}) shows: the account, its keys, organizations and access. +public sealed class UserDetailViewModel : ConfirmationModel, IFlashModel +{ + /// A package ID to evaluate the effective permissions for; empty means each repository as a whole. + public string? Package { get; set; } + + /// The user name (route). + public string? Name { get; set; } + + /// Whether the configured database has an access model (else the access sections are hidden). + public bool ModelAvailable { get; internal set; } + + /// The names of the groups the account belongs to (the implicit built-ins excluded). + public IReadOnlyList Groups { get; internal set; } = Array.Empty(); + + /// The roles the account holds in projects, directly or through a group. + public IReadOnlyList ProjectRoles { get; internal set; } = Array.Empty(); + + /// What the account may do in each NuGet repository, and why. + public IReadOnlyList Access { get; internal set; } = Array.Empty(); + + /// The account. + public UserAccountInfo? Account { get; internal set; } + + /// The account's API keys; the key and its hash are never shown. + public IReadOnlyList Keys { get; internal set; } = Array.Empty(); + + /// The organizations the account belongs to. + public IReadOnlyList Organizations { get; internal set; } = Array.Empty(); + + /// How many package IDs the account owns, in every repository. + public int OwnedPackageIds { get; internal set; } + + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/Models/Users/UserGroupForm.cs b/src/BaGet.Identity.Application/Models/Users/UserGroupForm.cs new file mode 100644 index 000000000..47a3a13c9 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/UserGroupForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Users; + +/// Adding an account to a group or removing it. +/// The group's name. +/// The administrator's password. +public sealed record UserGroupForm(string? Group, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Users/UserKeyForm.cs b/src/BaGet.Identity.Application/Models/Users/UserKeyForm.cs new file mode 100644 index 000000000..1eebfe549 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/UserKeyForm.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Models.Users; + +/// Revoking one of an account's API keys. +/// The key's number (). +/// The administrator's password. +public sealed record UserKeyForm(int Key, string? Password); diff --git a/src/BaGet.Identity.Application/Models/Users/UserKeyRow.cs b/src/BaGet.Identity.Application/Models/Users/UserKeyRow.cs new file mode 100644 index 000000000..a0b7e4397 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/UserKeyRow.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Models.Users; + +/// One of an account's API keys as the administrator sees it; the key itself and its hash are never shown. +/// The key's number (what revoking names). +/// The description the owner gave it. +/// What it may do. +/// The package IDs it applies to. +/// When it was created. +/// When it expires, or null. +/// Where it may be used: the repositories it is limited to, or "all repositories". +public sealed record UserKeyRow(int Key, string? Description, IReadOnlyList Scopes, string? PackageGlobPattern, DateTime Created, DateTime? Expires, string Repositories); diff --git a/src/BaGet.Identity.Application/Models/Users/UserRow.cs b/src/BaGet.Identity.Application/Models/Users/UserRow.cs new file mode 100644 index 000000000..1da4e4147 --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/UserRow.cs @@ -0,0 +1,12 @@ +using System; + +namespace BaGet.Identity.Application.Models.Users; + +/// A user as the Users page lists them. +/// The user name. +/// The email address, if any. +/// When the account was created. +/// Whether the user is an administrator. +/// The avatar's address, or null for the initial. +/// Whether the account waits for an administrator to enable it (Accounts:RequireApproval). +public record UserRow(string? UserName, string? Email, DateTime Created, bool IsAdministrator, string? AvatarUrl, bool PendingApproval = false); diff --git a/src/BaGet.Identity.Application/Models/Users/UsersViewModel.cs b/src/BaGet.Identity.Application/Models/Users/UsersViewModel.cs new file mode 100644 index 000000000..6f1bed08d --- /dev/null +++ b/src/BaGet.Identity.Application/Models/Users/UsersViewModel.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.Models.Users; + +/// What the Users screen (/admin/users) shows: the filtered, paged accounts and the state of the last action. +public sealed class UsersViewModel : ConfirmationModel, IFlashModel +{ + /// How many users a page lists. + public const int PageSize = 50; + + /// User-name filter (contains). + public string? Q { get; set; } + + /// One-based page number (the p query value; not "page", which Razor Pages reserved for the page path). + public int PageNumber { get; set; } = 1; + + /// The users on this page. + public IReadOnlyList Users { get; internal set; } = Array.Empty(); + + /// How many accounts, in all pages, wait for approval. + public int PendingCount { get; internal set; } + + /// The number of pages for the current filter. + public int PageCount { get; internal set; } = 1; + + /// The signed in administrator's user name; their own row has no actions. + public string? CurrentUserName { get; internal set; } + + /// Whether a reset link can be mailed: SMTP is configured. + public bool CanEmailResetLink { get; internal set; } + + /// Whether an invitation (a reset link mailed to the new user) can be offered: SMTP is configured. + public bool CanInvite { get; internal set; } + + /// + /// The password just generated. Only ever rendered by the response to the reset itself, never kept in TempData or a cookie. + /// + public string? GeneratedPassword { get; internal set; } + + /// The user belongs to. + public string? GeneratedFor { get; internal set; } + + /// Whether is a new account's first password rather than a reset. + public bool GeneratedForNewUser { get; internal set; } + + /// + public string? Message { get; set; } + + /// + public string? Error { get; set; } + + /// Whether is another account, so actions apply to it. + public bool CanAct(UserRow row) + => !string.Equals(row.UserName, CurrentUserName, StringComparison.OrdinalIgnoreCase); + + /// The address with all but its first letter and domain hidden, for a confirmation. + public static string MaskEmail(string? email) + { + var at = email?.LastIndexOf('@') ?? -1; + if (at < 1) return "the user's address"; + + #pragma warning disable CS8602 + return email.Substring(0, 1) + "***" + email.Substring(at); + #pragma warning restore CS8602 + } +} diff --git a/src/BaGet.Identity.Application/README.md b/src/BaGet.Identity.Application/README.md new file mode 100644 index 000000000..a4f9dcb0f --- /dev/null +++ b/src/BaGet.Identity.Application/README.md @@ -0,0 +1,29 @@ +# Extension.BaGet.Identity.Application + +The account and administration **use cases** of [BaGet Extension](https://pieroviano.github.io/BaGet/): business services (accounts, API keys, +ownership, administrators, rate limiters, email senders), the screen result and the screen gate. No MVC or Razor dependency (test-enforced); +the screens (controllers, views) are in [`Extension.BaGet.Identity`](https://www.nuget.org/packages/Extension.BaGet.Identity). + +| Type | Role | +|---|---| +| `ScreenRef`, `ScreenCatalog` | A screen is its controller and default GET action (`AdminUsers/Index`); the catalog has one member per screen, used by `ScreenNext`, `ScreenLink` and `IScreenLinks` | +| `ScreenResult` | What a use case returns for a screen: `Status` (Ok, Invalid, NotFound, Forbidden, SignIn, Next), `Model`, `Errors`, `Next`. The JSON UI API serialises it as it is | +| `ScreenGate` | Who may use a screen: accounts on, mail, signed in, administrator (or project administrator), access model present, server writable. View controllers and the JSON API both ask it | +| `SignInUseCase`, `RegistrationUseCase`, `ExternalSignInUseCase`, `AccountSettingsUseCase`, `TwoFactorUseCase`, `ApiKeysUseCase`, `AccountOverviewUseCase`, `ProfileUseCase` | The rules of the account screens (sign-in, two-factor steps, registration, mail round trips, settings, API keys, organizations, My packages/access, profile), registered by `AddBaGetAccounts`; the forms and screen models are in `Models/` | +| `ScreenValidator`, `LocalUrls`, `AccountConfirmation`, `AccountLinks` | Form validation by DataAnnotations, the return-URL rule, the password/re-authentication confirmation, the absolute links of account emails (from `Site:PublicUrl` only) | +| `PackageManageUseCase`, `NpmManageUseCase`, `MavenManageUseCase`, `DockerManageUseCase`, `ContactOwnersUseCase`, `ValidationStatusUseCase`, `ScanArtifactUseCase` | The package-management screens (`Packages/*`): ownership, listing, deletion, scanning, validation status. Scoped; `EnterAsync` (owner / Delete-permission check, read-only mode) runs once per request. Their models (`PackageManageScreen`, `NpmManageViewModel`, ...) are the JSON of `/api/ui/packages/{id}/manage`, `/api/ui/npm-manage`, ... | +| `ExternalLogins`, `ExternalProviderMapping`, `SignInProviderSettings`, `OpenIdConnectProviderSetup` | The external OpenID Connect providers (`Services/Accounts`): which are configured / linked to a user, the per-provider administrator and group mapping applied at each sign-in through it, the Settings screen's *Sign-in providers* panel (named providers written to the overrides file), and the handler options per provider. The provider list itself is `OpenIdConnectProviderSet` (`BaGet.Core`), built at startup | +| `PackageScreenServices`, `IReauthenticationState` | What those use cases share (user, ownership, sensitive-action confirmation); the host implements `IReauthenticationState` over the sign-in cookie | +| `UiApiJson` | The JSON options of `/api/ui` (camelCase, enums by name, nulls left out) | +| `PasswordConfirmation`, `IScreenLinks` | The administrator's password (or recent provider sign-in) check and the "link to a screen" seam, so a use case never sees `HttpContext` or an URL helper (`IScreenLinks` is implemented by the screens project) | +| `Admin*UseCase` (`Users`, `UserDetail`, `UserDeletion`, `Packages`, `Organizations`, `Settings`, `Operations`, `Repositories`, `RepositoryEdit`, `RepositoryDelete`) | The use cases of the core administration screens (`Users`, `UserDetail`, `DeleteUser`, `UserPackages`, `Packages`, `Organizations`, `OrganizationDetail`, `Settings`, `Operations`, `Validation`, `Abuse`, `Cluster`, `Formats`, `AccessUnavailable`, and the repository screens `Repositories`, `RepositoryEdit`, `RepositoryDelete`: no answer carries an upstream password); registered by `AddBaGetAdminUseCases` while accounts are enabled | +| `AdminGroupsUseCase`, `AdminPermissionsUseCase`, `AdminProjectsUseCase`, `AdminAuditUseCase` (+ `AccessUseCaseBase`, `AccessCaller`, `AccessAuthorization`, `AccessPatternSupport`) | The access-control screens (`Groups`, `GroupDetail`, `Permissions`, `PermissionDetail`, `Projects`, `ProjectDetail`, `Audit`); the caller says whether it is a server administrator, the gate (not the use case) admits a project's administrators by the `name` route value through `AccessAuthorization`; forms in `Models/Access` | +| `RetentionUseCase`, `ScanningUseCase`, `ReplicationUseCase` | The retention (`Retention`, `RetentionPolicy`, `RetentionHolds`), vulnerability scanning (`Scanning`, `ScanRepository`, `ScanProject`) and replication (`Replication`, `ReplicationConfig`) screens, over `PolicyUseCaseBase` (password confirmation, `AccessModelException` shown on the screen the action returns to). Twins under `/api/ui/admin/retention`, `/scanning`, `/replication`; the peer API key of a replication and the scanner's registry credential are in no model | +| `Models//` | The DTOs of those screens (the JSON `model`) and the bodies of their writes, by area (`Account`, `Access`, `Admin`-side `Users`/`Organizations`/`Repositories`/`Settings`/`Operations`, `Packages`, `Policies`, `Shared`). A DTO never carries a password, hash, security stamp or API key value | +| `AccountAuthenticationService`, `ApiKeyService`, `PackageOwnershipService`, ... | The services `AddBaGetAccounts` registers while accounts are enabled; they are in `Services/Accounts`, `Services/Organizations` and `Services/Ownership` (namespace `BaGet.Identity.Application.Services.*`) | + +`AddBaGetAccounts` (in `Extension.BaGet.Identity`) stays the entry point of a host; it calls `AddBaGetIdentityApplication` and, while accounts are enabled, `AddBaGetIdentityUseCases`. + +## Layout + +One type per file, no nested types, namespace = `BaGet.Identity.Application` + folder (`CodeLayoutTests`): `UseCases/{Account,Access,Admin,Packages,Policies}`, `Models/`, `Services/{Accounts,Organizations,Ownership}`, `Screens` (result/gate types), `Security`, `Email`, `RateLimiting`, `Links`, `Extensions`. diff --git a/src/BaGet.Identity.Application/RateLimiting/ContactRateLimiter.cs b/src/BaGet.Identity.Application/RateLimiting/ContactRateLimiter.cs new file mode 100644 index 000000000..d1654fffa --- /dev/null +++ b/src/BaGet.Identity.Application/RateLimiting/ContactRateLimiter.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using BaGet.Core; + +namespace BaGet.Identity.Application.RateLimiting; + +/// +/// Allows one contact-owners message per sender per package per . +/// +/// +/// The state is in memory, so it is per process: it resets on restart and each instance of a +/// scaled-out deployment counts separately. That bounds spam well enough for a feed's +/// size and keeps the feature free of schema changes. Time comes from . +/// In a cluster (Ha:Enabled) the allowance is a key in the shared store instead (expiring after ), so +/// the nodes count together. +/// +public class ContactRateLimiter +{ + public static readonly TimeSpan Window = TimeSpan.FromMinutes(10); + + private readonly SystemTime _time; + private readonly ConcurrentDictionary<(string Sender, string PackageId), DateTime> _last = new(); + private readonly object _gate = new(); + + private readonly IClusterStore? _shared; + + public ContactRateLimiter(SystemTime time, ClusterRuntime? cluster = null) + { + _time = time ?? throw new ArgumentNullException(nameof(time)); + _shared = cluster?.Store; + } + + private static string SharedKey(string senderId, string? packageId) => "limit:contact:" + senderId + ":" + packageId?.ToLowerInvariant(); + + /// + /// Takes the sender's allowance for the package, or returns false when it was used less + /// than ago. Atomic, so two concurrent posts cannot both pass. + /// + public bool TryAcquire(string senderId, string? packageId) + { + if (_shared != null) return _shared.SetIfAbsent(SharedKey(senderId, packageId), "1", Window); + + var now = _time.UtcNow; + var key = (senderId, packageId?.ToLowerInvariant()); + + lock (_gate) + { + #pragma warning disable CS8620 + if (_last.TryGetValue(key, out var previous) && now - previous < Window) + #pragma warning restore CS8620 + { + return false; + } + + #pragma warning disable CS8620 + _last[key] = now; + #pragma warning restore CS8620 + if (_last.Count > 10_000) Prune(now); + + return true; + } + } + + /// + /// Gives the allowance back, when the message could not be sent. + /// + public void Release(string senderId, string? packageId) + { + if (_shared != null) + { + _shared.Delete(SharedKey(senderId, packageId)); + + return; + } + + #pragma warning disable CS8620 + lock (_gate) _last.TryRemove((senderId, packageId?.ToLowerInvariant()), out _); + #pragma warning restore CS8620 + } + + private void Prune(DateTime now) + { + foreach (var expired in _last.Where(p => now - p.Value >= Window).Select(p => p.Key).ToList()) + { + _last.TryRemove(expired, out _); + } + } +} diff --git a/src/BaGet.Identity.Application/RateLimiting/PasswordResetRateLimiter.cs b/src/BaGet.Identity.Application/RateLimiting/PasswordResetRateLimiter.cs new file mode 100644 index 000000000..f581df1ee --- /dev/null +++ b/src/BaGet.Identity.Application/RateLimiting/PasswordResetRateLimiter.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; + +namespace BaGet.Identity.Application.RateLimiting; + +/// +/// Limits "forgot password" mail: one per account per (the real +/// protection), plus a generous backstop of per client address per +/// . There is deliberately no site-wide cap: it would let one caller, with a +/// spoofed address and public account names, block everyone else's reset. +/// +/// +/// +/// The client address is only as good as the forwarded headers the server trusts (they are +/// trusted from anyone, see ConfigureBaGetOptions), so it can be spoofed, and behind a +/// proxy that sets no forwarded header every request shares one address. That is why the +/// client limit is high and is not the only gate. +/// +/// +/// Only allowed mail is recorded, and the caller asks only for accounts that exist, so the +/// state holds at most one entry per account (an account cannot be acquired twice within the +/// window) and at most as many client entries: it is bounded by the number of accounts, whatever +/// the traffic. Entries leave in the order they came in, so expiry is O(1) amortised with no scan, +/// and a client's count only ever drops with age, which can make the limiter more permissive +/// for that client, never block an account. Like the state is in +/// memory: per process, reset on restart. The caller answers identically whether or not a request +/// was allowed. In a cluster (Ha:Enabled) the account allowance is a key in the shared store (expiring after ) +/// and the client count a shared counter that starts its at the first request (a fixed window, where the in-memory +/// one slides), so the nodes count together. +/// +/// +public class PasswordResetRateLimiter +{ + public static readonly TimeSpan Window = TimeSpan.FromMinutes(10); + + public const int MaxPerClient = 60; + + private readonly SystemTime _time; + private readonly Queue<(DateTime At, string Client, string Target)> _log = new(); + private readonly Dictionary _targets = new(); + private readonly Dictionary _clients = new(); + private readonly object _gate = new(); + + /// What is being remembered; never more than the number of accounts. + internal int TrackedCount + { + get + { + lock (_gate) return _log.Count; + } + } + + private readonly IClusterStore? _shared; + + public PasswordResetRateLimiter(SystemTime time, ClusterRuntime? cluster = null) + { + _time = time ?? throw new ArgumentNullException(nameof(time)); + _shared = cluster?.Store; + } + + /// + /// Takes the allowance, or returns false when the target was mailed less than + /// ago, or the client has used up its requests. Atomic. + /// + public bool TryAcquire(string client, string target) + { + if (_shared != null) return TryAcquireShared(client, target); + + var now = _time.UtcNow; + + lock (_gate) + { + Expire(now); + + if (_targets.ContainsKey(target)) return false; + if (_clients.TryGetValue(client, out var used) && used >= MaxPerClient) return false; + + _log.Enqueue((now, client, target)); + _targets[target] = now; + _clients[client] = used + 1; + + return true; + } + } + + private bool TryAcquireShared(string client, string target) + { + var shared = _shared!; + var targetKey = "limit:reset:target:" + target; + if (!shared.SetIfAbsent(targetKey, "1", Window)) return false; + + if (shared.Increment("limit:reset:client:" + client, Window) > MaxPerClient) + { + // The client used its requests up: nothing was mailed, so the account keeps its allowance. + shared.Delete(targetKey); + + return false; + } + + return true; + } + + private void Expire(DateTime now) + { + while (_log.Count > 0 && now - _log.Peek().At >= Window) + { + var (_, client, target) = _log.Dequeue(); + _targets.Remove(target); + + if (_clients[client] <= 1) _clients.Remove(client); + else _clients[client]--; + } + } +} diff --git a/src/BaGet.Identity.Application/Screens/EmptyScreen.cs b/src/BaGet.Identity.Application/Screens/EmptyScreen.cs new file mode 100644 index 000000000..947ca06b8 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/EmptyScreen.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.Screens; + +/// The model of a screen that shows nothing but itself (the sign-out button), or of an action that only continues elsewhere. +public sealed class EmptyScreen +{ + /// The one instance. + public static EmptyScreen Instance { get; } = new(); +} diff --git a/src/BaGet.Identity.Application/Screens/GateOutcome.cs b/src/BaGet.Identity.Application/Screens/GateOutcome.cs new file mode 100644 index 000000000..c56bfb856 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/GateOutcome.cs @@ -0,0 +1,23 @@ +namespace BaGet.Identity.Application.Screens; + +/// The answer of the . +public enum GateOutcome +{ + /// The caller may use the screen. + Allowed, + + /// Accounts are disabled: there is nothing to show (404). + AccountsOff, + + /// The screen does not exist for this caller (404): no mail configured, not an administrator, not a project administrator. + NotFound, + + /// The caller must sign in. + SignIn, + + /// The caller is known but this credential may not do it (an interactive-only twin over HTTP for a key or an anonymous caller, a key without the administration scope). + Forbidden, + + /// The database has no access model (Azure Table) and the caller is an administrator: the screen says so. + AccessUnavailable, +} diff --git a/src/BaGet.Identity.Application/Screens/GateRequest.cs b/src/BaGet.Identity.Application/Screens/GateRequest.cs new file mode 100644 index 000000000..6e83f8bc5 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/GateRequest.cs @@ -0,0 +1,37 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; + +namespace BaGet.Identity.Application.Screens; + +/// What a screen requires of its caller, in the order the gate checks it. +/// The caller must be signed in (else ). +/// Mail must be configured (else ). +/// Who may use the screen. +/// The request changes something: the read-only refuses it (, 503) once the role is settled. +/// The API key behind the request, or null for a browser session (or an anonymous visitor). +/// The screen changes or reveals credentials: an API key never opens it (). +/// For : admits a caller who is not a server administrator (a project administrator). +public sealed record GateRequest( + bool RequiresSignIn = false, + bool RequiresEmail = false, + GateRole Role = GateRole.Anyone, + bool IsWrite = false, + BaGetPrincipal? KeyCaller = null, + bool CookieOnly = false, + Func>? AlsoAllow = null) +{ + /// + /// The request reached the screen over HTTP as a JSON twin (/api/ui), where the only credential is an API key: a screen is then + /// unreachable (, "use the web screen") for any caller, and a caller who is not signed in is told how to authenticate. + /// The in-process call of a view controller leaves it false. + /// + public bool OverHttp { get; init; } + + /// + /// The caller of a JSON twin is a person's interactive session (a session token, or the cookie with a valid antiforgery header), not an API key. A + /// screen is open to it, and a caller who lacks the administrator role is told so (403) instead of the 404 a cookie visitor gets. + /// + public bool InteractiveSession { get; init; } +} diff --git a/src/BaGet.Identity.Application/Screens/GateResult.cs b/src/BaGet.Identity.Application/Screens/GateResult.cs new file mode 100644 index 000000000..88c7962ae --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/GateResult.cs @@ -0,0 +1,13 @@ +namespace BaGet.Identity.Application.Screens; + +/// The gate's decision and what it learned on the way. +/// Whether the screen may run, and if not why. +/// Whether the caller is a server administrator (only evaluated for the roles that need it). +public readonly record struct GateResult(GateOutcome Outcome, bool IsServerAdministrator) +{ + /// Why the screen was refused, in words for an API client (null when there is nothing to add). + public string? Message { get; init; } + + /// Whether the screen may run. + public bool IsAllowed => Outcome == GateOutcome.Allowed; +} diff --git a/src/BaGet.Identity.Application/Screens/GateRole.cs b/src/BaGet.Identity.Application/Screens/GateRole.cs new file mode 100644 index 000000000..ccf0d0f57 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/GateRole.cs @@ -0,0 +1,19 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Screens; + +/// Who may use an administration screen. +public enum GateRole +{ + /// Anybody the other requirements let in. + Anyone, + + /// Server administrators. + Administrator, + + /// + /// The access screens: server administrators, or whoever admits (a project's administrators; a key only when it carries and no repository limit); + /// 503 on a write while the server is read-only; an administrator is sent to the "unavailable" screen where there is no access model. + /// + AccessAdministrator, +} diff --git a/src/BaGet.Identity.Application/Screens/HtmlStringConverter.cs b/src/BaGet.Identity.Application/Screens/HtmlStringConverter.cs new file mode 100644 index 000000000..6a7638519 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/HtmlStringConverter.cs @@ -0,0 +1,19 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; +using Microsoft.AspNetCore.Html; + +namespace BaGet.Identity.Application.Screens; + +/// +/// An (rendered, already safe HTML such as a readme) is written as the plain string it holds, not as an object, so a client +/// receives the HTML as text. +/// +internal sealed class HtmlStringConverter : JsonConverter +{ + public override HtmlString? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => reader.TokenType == JsonTokenType.Null ? null : new HtmlString(reader.GetString()); + + public override void Write(Utf8JsonWriter writer, HtmlString value, JsonSerializerOptions options) + => writer.WriteStringValue(value.Value); +} diff --git a/src/BaGet.Identity.Application/Screens/IScreenLinks.cs b/src/BaGet.Identity.Application/Screens/IScreenLinks.cs new file mode 100644 index 000000000..9ba0d664f --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/IScreenLinks.cs @@ -0,0 +1,19 @@ +using BaGet.Identity.Application.Email; + +namespace BaGet.Identity.Application.Screens; + +/// +/// Builds the address of a screen for a use case that has to put one in a message (a password reset link in an email). The implementation +/// belongs to the UI project, which knows the routes (the controllers and actions of the screens); a use case never sees an URL helper. +/// +public interface IScreenLinks +{ + /// + /// An absolute link to a screen, for an email. Built only from Site:PublicUrl, never from the request's host or scheme (see + /// ). + /// + /// The screen (). + /// Route values, e.g. . + /// Site:PublicUrl is not set to a usable address. + string AbsoluteLink(ScreenRef screen, object values); +} diff --git a/src/BaGet.Identity.Application/Screens/IScreenResult.cs b/src/BaGet.Identity.Application/Screens/IScreenResult.cs new file mode 100644 index 000000000..3fa343193 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/IScreenResult.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace BaGet.Identity.Application.Screens; + +/// The model-independent part of a , for the code that maps a result to HTTP or to a view. +public interface IScreenResult +{ + /// The decision. + ScreenStatus Status { get; } + + /// Field name to messages; the empty name holds the messages of the form as a whole. + IReadOnlyDictionary Errors { get; } + + /// Where to go, when is . + ScreenNext? Next { get; } + + /// The HTTP status a view renders with when it is not 200 (an upload refused renders its form again with 400). + int? StatusCode { get; } + + /// The model, or null. + [JsonIgnore] + object? ModelObject { get; } +} diff --git a/src/BaGet.Identity.Application/Screens/LocalUrls.cs b/src/BaGet.Identity.Application/Screens/LocalUrls.cs new file mode 100644 index 000000000..fa9699fa8 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/LocalUrls.cs @@ -0,0 +1,59 @@ +using System; + +namespace BaGet.Identity.Application.Screens; + +/// +/// The rule for a return URL after a sign-in: only a local address is followed, so a sign-in link cannot send the user elsewhere. +/// It is the rule of IUrlHelper.IsLocalUrl (an absolute path, or an application-relative ~/ path, with no scheme, host, +/// //, /\ or control character), kept here because the use cases have no IUrlHelper. +/// +public static class LocalUrls +{ + /// The site root, written application-relative (the view prefixes the path base). + public const string Root = "~/"; + + private const char Backslash = (char)92; + + /// Whether is a local address. + public static bool IsLocal(string? url) + { + if (string.IsNullOrEmpty(url)) return false; + + if (url[0] == '/') + { + if (url.Length == 1) return true; + if (url[1] == '/' || url[1] == Backslash) return false; + + return !HasControlCharacter(url.AsSpan(1)); + } + + if (url[0] == '~' && url.Length > 1 && url[1] == '/') + { + if (url.Length == 2) return true; + if (url[2] == '/' || url[2] == Backslash) return false; + + return !HasControlCharacter(url.AsSpan(2)); + } + + return false; + } + + /// when it is local, else the site root. + public static string Target(string? returnUrl) => IsLocal(returnUrl) ? returnUrl! : Root; + + /// + /// A local address written application-relative (~/x), so the redirect adds the path base; a root-relative /x written by a + /// view or a caller that does not know the path base would otherwise leave the application. Other values are returned unchanged. + /// + public static string AppRelative(string url) => url.Length > 0 && url[0] == '/' && IsLocal(url) ? "~" + url : url; + + private static bool HasControlCharacter(ReadOnlySpan text) + { + foreach (var c in text) + { + if (char.IsControl(c)) return true; + } + + return false; + } +} diff --git a/src/BaGet.Identity.Application/Screens/PasswordConfirmation.cs b/src/BaGet.Identity.Application/Screens/PasswordConfirmation.cs new file mode 100644 index 000000000..b93bee46a --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/PasswordConfirmation.cs @@ -0,0 +1,84 @@ +using System; +using System.Security.Claims; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.Screens; + +/// +/// The check behind every sensitive action of the account and administration screens: the caller types their password again, or, for an +/// account without one (external sign-in only), has signed in again with the provider a moment ago. Also fills the confirmation fields +/// () a screen needs to ask for it. The only part of a use case that reads the request is the re-authentication +/// time, which lives in the session cookie, so it is read here (through ) and never by the use case itself. +/// +public sealed class PasswordConfirmation +{ + /// How long a sign-in with the external provider counts as proof of presence for a sensitive action. + public static readonly TimeSpan ReauthenticationWindow = AccountConfirmation.ReauthenticationWindow; + + /// The sign-in cookie property that holds the time (ticks, UTC) of the last re-authentication. + public const string ReauthenticatedItem = AccountConfirmation.ReauthenticatedItem; + + private readonly UserManager _users; + private readonly IHttpContextAccessor _http; + private readonly ExternalLogins _logins; + + /// Creates the service. + public PasswordConfirmation(UserManager users, IHttpContextAccessor http, IOptions accounts) + : this(users, http, accounts, ExternalLogins.For(users, accounts)) + { + } + + /// Creates the service. + public PasswordConfirmation(UserManager users, IHttpContextAccessor http, IOptions accounts, ExternalLogins logins) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _ = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _logins = logins ?? throw new ArgumentNullException(nameof(logins)); + } + + /// Whether confirmed: the right password, or, for an account without one, a recent provider sign-in. + public Task IsConfirmedAsync(BaGetUser? user, string? password) + => IsConfirmedAsync(_users, _http.HttpContext, user, password); + + /// Fills the fields the confirmation partial needs for . + /// The screen's model. + /// The signed-in user. + /// The page to come back to after signing in again, or null to leave the model's. + public async Task LoadAsync(ConfirmationModel model, ClaimsPrincipal caller, string? returnPage = null) + { + if (model == null) throw new ArgumentNullException(nameof(model)); + + var current = await _users.GetUserAsync(caller); + model.HasPassword = current == null || await _users.HasPasswordAsync(current); + model.Reauthenticated = !model.HasPassword && await HasReauthenticatedRecentlyAsync(_http.HttpContext); + model.CanReauthenticate = await _logins.CanReauthenticateAsync(current); + if (returnPage != null) model.ReturnPage = returnPage; + } + + /// + /// with the page to come back to after signing in again being the URL (path and query, application-relative with ~ so a path base is kept) of the request being served, as the + /// access screens always did. Through the in-process call of a view controller that is the screen's own address. + /// + public Task LoadForRequestAsync(ConfirmationModel model, ClaimsPrincipal caller) + { + var request = _http.HttpContext?.Request; + + return LoadAsync(model, caller, request == null ? null : "~" + request.Path + request.QueryString); + } + + /// The check behind every sensitive action, for a caller that holds its own (the rule lives in ). + public static Task IsConfirmedAsync(UserManager users, HttpContext? httpContext, BaGetUser? user, string? password) + => AccountConfirmation.IsConfirmedAsync(users, httpContext!, user, password); + + /// Whether the session re-authenticated with the external provider within . + public static Task HasReauthenticatedRecentlyAsync(HttpContext? httpContext) + => httpContext == null ? Task.FromResult(false) : AccountConfirmation.HasReauthenticatedRecentlyAsync(httpContext); +} diff --git a/src/BaGet.Identity.Application/Screens/RepositoryFeedUrl.cs b/src/BaGet.Identity.Application/Screens/RepositoryFeedUrl.cs new file mode 100644 index 000000000..653300485 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/RepositoryFeedUrl.cs @@ -0,0 +1,47 @@ +using System; +using BaGet.Core; +using Microsoft.AspNetCore.Http; + +namespace BaGet.Identity.Application.Screens; + +/// +/// The feed address of a repository, as shown to administrators to paste into a client: the format's +/// (NuGet: v3/index.json) below the repository base, which is the root for the +/// default repository and /r/{name}/ for the others. Built from the server's own service index URL (so a configured public URL or +/// path base is honoured), falling back to the address of the request being served. +/// +public sealed class RepositoryFeedUrl +{ + private const string ServiceIndexPath = "v3/index.json"; + + private readonly IUrlGenerator? _urls; + private readonly IHttpContextAccessor _http; + + /// Creates the service. + public RepositoryFeedUrl(IHttpContextAccessor http, IUrlGenerator? urls = null) + { + _http = http ?? throw new ArgumentNullException(nameof(http)); + _urls = urls; + } + + /// The address of 's feed for a format whose feed path is . + public string For(string repositoryName, string feedPath = ServiceIndexPath) + => feedPath.Contains("{repo}", StringComparison.Ordinal) + ? BaseFor(Repository.DefaultName) + feedPath.Replace("{repo}", repositoryName) + : BaseFor(repositoryName) + feedPath; + + /// The address of the repository's base (ends with a slash): where its format's routes start. + public string BaseFor(string repositoryName) + { + var root = _urls?.GetServiceIndexUrl(); + if (string.IsNullOrEmpty(root)) + { + var request = _http.HttpContext?.Request; + root = request == null ? "/" + ServiceIndexPath : $"{request.Scheme}://{request.Host}{request.PathBase}/{ServiceIndexPath}"; + } + + var prefix = root.EndsWith(ServiceIndexPath, StringComparison.Ordinal) ? root.Substring(0, root.Length - ServiceIndexPath.Length) : root.TrimEnd('/') + "/"; + + return repositoryName == Repository.DefaultName ? prefix : $"{prefix}r/{repositoryName}/"; + } +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenCatalog.cs b/src/BaGet.Identity.Application/Screens/ScreenCatalog.cs new file mode 100644 index 000000000..081b69f88 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenCatalog.cs @@ -0,0 +1,303 @@ +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Screens; + +/// +/// Every screen of the web UI, by the controller and default GET action that serve it (see ). Use cases name the screen +/// they continue at with these members; a test checks that each one still resolves to an existing view action. +/// +public static class ScreenCatalog +{ + /// AccountPackages/Access. + public static readonly ScreenRef AccountAccess = new("AccountPackages", "Access"); + + /// AccountSettings/ApiKeysIndex. + public static readonly ScreenRef AccountApiKeys = new("AccountSettings", "ApiKeysIndex"); + + /// Account/ConfirmEmail. + public static readonly ScreenRef AccountConfirmEmail = new("Account", "ConfirmEmail"); + + /// Account/ForgotPassword. + public static readonly ScreenRef AccountForgotPassword = new("Account", "ForgotPassword"); + + /// Account/Login. + public static readonly ScreenRef AccountLogin = new("Account", "Login"); + + /// Account/LoginWith2fa. + public static readonly ScreenRef AccountLoginWith2fa = new("Account", "LoginWith2fa"); + + /// Account/LoginWithRecoveryCode. + public static readonly ScreenRef AccountLoginWithRecoveryCode = new("Account", "LoginWithRecoveryCode"); + + /// Account/Logout. + public static readonly ScreenRef AccountLogout = new("Account", "Logout"); + + /// AccountOrganizations/Organizations. + public static readonly ScreenRef AccountOrganizations = new("AccountOrganizations", "Organizations"); + + /// AccountPackages/Packages. + public static readonly ScreenRef AccountPackages = new("AccountPackages", "Packages"); + + /// AccountPackages/MyProfile. + public static readonly ScreenRef AccountProfile = new("AccountPackages", "MyProfile"); + + /// Account/Reauthenticate. + public static readonly ScreenRef AccountReauthenticate = new("Account", "Reauthenticate"); + + /// Account/Register. + public static readonly ScreenRef AccountRegister = new("Account", "Register"); + + /// Account/ResetPassword. + public static readonly ScreenRef AccountResetPassword = new("Account", "ResetPassword"); + + /// AccountSettings/Settings. + public static readonly ScreenRef AccountSettings = new("AccountSettings", "Settings"); + + /// AccountSettings/TwoFactor. + public static readonly ScreenRef AccountTwoFactor = new("AccountSettings", "TwoFactor"); + + /// AdminOperations/Abuse. + public static readonly ScreenRef AdminAbuse = new("AdminOperations", "Abuse"); + + /// AdminOperations/AccessUnavailable. + public static readonly ScreenRef AdminAccessUnavailable = new("AdminOperations", "AccessUnavailable"); + + /// ApiCatalog/Index. + public static readonly ScreenRef AdminApi = new("ApiCatalog", "Index"); + + /// AdminAudit/Index. + public static readonly ScreenRef AdminAudit = new("AdminAudit", "Index"); + + /// AdminOperations/Cluster. + public static readonly ScreenRef AdminCluster = new("AdminOperations", "Cluster"); + + /// AdminUsers/DeleteUser. + public static readonly ScreenRef AdminDeleteUser = new("AdminUsers", "DeleteUser"); + + /// AdminOperations/Formats. + public static readonly ScreenRef AdminFormats = new("AdminOperations", "Formats"); + + /// AdminGroups/Detail. + public static readonly ScreenRef AdminGroupDetail = new("AdminGroups", "Detail"); + + /// AdminGroups/Index. + public static readonly ScreenRef AdminGroups = new("AdminGroups", "Index"); + + /// AdminOperations/Index. + public static readonly ScreenRef AdminOperations = new("AdminOperations", "Index"); + + /// AdminOrganizations/Detail. + public static readonly ScreenRef AdminOrganizationDetail = new("AdminOrganizations", "Detail"); + + /// AdminOrganizations/Index. + public static readonly ScreenRef AdminOrganizations = new("AdminOrganizations", "Index"); + + /// AdminPackages/Index. + public static readonly ScreenRef AdminPackages = new("AdminPackages", "Index"); + + /// AdminPermissions/Detail. + public static readonly ScreenRef AdminPermissionDetail = new("AdminPermissions", "Detail"); + + /// AdminPermissions/Index. + public static readonly ScreenRef AdminPermissions = new("AdminPermissions", "Index"); + + /// AdminProjects/Detail. + public static readonly ScreenRef AdminProjectDetail = new("AdminProjects", "Detail"); + + /// AdminProjects/Index. + public static readonly ScreenRef AdminProjects = new("AdminProjects", "Index"); + + /// AdminReplication/Index. + public static readonly ScreenRef AdminReplication = new("AdminReplication", "Index"); + + /// AdminReplication/Config. + public static readonly ScreenRef AdminReplicationConfig = new("AdminReplication", "Config"); + + /// AdminRepositories/Index. + public static readonly ScreenRef AdminRepositories = new("AdminRepositories", "Index"); + + /// AdminRepositories/DeleteRepository. + public static readonly ScreenRef AdminRepositoryDelete = new("AdminRepositories", "DeleteRepository"); + + /// AdminRepositories/Edit. + public static readonly ScreenRef AdminRepositoryEdit = new("AdminRepositories", "Edit"); + + /// AdminRetention/Index. + public static readonly ScreenRef AdminRetention = new("AdminRetention", "Index"); + + /// AdminRetention/Holds. + public static readonly ScreenRef AdminRetentionHolds = new("AdminRetention", "Holds"); + + /// AdminRetention/Policy. + public static readonly ScreenRef AdminRetentionPolicy = new("AdminRetention", "Policy"); + + /// AdminScanning/Project. + public static readonly ScreenRef AdminScanProject = new("AdminScanning", "Project"); + + /// AdminScanning/Repository. + public static readonly ScreenRef AdminScanRepository = new("AdminScanning", "Repository"); + + /// AdminScanning/Index. + public static readonly ScreenRef AdminScanning = new("AdminScanning", "Index"); + + /// AdminSettings/Index. + public static readonly ScreenRef AdminSettings = new("AdminSettings", "Index"); + + /// AdminUsers/Detail. + public static readonly ScreenRef AdminUserDetail = new("AdminUsers", "Detail"); + + /// AdminUsers/UserPackages. + public static readonly ScreenRef AdminUserPackages = new("AdminUsers", "UserPackages"); + + /// AdminUsers/Index. + public static readonly ScreenRef AdminUsers = new("AdminUsers", "Index"); + + /// AdminOperations/Validation. + public static readonly ScreenRef AdminValidation = new("AdminOperations", "Validation"); + + /// DockerBrowse/Image. + public static readonly ScreenRef DockerImage = new("DockerBrowse", "Image"); + + /// DockerBrowse/Images. + public static readonly ScreenRef DockerImages = new("DockerBrowse", "Images"); + + /// Home/Index. + public static readonly ScreenRef Index = new("Home", "Index"); + + /// MavenBrowse/Artifact. + public static readonly ScreenRef MavenArtifact = new("MavenBrowse", "Artifact"); + + /// MavenBrowse/Artifacts. + public static readonly ScreenRef MavenArtifacts = new("MavenBrowse", "Artifacts"); + + /// MavenBrowse/Upload. + public static readonly ScreenRef MavenUpload = new("MavenBrowse", "Upload"); + + /// NpmBrowse/Package. + public static readonly ScreenRef NpmPackage = new("NpmBrowse", "Package"); + + /// NpmBrowse/Packages. + public static readonly ScreenRef NpmPackages = new("NpmBrowse", "Packages"); + + /// NpmBrowse/Upload. + public static readonly ScreenRef NpmUpload = new("NpmBrowse", "Upload"); + + /// Package/Show. + public static readonly ScreenRef Package = new("Package", "Show"); + + /// ContactOwners/Index. + public static readonly ScreenRef PackagesContactOwners = new("ContactOwners", "Index"); + + /// DockerManage/Index. + public static readonly ScreenRef PackagesDockerManage = new("DockerManage", "Index"); + + /// PackageManage/Index. + public static readonly ScreenRef PackagesManage = new("PackageManage", "Index"); + + /// MavenManage/Index. + public static readonly ScreenRef PackagesMavenManage = new("MavenManage", "Index"); + + /// NpmManage/Index. + public static readonly ScreenRef PackagesNpmManage = new("NpmManage", "Index"); + + /// ScanArtifact/Index. + public static readonly ScreenRef PackagesScan = new("ScanArtifact", "Index"); + + /// ValidationStatusPage/Index. + public static readonly ScreenRef PackagesValidationStatus = new("ValidationStatusPage", "Index"); + + /// Legal/Privacy. + public static readonly ScreenRef Privacy = new("Legal", "Privacy"); + + /// Profile/Profile. + public static readonly ScreenRef ProfilesProfile = new("Profile", "Profile"); + + /// ReportAbuse/Show. + public static readonly ScreenRef ReportAbuse = new("ReportAbuse", "Show"); + + /// Statistics/Index. + public static readonly ScreenRef Statistics = new("Statistics", "Index"); + + /// Legal/Terms. + public static readonly ScreenRef Terms = new("Legal", "Terms"); + + /// Upload/Index. + public static readonly ScreenRef Upload = new("Upload", "Index"); + + /// Every screen above. + public static IReadOnlyList All { get; } = new[] + { + AccountAccess, + AccountApiKeys, + AccountConfirmEmail, + AccountForgotPassword, + AccountLogin, + AccountLoginWith2fa, + AccountLoginWithRecoveryCode, + AccountLogout, + AccountOrganizations, + AccountPackages, + AccountProfile, + AccountReauthenticate, + AccountRegister, + AccountResetPassword, + AccountSettings, + AccountTwoFactor, + AdminAbuse, + AdminAccessUnavailable, + AdminApi, + AdminAudit, + AdminCluster, + AdminDeleteUser, + AdminFormats, + AdminGroupDetail, + AdminGroups, + AdminOperations, + AdminOrganizationDetail, + AdminOrganizations, + AdminPackages, + AdminPermissionDetail, + AdminPermissions, + AdminProjectDetail, + AdminProjects, + AdminReplication, + AdminReplicationConfig, + AdminRepositories, + AdminRepositoryDelete, + AdminRepositoryEdit, + AdminRetention, + AdminRetentionHolds, + AdminRetentionPolicy, + AdminScanProject, + AdminScanRepository, + AdminScanning, + AdminSettings, + AdminUserDetail, + AdminUserPackages, + AdminUsers, + AdminValidation, + DockerImage, + DockerImages, + Index, + MavenArtifact, + MavenArtifacts, + MavenUpload, + NpmPackage, + NpmPackages, + NpmUpload, + Package, + PackagesContactOwners, + PackagesDockerManage, + PackagesManage, + PackagesMavenManage, + PackagesNpmManage, + PackagesScan, + PackagesValidationStatus, + Privacy, + ProfilesProfile, + ReportAbuse, + Statistics, + Terms, + Upload, + }; +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenGate.cs b/src/BaGet.Identity.Application/Screens/ScreenGate.cs new file mode 100644 index 000000000..83f1fd29d --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenGate.cs @@ -0,0 +1,150 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.Screens; + +/// +/// The single place that decides whether a caller may use a screen of the account and administration area: accounts enabled, mail +/// configured, signed in, administrator (or project administrator), the access model present, the server writable. The view +/// controller bases and the JSON API bases both ask it, in the same order, so the two ways to reach a screen cannot disagree. It +/// returns a ; each side turns it into its own answer (a 404 page or a JSON 404, a sign-in redirect or a +/// 401). Resolved per request: the services it needs exist only while accounts are enabled. +/// +public sealed class ScreenGate +{ + private readonly IOptions _accounts; + private readonly IOptions _email; + private readonly IServiceProvider _services; + + /// Creates the gate. + public ScreenGate(IOptions accounts, IOptions email, IServiceProvider services) + { + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _email = email ?? throw new ArgumentNullException(nameof(email)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + /// Whether accounts are enabled. + public bool AccountsEnabled => _accounts.Value.Enabled; + + /// Whether outgoing mail is configured. + public bool EmailConfigured => _email.Value.IsConfigured; + + /// + /// The synchronous part of the gate: accounts enabled, mail configured when required, the interactive-only rule, signed in when required. + /// + public GateOutcome CheckAccount(ClaimsPrincipal? user, GateRequest request) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + if (!AccountsEnabled) return GateOutcome.AccountsOff; + if (request.RequiresEmail && !EmailConfigured) return GateOutcome.NotFound; + if (request.CookieOnly && (request.KeyCaller != null || (request.OverHttp && !request.InteractiveSession))) return GateOutcome.Forbidden; + if (request.RequiresSignIn && user?.Identity?.IsAuthenticated != true) return GateOutcome.SignIn; + + return GateOutcome.Allowed; + } + + /// Whether the caller is a server administrator: the session's user, or the key of an administrator (see ). + public async Task IsAdministratorAsync(ClaimsPrincipal? user, BaGetPrincipal? keyCaller, CancellationToken cancellationToken) + { + if (keyCaller != null) return IsAdministratorKey(keyCaller); + if (user == null) return false; + + return await _services.GetRequiredService().IsAdministratorAsync(user, cancellationToken); + } + + /// + /// Whether an API key may use the administration screens: the key of an administrator that carries and is not limited + /// to repositories. The global ApiKey (the superuser) is refused here, unlike on the administration API (/api/v1): it has no owner, and the + /// screens act as the signed-in user (an open server authenticates everybody as the superuser, which must never open the administration anyway). + /// + public bool IsAdministratorKey(BaGetPrincipal key) + { + if (key == null) throw new ArgumentNullException(nameof(key)); + + // The global key has no owner: the use cases that need the current user could not act for it. The screens want an administrator's key. + if (key.IsSuperuser) return false; + + return key.IsAdministrator && key.HasScope(ApiKeyScopes.Admin) && key.RepositoryKeys == null; + } + + /// The whole gate for a screen. + public async Task CheckAsync(ClaimsPrincipal? user, GateRequest request, CancellationToken cancellationToken) + { + var account = CheckAccount(user, request); + if (account != GateOutcome.Allowed) return new GateResult(account, false) { Message = MessageFor(account, request) }; + + if (request.Role == GateRole.Anyone) return new GateResult(GateOutcome.Allowed, false); + + var isAdministrator = await IsAdministratorAsync(user, request.KeyCaller, cancellationToken); + + if (request.Role == GateRole.Administrator) + { + return Decide(isAdministrator, request); + } + + // The access screens need a relational database: an administrator is told so, anyone else sees nothing. + if (_services.GetRequiredService() is NullContext) + { + return new GateResult(isAdministrator ? GateOutcome.AccessUnavailable : GateOutcome.NotFound, isAdministrator); + } + + if (!isAdministrator && (request.AlsoAllow == null || !CanDelegate(request.KeyCaller) || !await request.AlsoAllow(cancellationToken))) + { + return Decide(false, request); + } + + if (request.IsWrite) _services.GetService()?.ThrowIfClosed(); + + return new GateResult(GateOutcome.Allowed, isAdministrator); + } + + // A key reaches the access screens only with the administration scope and no repository limit, as for the administration API + // (a project administrator's other keys, e.g. package:push or limited to one repository, never administer); a session needs nothing more. + private static bool CanDelegate(BaGetPrincipal? key) => key == null || (!key.IsSuperuser && key.HasScope(ApiKeyScopes.Admin) && key.RepositoryKeys == null); + + // A key that lacks the administration scope is told so (403); a session that is not an administrator learns nothing (404). + private static GateOutcome Refusal(GateRequest request) + => request.KeyCaller != null || request.InteractiveSession ? GateOutcome.Forbidden : GateOutcome.NotFound; + + /// The words an API client gets for a refusal of the gate (null where the outcome says it all). + public const string ScreenOnlyMessage = "This screen is only available to an interactive session (it changes or reveals credentials or ownership, which an API key never does): use the web screen, or sign in at /api/ui/session and send the session token."; + + /// The words for a caller of /api/ui who is not authenticated. + public const string KeyRequiredMessage = "Authenticate with an API key ('Authorization: Bearer ' or the 'X-NuGet-ApiKey' header) or a session token (POST /api/ui/session). The browser cookie is accepted only with a valid antiforgery header."; + + /// The words for the global ApiKey on an administration screen. + public const string GlobalKeyMessage = "The global ApiKey cannot use the administration screens: use an administrator's API key with the admin:api scope and no repository limit."; + + /// The words for a key that is not an administrator's, lacks the admin:api scope or is limited to repositories. + public const string AdminKeyMessage = "The administration screens need an administrator's API key with the admin:api scope and no repository limit."; + + /// The words for an interactive session that is not an administrator's, on an administration screen. + public const string AdminSessionMessage = "The administration screens need an administrator's account."; + + private static string? MessageFor(GateOutcome outcome, GateRequest request) + => outcome switch + { + GateOutcome.Forbidden when request.CookieOnly => ScreenOnlyMessage, + GateOutcome.SignIn when request.OverHttp => KeyRequiredMessage, + _ => null, + }; + + private static GateResult Decide(bool isAdministrator, GateRequest request) + { + if (isAdministrator) return new GateResult(GateOutcome.Allowed, true); + + var outcome = Refusal(request); + var message = outcome != GateOutcome.Forbidden + ? null + : request.KeyCaller == null ? AdminSessionMessage : request.KeyCaller.IsSuperuser ? GlobalKeyMessage : AdminKeyMessage; + + return new GateResult(outcome, false) { Message = message }; + } +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenNext.cs b/src/BaGet.Identity.Application/Screens/ScreenNext.cs new file mode 100644 index 000000000..973d935e7 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenNext.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Screens; + +/// Where a finished action leads: the screen (controller and action, see ), its route values and the message to show there. +/// The next screen (); null for a . +/// Route and query values of the next screen (repo, name, handler). +/// The outcome to show on the next screen (a flash message). +/// The refusal to show on the next screen (a flash error). +/// +/// Instead of a screen: a local address to continue at (/packages, or ~/ for the site root, which the view prefixes with the path +/// base). Always safe to follow: a use case only puts a validated local address here (). +/// +/// The URL fragment (#id) to leave the next screen at, or null. +public sealed record ScreenNext( + ScreenRef? Screen, + IReadOnlyDictionary? RouteValues = null, + string? Message = null, + string? Error = null, + string? LocalUrl = null, + string? Fragment = null) +{ + /// Continue at a local address (a sign-in return URL, the site root). + public static ScreenNext Local(string localUrl) => new(null, LocalUrl: localUrl); +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenRef.cs b/src/BaGet.Identity.Application/Screens/ScreenRef.cs new file mode 100644 index 000000000..5afb29abd --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenRef.cs @@ -0,0 +1,14 @@ +namespace BaGet.Identity.Application.Screens; + +/// +/// A screen of the web UI: the MVC controller (without the Controller suffix, as asp-controller writes it) and the action that +/// answers a plain GET for it (AdminUsers / Index). The Application projects have no MVC reference, so the UI project +/// turns it into a link. lists every screen. +/// +/// The controller name without the Controller suffix (AdminUsers). +/// The action that shows the screen (Index). +public sealed record ScreenRef(string Controller, string Action) +{ + /// Controller/Action, the form the contracts and the coverage table write a screen in. + public override string ToString() => Controller + "/" + Action; +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenResult.cs b/src/BaGet.Identity.Application/Screens/ScreenResult.cs new file mode 100644 index 000000000..90c6daee6 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenResult.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Identity.Application.Screens; + +/// +/// What a use case of a screen returns: independent of the programming model that runs it. The JSON API serialises it as it is +/// (status, model, errors, next); the view controllers turn it into a view, an error status or a redirect. +/// A use case holds the rules and never sees HttpContext, ModelState or TempData. +/// +/// The screen's model (a plain DTO). +public sealed class ScreenResult : IScreenResult +{ + private static readonly IReadOnlyDictionary NoErrors = new Dictionary(); + + private ScreenResult(ScreenStatus status, T? model, IReadOnlyDictionary? errors, ScreenNext? next, int? statusCode) + { + Status = status; + Model = model; + Errors = errors ?? NoErrors; + Next = next; + StatusCode = statusCode; + } + + /// + public ScreenStatus Status { get; } + + /// The screen's model; null for an answer that has none (not found, sign in, next). + public T? Model { get; } + + /// + public IReadOnlyDictionary Errors { get; } + + /// + public ScreenNext? Next { get; } + + /// + public int? StatusCode { get; } + + /// + object? IScreenResult.ModelObject => Model; + + /// Show the screen. + public static ScreenResult Ok(T model, int? statusCode = null) + => new(ScreenStatus.Ok, model, null, null, statusCode); + + /// The input was refused: show the screen again with the reasons. + public static ScreenResult Invalid(T model, IReadOnlyDictionary errors, int? statusCode = null) + => new(ScreenStatus.Invalid, model, errors ?? throw new ArgumentNullException(nameof(errors)), null, statusCode); + + /// The input was refused with one message about the form as a whole. + public static ScreenResult Invalid(T model, string message, int? statusCode = null) + => Invalid(model, new Dictionary { [string.Empty] = new[] { message } }, statusCode); + + /// No such screen or item. + public static ScreenResult NotFound() => new(ScreenStatus.NotFound, default, null, null, null); + + /// The caller may not do this. + public static ScreenResult Forbidden() => new(ScreenStatus.Forbidden, default, null, null, null); + + /// The caller may not do this, and says why (carried as the form-wide error, ""). + public static ScreenResult Forbidden(string message) + => new(ScreenStatus.Forbidden, default, new Dictionary { [string.Empty] = new[] { message } }, null, null); + + /// The caller must sign in. + public static ScreenResult SignIn() => new(ScreenStatus.SignIn, default, null, null, null); + + /// The caller must sign in, and says how (carried as the form-wide error, ""). + public static ScreenResult SignIn(string message) + => new(ScreenStatus.SignIn, default, new Dictionary { [string.Empty] = new[] { message } }, null, null); + + /// The action is done; continue at . + public static ScreenResult GoTo(ScreenNext next) + => new(ScreenStatus.Next, default, null, next ?? throw new ArgumentNullException(nameof(next)), null); + + /// The same decision for a screen of another model (a gate's refusal, which has no model). + public static ScreenResult From(IScreenResult refusal) + { + if (refusal == null) throw new ArgumentNullException(nameof(refusal)); + + return refusal.Status switch + { + ScreenStatus.NotFound => NotFound(), + ScreenStatus.Forbidden => refusal.Errors.Count > 0 ? new(ScreenStatus.Forbidden, default, refusal.Errors, null, null) : Forbidden(), + ScreenStatus.SignIn => refusal.Errors.Count > 0 ? new(ScreenStatus.SignIn, default, refusal.Errors, null, null) : SignIn(), + ScreenStatus.Next => GoTo(refusal.Next!), + _ => throw new ArgumentException("Only an answer without a model can be carried over.", nameof(refusal)), + }; + } +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenStatus.cs b/src/BaGet.Identity.Application/Screens/ScreenStatus.cs new file mode 100644 index 000000000..42a7b448f --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenStatus.cs @@ -0,0 +1,23 @@ +namespace BaGet.Identity.Application.Screens; + +/// What a use case decided about a screen. +public enum ScreenStatus +{ + /// The screen is shown (or the action succeeded and the screen is shown again). + Ok, + + /// The input was refused; the model and say why. + Invalid, + + /// There is no such screen or item (also the answer to a caller who may not know it exists). + NotFound, + + /// The caller is known but may not do this. + Forbidden, + + /// The caller must sign in first. + SignIn, + + /// The action is done; go to . + Next, +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenValidation.cs b/src/BaGet.Identity.Application/Screens/ScreenValidation.cs new file mode 100644 index 000000000..7af2d0543 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenValidation.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; + +namespace BaGet.Identity.Application.Screens; + +/// +/// Explicit validation of a screen's input with its DataAnnotations (a use case validates by itself, because the JSON body and the form +/// of a page are not bound by the same machinery). The messages are the ones model binding produces, so a page shows the same text. +/// +public static class ScreenValidation +{ + /// The errors of by member name, or an empty dictionary when it is valid. + public static IReadOnlyDictionary Validate(object model) + { + if (model == null) throw new ArgumentNullException(nameof(model)); + + var results = new List(); + Validator.TryValidateObject(model, new ValidationContext(model), results, validateAllProperties: true); + + return results + .SelectMany(r => (r.MemberNames.Any() ? r.MemberNames : new[] { string.Empty }).Select(member => (Member: member, Message: r.ErrorMessage ?? string.Empty))) + .GroupBy(p => p.Member, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.Select(p => p.Message).ToArray(), StringComparer.Ordinal); + } +} diff --git a/src/BaGet.Identity.Application/Screens/ScreenValidator.cs b/src/BaGet.Identity.Application/Screens/ScreenValidator.cs new file mode 100644 index 000000000..df612041d --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/ScreenValidator.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; + +namespace BaGet.Identity.Application.Screens; + +/// +/// Validates a form with its System.ComponentModel.DataAnnotations attributes, the same rules MVC applies to a bound model, so a +/// use case checks its input itself whether it is called from a view controller, the JSON API or a test (the view's model binding does +/// not decide). The messages are the attributes' (The User name field is required.). +/// +public static class ScreenValidator +{ + /// Field name to messages for every failed rule of ; empty when it is valid. A null form is one form-level error. + public static Dictionary Validate(object? form) + { + if (form == null) return new Dictionary { [string.Empty] = new[] { "The request has no content." } }; + + var results = new List(); + Validator.TryValidateObject(form, new ValidationContext(form), results, validateAllProperties: true); + + var errors = new Dictionary(StringComparer.Ordinal); + foreach (var result in results) + { + var message = result.ErrorMessage ?? "The value is not valid."; + var names = result.MemberNames.Any() ? result.MemberNames : new[] { string.Empty }; + foreach (var name in names) + { + errors[name] = errors.TryGetValue(name, out var existing) ? existing.Append(message).ToArray() : new[] { message }; + } + } + + return errors; + } + + /// The same errors with one more message under (a rule the attributes cannot say). + public static Dictionary With(Dictionary errors, string field, string message) + { + errors[field] = errors.TryGetValue(field, out var existing) ? existing.Append(message).ToArray() : new[] { message }; + + return errors; + } +} diff --git a/src/BaGet.Identity.Application/Screens/UiApiJson.cs b/src/BaGet.Identity.Application/Screens/UiApiJson.cs new file mode 100644 index 000000000..1b7b7bca8 --- /dev/null +++ b/src/BaGet.Identity.Application/Screens/UiApiJson.cs @@ -0,0 +1,26 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace BaGet.Identity.Application.Screens; + +/// The JSON of /api/ui: camelCase, enums as their names, nulls left out (the same shape as the administration API). +public static class UiApiJson +{ + /// The serializer options of every UI API response. + public static JsonSerializerOptions Options { get; } = Create(); + + private static JsonSerializerOptions Create() + { + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + // Explicit: an output formatter makes the options read-only, which needs a resolver. + TypeInfoResolver = new DefaultJsonTypeInfoResolver(), + }; + options.Converters.Add(new JsonStringEnumConverter()); + options.Converters.Add(new HtmlStringConverter()); + + return options; + } +} diff --git a/src/BaGet.Identity.Application/Security/AccountConfirmation.cs b/src/BaGet.Identity.Application/Security/AccountConfirmation.cs new file mode 100644 index 000000000..5f190d163 --- /dev/null +++ b/src/BaGet.Identity.Application/Security/AccountConfirmation.cs @@ -0,0 +1,122 @@ +using System; +using System.Text; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Email; + +namespace BaGet.Identity.Application.Security; + +/// +/// The rules behind every sensitive account action (change email, set a password, delete the account, turn two-factor off or reset it), shared +/// by the account use cases and by the screens that have not moved yet (AccountSupport forwards here). +/// +public static class AccountConfirmation +{ + /// How long a sign-in with the external provider counts as proof of presence for a sensitive action. + public static readonly TimeSpan ReauthenticationWindow = TimeSpan.FromMinutes(5); + + /// The sign-in cookie property that holds the time (ticks, UTC) of the last re-authentication. + public const string ReauthenticatedItem = "baget.reauthenticated"; + + /// + /// The check behind every sensitive action. An account with a password types it again; one without (external sign-in + /// only) must have signed in again with its provider a moment ago. A locked-out account never confirms; a wrong password is counted. + /// + public static async Task IsConfirmedAsync(UserManager users, HttpContext httpContext, BaGetUser? user, string? password) + { + #pragma warning disable CS8604 + if (!await users.HasPasswordAsync(user)) return await HasReauthenticatedRecentlyAsync(httpContext); + + // Like a sign-in: a locked-out account is refused without looking at the password, and a wrong one counts as a failed attempt + // (a refused write while the read-only gate is closed), so confirmations cannot be used to guess a password without limit. + if (await users.IsLockedOutAsync(user)) return false; + if (await users.CheckPasswordAsync(user, password ?? string.Empty)) return true; + await users.AccessFailedAsync(user); + + return false; + #pragma warning restore CS8604 + } + + /// + /// The key that marks a request whose browser session cookie is not a credential (a JSON twin called over HTTP, which + /// accepts API keys and session tokens, or the cookie only with an antiforgery header): nothing may read the cookie for it. + /// + public const string IgnoreSessionItem = "BaGet.IgnoreSessionCookie"; + + /// + /// The key (a , UTC) that holds when the user of a session token (/api/ui/session) signed in: + /// that time stands for the cookie's re-authentication property, so an account without a password confirms a sensitive action within + /// of its (external provider) sign-in. + /// + public const string SessionAuthenticatedItem = "BaGet.SessionAuthenticatedAt"; + + /// The key set while a request is served by a JSON twin over HTTP (the in-process call of a view controller never has it). + public const string OverHttpItem = "BaGet.UiApi.OverHttp"; + + /// The key under which a JSON twin over HTTP records the interactive session that authenticated the request. + public const string InteractiveSessionItem = "BaGet.UiApi.Interactive"; + + /// Whether the request is an interactive session (token, or cookie with the antiforgery header) calling a JSON twin over HTTP. + public static bool IsHttpSession(HttpContext httpContext) => httpContext.Items.ContainsKey(InteractiveSessionItem); + + /// Whether the request is served by a JSON twin over HTTP. + public static bool IsOverHttp(HttpContext httpContext) => httpContext.Items.ContainsKey(OverHttpItem); + + /// The header that carries the password to confirm a GET over HTTP (as on the administration API). + public const string ConfirmPasswordHeader = "X-Confirm-Password"; + + /// Whether the session re-authenticated with the external provider within . + public static async Task HasReauthenticatedRecentlyAsync(HttpContext httpContext) + { + // A session token carries the time of its sign-in; the cookie is not read for it. + if (httpContext.Items.TryGetValue(SessionAuthenticatedItem, out var signedInAt) && signedInAt is DateTime signedIn) + { + var sinceSignIn = httpContext.RequestServices.GetRequiredService().UtcNow - signedIn; + + return sinceSignIn >= TimeSpan.Zero && sinceSignIn <= ReauthenticationWindow; + } + + // A request that does not use the session cookie (/api/ui over HTTP with a key) must not read it here either. + if (httpContext.Items.ContainsKey(IgnoreSessionItem)) return false; + + var authentication = await httpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme); + if (authentication?.Properties == null + || !authentication.Properties.Items.TryGetValue(ReauthenticatedItem, out var value) + || !long.TryParse(value, out var ticks) + || ticks < DateTime.MinValue.Ticks || ticks > DateTime.MaxValue.Ticks) + { + return false; + } + + var age = httpContext.RequestServices.GetRequiredService().UtcNow - new DateTime(ticks, DateTimeKind.Utc); + + return age >= TimeSpan.Zero && age <= ReauthenticationWindow; + } + + /// Identity's tokens carry characters that do not survive a URL, so they travel encoded. + public static string EncodeToken(string token) => PasswordResetLinkSender.EncodeToken(token); + + /// Decodes a token written by , or null. + public static string? DecodeToken(string? code) + { + try + { + #pragma warning disable CS8604 + return Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); + #pragma warning restore CS8604 + } + catch (FormatException) + { + return null; + } + } + + /// The messages of an identity failure as one sentence. + public static string Describe(IdentityResult result) + => string.Join(" ", System.Linq.Enumerable.Select(result.Errors, e => e.Description)); +} diff --git a/src/BaGet.Identity.Application/Security/MaintenanceAwareSignInManager.cs b/src/BaGet.Identity.Application/Security/MaintenanceAwareSignInManager.cs new file mode 100644 index 000000000..6f8028ee4 --- /dev/null +++ b/src/BaGet.Identity.Application/Security/MaintenanceAwareSignInManager.cs @@ -0,0 +1,106 @@ +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Services.Sessions; +using BaGet.Identity.Application.UseCases.Account; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Identity.Application.Security; + +/// +/// The sign-in manager, made to work while the is closed. +/// +/// +/// A successful sign-in only needs to read the database, but Identity also writes the user on the way: it resets the +/// failed-attempt counter. With the gate closed that write is refused (503), which would keep an administrator who is +/// not signed in from reaching the Settings page after a database copy, where the status and the restart instructions +/// are. The rule is: while the gate is closed a sign-in completes without its incidental, non-essential writes (here, the +/// counter reset, which is retried by the next sign-in once the gate is open); every other write stays refused, a wrong +/// password included, because counting the failed attempt is a write. +/// +public class MaintenanceAwareSignInManager : SignInManager +{ + private readonly MaintenanceGate _gate; + + public MaintenanceAwareSignInManager( + UserManager userManager, + IHttpContextAccessor contextAccessor, + IUserClaimsPrincipalFactory claimsFactory, + IOptions optionsAccessor, + ILogger> logger, + IAuthenticationSchemeProvider schemes, + IUserConfirmation confirmation, + MaintenanceGate gate) + : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation) + { + _gate = gate; + } + + /// + /// An account awaiting an administrator's approval () cannot sign in by any + /// route (password, two-factor, external provider): every one of them asks here first, and the result is the + /// same "not allowed" as an unconfirmed email. + /// + public override async Task CanSignInAsync(BaGetUser user) + => !user.PendingApproval && await base.CanSignInAsync(user); + + /// + /// For an account that may not sign in yet (awaiting approval, or an unconfirmed email) Identity answers "not allowed" before it looks at the password or the lockout, + /// which would let anyone guess passwords without limit and learn from the answer which one is right. Here the + /// lockout is honoured first (a locked-out account answers "locked out" whatever the password), a wrong password + /// is a counted failed attempt (a write, so refused while the gate is closed like any failed sign-in), and only + /// the right one answers "not allowed". Nothing about the password is learned from a locked-out account, and the existence of an + /// unconfirmed account is not revealed to a wrong password. + /// + public override async Task CheckPasswordSignInAsync(BaGetUser user, string password, bool lockoutOnFailure) + { + if (user == null || await CanSignInAsync(user)) return await base.CheckPasswordSignInAsync(user!, password, lockoutOnFailure); + + if (await UserManager.IsLockedOutAsync(user)) return SignInResult.LockedOut; + + if (await UserManager.CheckPasswordAsync(user, password)) return SignInResult.NotAllowed; + + if (UserManager.SupportsUserLockout && lockoutOnFailure) + { + // Like Identity: an attempt that could not be recorded (a concurrent update) is a plain failure. + var counted = await UserManager.AccessFailedAsync(user); + if (counted.Succeeded && await UserManager.IsLockedOutAsync(user)) return SignInResult.LockedOut; + } + + return SignInResult.Failed; + } + + /// + /// Keeps the current session signed in after a change of the security stamp. A cookie session gets a new cookie. A token session (/api/ui with a + /// session token) has no cookie: it gets a renewed pair of tokens in the response headers (), with the same authentication time. + /// + public override async Task RefreshSignInAsync(BaGetUser user) + { + if (Context != null && Context.Items.TryGetValue(AccountConfirmation.SessionAuthenticatedItem, out var signedIn) && signedIn is System.DateTime authenticatedAt) + { + // Only the caller's own account gets tokens (a stamp change of another account, an administrator's action, renews nothing). + var session = Context.RequestServices.GetService(); + if (session != null && Context.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value == user.Id) + { + var pair = await session.IssueAsync(user, authenticatedAt); + Context.Response.Headers[SessionHeaders.AccessToken] = pair.AccessToken; + Context.Response.Headers[SessionHeaders.AccessExpires] = pair.ExpiresAt?.ToString("O", System.Globalization.CultureInfo.InvariantCulture); + Context.Response.Headers[SessionHeaders.RefreshToken] = pair.RefreshToken; + Context.Response.Headers[SessionHeaders.RefreshExpires] = pair.RefreshExpiresAt?.ToString("O", System.Globalization.CultureInfo.InvariantCulture); + Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "no-store"; + } + + return; + } + + await base.RefreshSignInAsync(user); + } + + /// Resets the failed-attempt counter, unless the gate is closed (a write it would refuse). + protected override Task ResetLockout(BaGetUser user) + => _gate.IsClosed ? Task.CompletedTask : base.ResetLockout(user); +} diff --git a/src/BaGet.Identity.Application/Security/ManagePermission.cs b/src/BaGet.Identity.Application/Security/ManagePermission.cs new file mode 100644 index 000000000..0ed5b1c82 --- /dev/null +++ b/src/BaGet.Identity.Application/Security/ManagePermission.cs @@ -0,0 +1,57 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Identity.Application.Security; + +/// +/// Whether a signed-in user holds an access model action on a package in the current repository: the permission half of +/// the Manage page's rule ( for owners, for unlisting and +/// deleting, for deprecation and vulnerabilities, as the protocol endpoints ask). Ownership is the other half (D4 of the access plan: a +/// permission is necessary, ownership remains necessary); administrators hold every action. +/// +public static class ManagePermission +{ + /// The request's services. + /// The signed-in user. + /// The package ID. + /// The cancellation token. + public static Task HeldAsync(IServiceProvider services, ClaimsPrincipal user, string? packageId, CancellationToken cancellationToken) + => HeldAsync(services, user, packageId, AccessAction.Manage, cancellationToken); + + /// Whether the user holds any of the actions the Manage page's handlers need (enough to open the page and see its link). + /// The request's services. + /// The signed-in user. + /// The package ID. + /// The cancellation token. + public static async Task HeldAnyAsync(IServiceProvider services, ClaimsPrincipal user, string? packageId, CancellationToken cancellationToken) + { + foreach (var action in new[] { AccessAction.Manage, AccessAction.Delete, AccessAction.Annotate }) + { + if (await HeldAsync(services, user, packageId, action, cancellationToken).ConfigureAwait(false)) return true; + } + + return false; + } + + /// Whether the user holds on the package. + /// The request's services. + /// The signed-in user. + /// The package ID. + /// The access model action. + /// The cancellation token. + public static async Task HeldAsync(IServiceProvider services, ClaimsPrincipal user, string? packageId, AccessAction action, CancellationToken cancellationToken) + { + var sessions = services.GetService(); + var evaluator = services.GetService(); + if (sessions == null || evaluator == null) return true; + + var principal = await sessions.CreateAsync(user).ConfigureAwait(false); + var repository = services.GetRequiredService().Current; + + return await evaluator.IsAllowedAsync(principal, repository, packageId, action, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Identity.Application/Security/ScanAccess.cs b/src/BaGet.Identity.Application/Security/ScanAccess.cs new file mode 100644 index 000000000..30d34c5ba --- /dev/null +++ b/src/BaGet.Identity.Application/Security/ScanAccess.cs @@ -0,0 +1,30 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Identity.Application.Security; + +/// +/// Who may start a vulnerability scan of one version from the web UI: a signed-in user who may manage the package in the request's +/// repository (the Manage action of the access model plus ownership where the format has it, or an administrator). Scans cost the +/// server work and a call to the vulnerability source, so a reader cannot start them; the result itself is public to anyone who can +/// read the package. +/// +public static class ScanAccess +{ + /// Whether may scan in the request's repository. + public static async Task CanScanAsync(IServiceProvider services, ClaimsPrincipal? user, string name, CancellationToken cancellationToken) + { + if (user?.Identity?.IsAuthenticated != true) return false; + + var sessions = services.GetService(); + var principal = sessions == null ? null : await sessions.CreateAsync(user); + if (principal == null) return false; + + // The same decision as the package's Manage page. + return await services.GetRequiredService().AuthorizeAsync(principal, PackageAction.Manage, name, cancellationToken); + } +} diff --git a/src/BaGet.Identity.Application/Security/SessionPrincipalFactory.cs b/src/BaGet.Identity.Application/Security/SessionPrincipalFactory.cs new file mode 100644 index 000000000..4da5f74f0 --- /dev/null +++ b/src/BaGet.Identity.Application/Security/SessionPrincipalFactory.cs @@ -0,0 +1,54 @@ +using System; +using System.Security.Claims; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.Security; + +/// +/// Turns a signed-in browser session into a , so the browser +/// path is authorized by exactly the rules the API key path is. +/// +public class SessionPrincipalFactory : ISessionPrincipalFactory +{ + private readonly UserManager _users; + + public SessionPrincipalFactory(UserManager users) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + } + + /// + /// A session carries every scope - the user could create a key with all of them + /// anyway - and a glob that matches every ID. Ownership still decides: + /// requires the user to own an existing + /// ID, so a session may push a new ID or one its user owns, and nothing else. It is + /// never the superuser; an administrator's session carries . + /// + /// Null when nobody is signed in or the account no longer exists. + public async Task CreateAsync(ClaimsPrincipal? user) + { + if (user?.Identity?.IsAuthenticated != true) return null; + + var userId = _users.GetUserId(user); + if (string.IsNullOrEmpty(userId)) return null; + + var account = await _users.FindByIdAsync(userId); + if (account == null || account.PendingApproval) return null; + + return For(account, user.Identity.Name); + } + + /// The principal of an interactive session of (see ). + internal static BaGetPrincipal For(BaGetUser account, string? userName = null) + => new( + userId: account.Id, + userName: userName ?? account.UserName, + isSuperuser: false, + scopes: ApiKeyScopes.All, + packageGlobPattern: "*", + isAdministrator: account.IsAdministrator, + isInteractiveSession: true); +} \ No newline at end of file diff --git a/src/BaGet.Identity.Application/Security/SessionReturnUrls.cs b/src/BaGet.Identity.Application/Security/SessionReturnUrls.cs new file mode 100644 index 000000000..4272e8a57 --- /dev/null +++ b/src/BaGet.Identity.Application/Security/SessionReturnUrls.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BaGet.Identity.Application.Security; + +/// +/// Where the external sign-in of a single-page application may send the tokens it issued (in the URL fragment). A wrong rule would hand a user's +/// tokens to a hostile page, so the answer is strict: a path of this server, or an absolute address whose origin is this server's or one the operator listed +/// (Cors:AllowedOrigins). An empty list does not mean "any origin" here, unlike for CORS. +/// +public static class SessionReturnUrls +{ + /// Whether tokens may be returned to . + /// The address the application asked to return to. + /// This server's origin as the request reached it (https://baget.example.com). + /// The operator's list of origins (see ). + /// The path of the single-page application (/app): a same-origin address must lie under it (/ allows any path). + public static bool IsAllowed(string? returnUrl, string requestOrigin, IEnumerable allowedOrigins, string spaBasePath = "/") + { + if (string.IsNullOrWhiteSpace(returnUrl) || returnUrl.Length > 2048) return false; + if (returnUrl.Any(c => char.IsControl(c) || c == '\\' || c == '#')) return false; + + // A path of this server ("/app/"), but not "//host" or "/\host", which a browser reads as another host. + if (returnUrl[0] == '/') + { + if (returnUrl.Length > 1 && (returnUrl[1] == '/' || returnUrl[1] == '\\')) return false; + + // Judged by the path the browser will request: dot segments (also written %2e) and encoded separators are resolved, or refused. + if (returnUrl.Contains("%2e", StringComparison.OrdinalIgnoreCase) || returnUrl.Contains("%2f", StringComparison.OrdinalIgnoreCase) + || returnUrl.Contains("%5c", StringComparison.OrdinalIgnoreCase)) return false; + if (!Uri.TryCreate(new Uri("http://baget.invalid"), returnUrl, out var relative)) return false; + + return UnderBase(relative.AbsolutePath, spaBasePath); + } + + if (!Uri.TryCreate(returnUrl, UriKind.Absolute, out var uri)) return false; + if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false; + if (!string.IsNullOrEmpty(uri.UserInfo)) return false; + + var origin = Normalize(uri.GetLeftPart(UriPartial.Authority)); + + return (string.Equals(origin, Normalize(requestOrigin), StringComparison.OrdinalIgnoreCase) && UnderBase(uri.PathAndQuery, spaBasePath)) + || allowedOrigins.Any(allowed => string.Equals(origin, Normalize(allowed), StringComparison.OrdinalIgnoreCase)); + } + + /// The origins of a setting such as Cors:AllowedOrigins: separated by semicolons (or commas), blanks dropped. + public static IReadOnlyList Origins(string? setting) + => (setting ?? string.Empty) + .Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(Normalize) + .ToList(); + + // "/app" admits "/app", "/app/", "/app/x" and "/app?x", not "/application" or "/other"; the root admits everything. + private static bool UnderBase(string pathAndQuery, string spaBasePath) + { + var path = pathAndQuery.Split('?')[0]; + var root = (spaBasePath ?? "/").Trim().TrimEnd('/'); + if (root.Length == 0) return true; + + return string.Equals(path, root, StringComparison.OrdinalIgnoreCase) || path.StartsWith(root + "/", StringComparison.OrdinalIgnoreCase); + } + + private static string Normalize(string origin) => origin.Trim().TrimEnd('/'); +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/AccountApprovalResult.cs b/src/BaGet.Identity.Application/Services/Accounts/AccountApprovalResult.cs new file mode 100644 index 000000000..56d2c2092 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AccountApprovalResult.cs @@ -0,0 +1,17 @@ +namespace BaGet.Identity.Application.Services.Accounts; + +/// The outcome of . +public enum AccountApprovalResult +{ + /// The account is enabled and can sign in. + Approved, + + /// The account was not waiting for approval. + NotPending, + + /// There is no such user. + UserNotFound, + + /// The account changed or was deleted while it was being approved; nothing was approved. + Conflict, +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/AccountApprovalService.cs b/src/BaGet.Identity.Application/Services/Accounts/AccountApprovalService.cs new file mode 100644 index 000000000..eb251fab5 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AccountApprovalService.cs @@ -0,0 +1,58 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Enables the accounts that wait for an administrator (, set for self-registered +/// accounts while Accounts:RequireApproval is on). Rejecting an account is deleting it (the Users page's Delete). +/// +public class AccountApprovalService +{ + private readonly UserManager _users; + private readonly IContext _context; + private readonly ILogger _logger; + + /// Creates the service. + public AccountApprovalService(UserManager users, IContext context, ILogger logger) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// The number of accounts waiting for approval. + public Task CountPendingAsync(CancellationToken cancellationToken) + => _context.Users.CountAsync(u => u.PendingApproval, cancellationToken); + + /// Enables the user, who can then sign in. A racing delete or edit of the same user is . + /// The user to enable. + /// Who asks, for the log. + /// The cancellation token. + public async Task ApproveAsync(string? userName, string? actor, CancellationToken cancellationToken) + { + var user = string.IsNullOrWhiteSpace(userName) ? null : await _users.FindByNameAsync(userName.Trim()); + if (user == null) return AccountApprovalResult.UserNotFound; + if (!user.PendingApproval) return AccountApprovalResult.NotPending; + + user.PendingApproval = false; + var result = await _users.UpdateAsync(user); // the concurrency stamp rejects a racing edit of the same user + if (!result.Succeeded) + { + // A racing delete or edit (concurrency failure): the account is gone or different, so report it, don't crash. + _logger.LogWarning("{Actor} could not approve {User}: {Errors}", actor, user.UserName, string.Join(" ", result.Errors.Select(e => e.Code))); + + return AccountApprovalResult.Conflict; + } + + _logger.LogWarning("{Actor} approved the account {User}", actor, user.UserName); + + return AccountApprovalResult.Approved; + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/AccountAuthenticationService.cs b/src/BaGet.Identity.Application/Services/Accounts/AccountAuthenticationService.cs new file mode 100644 index 000000000..22313d475 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AccountAuthenticationService.cs @@ -0,0 +1,66 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// The global API key, as before, plus users' own keys. +/// +public class AccountAuthenticationService : Core.IAuthenticationService +{ + private readonly ApiKeyAuthenticationService _globalKey; + private readonly ApiKeyService _apiKeys; + private readonly UserManager _users; + private readonly IOptionsSnapshot _options; + + public AccountAuthenticationService( + ApiKeyAuthenticationService globalKey, + ApiKeyService apiKeys, + UserManager users, + IOptionsSnapshot options) + { + _globalKey = globalKey ?? throw new ArgumentNullException(nameof(globalKey)); + _apiKeys = apiKeys ?? throw new ArgumentNullException(nameof(apiKeys)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public async Task AuthenticateAsync(string? apiKey, CancellationToken cancellationToken) + => await AuthenticatePrincipalAsync(apiKey, cancellationToken) != null; + + public async Task AuthenticatePrincipalAsync(string? apiKey, CancellationToken cancellationToken) + { + // The global key is the superuser, as it always was - but only when one is + // configured. An empty ApiKey means "there is no global key", never "every + // caller is the superuser": enabling accounts is asking for ownership to decide + // who may push what, and a superuser principal skips ownership entirely, so + // treating the open-server default as a free pass would make the ownership gate + // bypassable by simply sending no key at all. + if (!string.IsNullOrEmpty(_options.Value.ApiKey) + && await _globalKey.AuthenticateAsync(apiKey, cancellationToken)) + { + return BaGetPrincipal.Superuser; + } + + var key = await _apiKeys.FindValidOrNullAsync(apiKey, cancellationToken); + if (key == null) return null; + + #pragma warning disable CS8604 + var user = await _users.FindByIdAsync(key.UserId); + #pragma warning restore CS8604 + if (user == null || user.PendingApproval) return null; + + return new BaGetPrincipal( + user.Id, + user.UserName, + isSuperuser: false, + key.Scopes, + key.PackageGlobPattern, + isAdministrator: user.IsAdministrator, + repositoryKeys: await _apiKeys.RepositoryKeysAsync(key.Key, cancellationToken)); + } +} \ No newline at end of file diff --git a/src/BaGet.Identity.Application/Services/Accounts/AccountDeletionService.cs b/src/BaGet.Identity.Application/Services/Accounts/AccountDeletionService.cs new file mode 100644 index 000000000..62630d2f7 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AccountDeletionService.cs @@ -0,0 +1,423 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using BaGet.Identity.Application.Services.Organizations; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Atomically deletes a user together with what hangs off them: API keys, organization memberships +/// and package ownerships. The ownership rows go too, because they are keyed by name and a +/// later user registering the same name would otherwise inherit the packages. +/// +public class AccountDeletionService +{ + private readonly IContext _context; + private readonly UserManager _users; + private readonly IServiceScopeFactory _scopes; + private readonly IRepositoryService _repositories; + private readonly ILogger _logger; + + public AccountDeletionService( + IContext context, + UserManager users, + IServiceScopeFactory scopes, + IRepositoryService repositories, + ILogger logger) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task GetBlockersAsync(BaGetUser? user, CancellationToken cancellationToken) + { + #pragma warning disable CS8602 + var name = user.UserName?.ToLowerInvariant(); + #pragma warning restore CS8602 + + #pragma warning disable CS8602, CS8604 + // Ownership is per repository, and an account belongs to the whole server: look in every repository. + var owned = await _context.PackageOwners + .IgnoreQueryFilters() + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == name) + .Select(o => new { o.RepositoryKey, o.PackageId }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + var lastOwner = new List<(int RepositoryKey, string? PackageId)>(); + foreach (var entry in owned + .GroupBy(o => (o.RepositoryKey, Id: o.PackageId?.ToLowerInvariant())) + .Select(g => g.First()) + .OrderBy(o => o.PackageId, StringComparer.OrdinalIgnoreCase) + .ThenBy(o => o.RepositoryKey)) + { + var id = entry.PackageId?.ToLowerInvariant(); + var repositoryKey = entry.RepositoryKey; + #pragma warning disable CS8602 + if (await _context.PackageOwners.IgnoreQueryFilters().CountAsync( + o => o.RepositoryKey == repositoryKey && o.PackageId.ToLower() == id, cancellationToken) == 1) + #pragma warning restore CS8602 + { + lastOwner.Add((repositoryKey, entry.PackageId)); + } + } + + var blocking = new List(); + foreach (var organization in await OrganizationsToLeaveAsync(user, cancellationToken)) + { + #pragma warning disable CS8602 + var blocked = organization.OtherMembers > 0 + ? organization.IsLastAdmin + : await OrganizationOwnsPackagesAsync(organization.Name, cancellationToken); + #pragma warning restore CS8602 + + if (blocked) blocking.Add(organization.Name); + } + + // Same rule as AdministratorService.IsLastAdministratorAsync. + var lastAdministrator = user.IsAdministrator + && await _context.Users.CountAsync(u => u.IsAdministrator, cancellationToken) <= 1; + + var known = lastOwner.Count == 0 + ? new Dictionary() + : (await _repositories.ListAsync(cancellationToken)).ToDictionary(r => r.Key); + + return new DeletionBlockers( + lastOwner.Select(o => o.PackageId).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), + blocking, + lastAdministrator, + lastOwner + .Select(o => new SoleOwnedPackage( + o.RepositoryKey, + known.TryGetValue(o.RepositoryKey, out var found) ? found.Name : Repository.DefaultName, + o.PackageId, + found?.Format ?? RepositoryFormat.NuGet)) + .ToList()); + } + + /// + /// Delete the user, or return the reasons it cannot be done. + /// + public async Task<(DeletionBlockers Blockers, IdentityResult Result)> DeleteAsync(BaGetUser? user, CancellationToken cancellationToken) + { + var blockers = await GetBlockersAsync(user, cancellationToken); + #pragma warning disable CS8619 + if (blockers.Any) return (blockers, null); + #pragma warning restore CS8619 + + await StageCleanupAsync(user, administrator: false, cancellationToken); + + return (blockers, await SaveDeletionAsync(user)); + } + + /// + /// Delete another user as an administrator. Unlike nothing but + /// blocks it: an organization whose last + /// administrator leaves hands the role to its longest-standing member, an organization of one + /// that owns packages is kept without members, and the IDs only this user owned are either + /// left without owners or deleted. The package deletion runs after the user is gone and + /// never undoes it: failures are returned. + /// + /// The user to delete. + /// Delete the sole-owned IDs with all their versions instead of leaving them ownerless. + /// The administrator, for the log. + /// The cancellation token. + public async Task DeleteByAdministratorAsync( + BaGetUser? user, bool deleteSoleOwnedPackages, string? actor, CancellationToken cancellationToken) + { + var none = Array.Empty(); + + var blockers = await GetBlockersAsync(user, cancellationToken); + if (blockers.LastAdministrator) + { + return new AdminDeletionResult( + IdentityResult.Failed(new IdentityError { Description = "The last administrator cannot be deleted. Promote another user first." }), + none, none, none); + } + + // The IDs only this user owned, in every repository: each is removed from its own repository. + var soleOwned = blockers.LastOwnerPackages; + var userName = user?.UserName; + + await StageCleanupAsync(user, administrator: true, cancellationToken); + var result = await SaveDeletionAsync(user); + if (!result.Succeeded) return new AdminDeletionResult(result, none, none, none); + + var deleted = new List(); + var failures = new List(); + if (deleteSoleOwnedPackages) + { + var repositories = (await _repositories.ListAsync(cancellationToken)).ToDictionary(r => r.Key); + foreach (var package in soleOwned) + { + try + { + if (!repositories.TryGetValue(package.RepositoryKey, out var repository)) + { + failures.Add(package.Label); + continue; + } + + // The deletion services work in the repository their scope is pinned to. + using var scope = _scopes.CreateRepositoryScope(repository); + + if (repository.Format == RepositoryFormat.Npm) + { + // An npm package is unpublished whole, as the administrator the deletion is done by. + var administrator = new BaGetPrincipal(null, actor, isSuperuser: false, ApiKeyScopes.All, "*", isAdministrator: true); + var outcome = await scope.ServiceProvider.GetRequiredService() + .UnpublishPackageAsync(administrator, package.PackageId?.ToLowerInvariant() ?? string.Empty, cancellationToken); + if (outcome.Succeeded || outcome.Status == NpmStatus.NotFound) deleted.Add(package.Label); else failures.Add(package.Label); + + continue; + } + + if (repository.Format == RepositoryFormat.Maven) + { + // A Maven artifact is deleted whole (every version and file), as the administrator the deletion is done by. + var administrator = new BaGetPrincipal(null, actor, isSuperuser: false, ApiKeyScopes.All, "*", isAdministrator: true); + var deletedArtifact = MavenNames.TryParseArtifactName(package.PackageId, out var mavenGroup, out var mavenArtifact) + ? await scope.ServiceProvider.GetRequiredService().DeleteArtifactAsync(administrator, mavenGroup, mavenArtifact, cancellationToken) + : null; + if (deletedArtifact != null && (deletedArtifact.Succeeded || deletedArtifact.Status == MavenStatus.NotFound)) deleted.Add(package.Label); else failures.Add(package.Label); + + continue; + } + + var packages = scope.ServiceProvider.GetRequiredService(); + var deletion = scope.ServiceProvider.GetRequiredService(); + + var versions = await packages.FindAsync(package.PackageId, includeUnlisted: true, cancellationToken); + var failed = false; + foreach (var version in versions) + { + failed |= !await deletion.TryHardDeletePackageAsync(package.PackageId, version.Version, cancellationToken); + } + + if (failed) failures.Add(package.Label); else deleted.Add(package.Label); + } + catch (Exception e) when (e is not OperationCanceledException and not MaintenanceException) + { + _logger.LogError(e, "Could not delete package {Id} ({Repository}) of deleted user {User}", package.PackageId, package.RepositoryName, userName); + failures.Add(package.Label); + } + } + } + + var kept = deleteSoleOwnedPackages + ? new List() + : soleOwned.Select(p => p.Label).ToList(); + _logger.LogWarning( + "{Admin} deleted user {User}; sole-owned IDs {Ids} {Outcome}", + actor, userName, string.Join(", ", soleOwned.Select(p => p.Label)), deleteSoleOwnedPackages ? "deleted" : "kept without owners"); + + return new AdminDeletionResult(result, kept, deleted, failures); + } + + /// What would do to , for the confirmation page. + public async Task PreviewAdministratorDeletionAsync(BaGetUser user, CancellationToken cancellationToken) + { + var name = user.UserName?.ToLowerInvariant(); + var blockers = await GetBlockersAsync(user, cancellationToken); + + #pragma warning disable CS8602, CS8604 + var direct = (await _context.PackageOwners + .IgnoreQueryFilters() + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == name) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(i => i, StringComparer.OrdinalIgnoreCase) + .ToList(); + #pragma warning restore CS8602, CS8604 + + var outcomes = new List(); + foreach (var organization in await OrganizationsToLeaveAsync(user, cancellationToken)) + { + string outcome; + if (organization.OtherMembers == 0) + { + #pragma warning disable CS8602 + outcome = await OrganizationOwnsPackagesAsync(organization.Name, cancellationToken) + ? "The organization owns packages, so it is kept without members." + : "The organization has no other member and is deleted."; + #pragma warning restore CS8602 + } + else if (organization.IsLastAdmin) + { + #pragma warning disable CS8604 + var successor = await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.OrganizationKey == organization.Key && m.UserId != user.Id) + .OrderBy(m => m.Key) + .Select(m => m.UserId) + .FirstAsync(cancellationToken); + var successorName = (await _users.FindByIdAsync(successor))?.UserName ?? successor; + #pragma warning restore CS8604 + + outcome = $"{successorName}, its longest-standing member, becomes its administrator."; + } + else + { + outcome = "The user leaves the organization."; + } + + outcomes.Add(new OrganizationOutcome(organization.Name, outcome)); + } + + #pragma warning disable CS8602 + var keys = await _context.ApiKeys?.CountAsync(k => k.UserId == user.Id, cancellationToken); + #pragma warning restore CS8602 + + return new AdminDeletionPreview(keys, direct, blockers.LastOwnerPackages, outcomes); + } + + /// + /// Stage the removal of the user's API keys, ownerships and memberships; nothing is saved + /// until the user itself is deleted. + /// + /// The user being deleted. + /// + /// An administrator is deleting: the last administrator of an organization with other members + /// is replaced by its longest-standing member, and an organization of one that owns packages + /// is kept. Otherwise those cases were refused beforehand. + /// + /// The cancellation token. + private async Task StageCleanupAsync(BaGetUser? user, bool administrator, CancellationToken cancellationToken) + { + #pragma warning disable CS8602 + var keys = await _context.ApiKeys?.Where(k => k.UserId == user.Id).ToListAsync(cancellationToken); + #pragma warning restore CS8602 + _context.ApiKeys?.RemoveRange(keys); + + var name = user?.UserName?.ToLowerInvariant(); + #pragma warning disable CS8602 + var ownerships = await _context.PackageOwners?.IgnoreQueryFilters().Where(o => o.OwnerName.ToLower() == name).ToListAsync(cancellationToken); + #pragma warning restore CS8602 + _context.PackageOwners?.RemoveRange(ownerships); + + await StageAccessCleanupAsync(PrincipalType.User, user?.Id, cancellationToken); + + // A membership of no organization (OrganizationKey is optional, a legacy row) is not found by OrganizationsToLeaveAsync, but + // OrganizationMember.UserId is a foreign key to the user. + #pragma warning disable CS8602 + _context.OrganizationMembers.RemoveRange(await _context.OrganizationMembers.Where(m => m.UserId == user.Id && m.OrganizationKey == null).ToListAsync(cancellationToken)); + #pragma warning restore CS8602 + + foreach (var organization in await OrganizationsToLeaveAsync(user, cancellationToken)) + { + #pragma warning disable CS8604 + var members = await _context.OrganizationMembers + .Where(m => m.OrganizationKey == organization.Key) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + if (administrator && organization.OtherMembers > 0 && organization.IsLastAdmin) + { + members.Where(m => m.UserId != user?.Id).OrderBy(m => m.Key).First().IsAdmin = true; + } + + // An organization of one with nothing to its name goes with its only member; an + // administrator's deletion keeps one that owns packages, without members. + #pragma warning disable CS8602 + var removeOrganization = organization.OtherMembers == 0 + && !(administrator && await OrganizationOwnsPackagesAsync(organization.Name, cancellationToken)); + #pragma warning restore CS8602 + _context.OrganizationMembers.RemoveRange(removeOrganization ? members : members.Where(m => m.UserId == user?.Id)); + if (removeOrganization) + { + await StageAccessCleanupAsync(PrincipalType.Organization, organization.Key.ToString(), cancellationToken); + #pragma warning disable CS8602 + _context.Organizations?.RemoveRange(await _context.Organizations?.Where(o => o.Key == organization.Key).ToListAsync(cancellationToken)); + #pragma warning restore CS8602 + } + } + } + + // A deleted user, or organization, leaves the access model with them: group memberships (users only), permission + // grants and project roles that name them. Orphans would be harmless to a decision (nobody can present that + // identity again) but would linger in the admin pages. Staged with the rest of the cleanup. + private Task StageAccessCleanupAsync(PrincipalType type, string? id, CancellationToken cancellationToken) + => AccessAdministration.StageCleanupAsync(_context, type, id, cancellationToken); + + // The cleanup is only staged. Deleting the user saves it in the same SaveChanges, so the + // database applies all of it or none of it: a user that cannot be deleted keeps its keys, + // ownerships and memberships. + private async Task SaveDeletionAsync(BaGetUser? user) + { + try + { + #pragma warning disable CS8604 + var result = await _users.DeleteAsync(user); + #pragma warning restore CS8604 + if (!result.Succeeded) Discard(); + + return result; + } + catch + { + Discard(); + throw; + } + } + + /// + /// Forget the staged cleanup, so a later save in the same scope cannot apply it. + /// + private void Discard() + { + if (_context is DbContext context) context.ChangeTracker.Clear(); + } + + private async Task> OrganizationsToLeaveAsync(BaGetUser? user, CancellationToken cancellationToken) + { + #pragma warning disable CS8602, CS8604 + var mine = await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.UserId == user.Id && m.Organization != null) + .Select(m => new { m.OrganizationKey, m.IsAdmin, m.Organization.Name }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + var result = new List(); + foreach (var membership in mine) + { + #pragma warning disable CS8602 + var others = await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.OrganizationKey == membership.OrganizationKey && m.UserId != user.Id) + .Select(m => m.IsAdmin) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602 + + result.Add(new OrganizationMembership( + membership.OrganizationKey.GetValueOrDefault(), + membership.Name, + membership.IsAdmin && !others.Any(isAdmin => isAdmin), + others.Count)); + } + + return result; + } + + private Task? OrganizationOwnsPackagesAsync(string? organization, CancellationToken cancellationToken) + { + var name = organization?.ToLowerInvariant(); + + #pragma warning disable CS8602 + return _context.PackageOwners?.IgnoreQueryFilters().AnyAsync(o => o.OwnerName.ToLower() == name, cancellationToken); + #pragma warning restore CS8602 + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/AccountRecoveryService.cs b/src/BaGet.Identity.Application/Services/Accounts/AccountRecoveryService.cs new file mode 100644 index 000000000..6900e97fc --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AccountRecoveryService.cs @@ -0,0 +1,95 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Administrator recovery of an account, for the command line. It needs no email, so it +/// works whether or not SMTP is configured. +/// +public class AccountRecoveryService +{ + private const string Upper = "ABCDEFGHJKLMNPQRSTUVWXYZ"; + private const string Lower = "abcdefghijkmnopqrstuvwxyz"; + private const string Digits = "23456789"; + private const string Symbols = "!@#$%*-_=+?"; + + private readonly UserManager _users; + + public AccountRecoveryService(UserManager users) => _users = users; + + /// + /// Replace the user's password with a generated one and return it, or null if there is + /// no such user. Two-factor authentication is switched off, its key discarded, and any + /// lockout lifted, so this also recovers a user who lost their authenticator. The user's + /// email address is marked confirmed; sets and confirms one. + /// + public async Task ResetPasswordAsync(string? userName, CancellationToken cancellationToken, string? email = null) + { + if (string.IsNullOrWhiteSpace(userName)) return null; + + #pragma warning disable CS8604 + var user = await _users.FindByNameAsync(userName); + #pragma warning restore CS8604 + if (user == null) return null; + + // Whoever runs this command is the administrator, so the address is trusted: it is + // confirmed, or replaced by and confirmed. Without that, a + // user with no confirmed address could never sign in once SMTP is switched on. + if (!string.IsNullOrWhiteSpace(email)) + { + Check(await _users.SetEmailAsync(user, email.Trim())); + } + + if (!string.IsNullOrEmpty(user.Email) && !user.EmailConfirmed) + { + Check(await _users.ConfirmEmailAsync(user, await _users.GenerateEmailConfirmationTokenAsync(user))); + } + + var password = GeneratePassword(); + + var token = await _users.GeneratePasswordResetTokenAsync(user); + Check(await _users.ResetPasswordAsync(user, token, password)); + Check(await _users.SetTwoFactorEnabledAsync(user, false)); + Check(await _users.ResetAuthenticatorKeyAsync(user)); + Check(await _users.SetLockoutEndDateAsync(user, null)); + Check(await _users.ResetAccessFailedCountAsync(user)); + + return password; + } + + /// + /// A random password with a character of every class Identity's default policy asks for. + /// + internal static string GeneratePassword() + { + var chars = new char[20]; + var all = Upper + Lower + Digits + Symbols; + + chars[0] = Pick(Upper); + chars[1] = Pick(Lower); + chars[2] = Pick(Digits); + chars[3] = Pick(Symbols); + for (var i = 4; i < chars.Length; i++) chars[i] = Pick(all); + + RandomNumberGenerator.Shuffle(chars.AsSpan()); + + return new string(chars); + } + + private static char Pick(string alphabet) => alphabet[RandomNumberGenerator.GetInt32(alphabet.Length)]; + + private static void Check(IdentityResult result) + { + if (!result.Succeeded) + { + throw new InvalidOperationException( + "Could not update the account: " + string.Join("; ", result.Errors.Select(e => e.Description))); + } + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/AdminDeletionPreview.cs b/src/BaGet.Identity.Application/Services/Accounts/AdminDeletionPreview.cs new file mode 100644 index 000000000..38772c214 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AdminDeletionPreview.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using BaGet.Identity.Application.Services.Organizations; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// What deleting a user as an administrator would remove or change. +/// How many API keys go. +/// Package IDs the user owns directly. +/// The subset nobody else owns, in every repository. +/// What happens to each organization the user belongs to. +public record AdminDeletionPreview( + int ApiKeys, + IReadOnlyList DirectPackageIds, + IReadOnlyList SoleOwnedPackages, + IReadOnlyList Organizations); diff --git a/src/BaGet.Identity.Application/Services/Accounts/AdminDeletionResult.cs b/src/BaGet.Identity.Application/Services/Accounts/AdminDeletionResult.cs new file mode 100644 index 000000000..5b020c987 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AdminDeletionResult.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// What an administrator's deletion of a user did. +/// The outcome of deleting the user. Failed with nothing deleted when refused. +/// Sole-owned package IDs left without owners (only admins and the global key manage them), in form. +/// Sole-owned package IDs removed with all their versions, in every repository, in form. +/// What could not be removed after the user was deleted; these IDs stay ownerless; form. +public record AdminDeletionResult( + IdentityResult Result, + IReadOnlyList KeptWithoutOwners, + IReadOnlyList DeletedPackageIds, + IReadOnlyList Failures); diff --git a/src/BaGet.Identity.Application/Services/Accounts/AdminUserCreationService.cs b/src/BaGet.Identity.Application/Services/Accounts/AdminUserCreationService.cs new file mode 100644 index 000000000..15288246c --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AdminUserCreationService.cs @@ -0,0 +1,76 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Creates an account on an administrator's behalf. The same name rule as registration applies (user and +/// organization names share one namespace); the address is trusted, as in +/// , so it is marked confirmed and the user can sign in while SMTP is on. +/// +public class AdminUserCreationService +{ + private readonly UserManager _users; + private readonly PackageOwnershipService _ownership; + private readonly SystemTime _time; + + /// Creates the service. + public AdminUserCreationService(UserManager users, PackageOwnershipService ownership, SystemTime time) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + /// Create the user, or say why not. + /// The user name. + /// The address, or blank for none. + /// Where the first password comes from. + /// The typed password, for . + /// Cancellation. + public async Task CreateAsync( + string? userName, + string? email, + NewUserPasswordMode mode, + string? password, + CancellationToken cancellationToken) + { + var name = userName?.Trim(); + if (string.IsNullOrEmpty(name)) return new NewUserResult(null, "A user name is required."); + if (name.Length > AbstractContext.MaxAccountNameLength || name.Any(c => char.IsControl(c) || "/\\?#%".Contains(c))) + { + return new NewUserResult(null, "That is not a valid user name."); + } + + if (await _ownership.AccountExistsAsync(name, cancellationToken)) return new NewUserResult(null, "That name is taken."); + + var address = string.IsNullOrWhiteSpace(email) ? null : email.Trim(); + if (mode == NewUserPasswordMode.Given && string.IsNullOrEmpty(password)) + { + return new NewUserResult(null, "A password is required."); + } + + var chosen = mode == NewUserPasswordMode.Given ? password! : AccountRecoveryService.GeneratePassword(); + var user = new BaGetUser + { + UserName = name, + Email = address, + EmailConfirmed = address != null, + Created = _time.UtcNow, + }; + + var result = await _users.CreateAsync(user, chosen); + if (!result.Succeeded) + { + return new NewUserResult(null, string.Join(" ", result.Errors.Select(e => e.Description))); + } + + return new NewUserResult(user, null, mode == NewUserPasswordMode.Generated ? chosen : null); + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/AdministratorChange.cs b/src/BaGet.Identity.Application/Services/Accounts/AdministratorChange.cs new file mode 100644 index 000000000..3b1bbd117 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AdministratorChange.cs @@ -0,0 +1,19 @@ +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// The outcome of promoting or demoting a user. +/// +public enum AdministratorChange +{ + /// The flag was changed. + Changed, + + /// The user already had the requested state. + Unchanged, + + /// There is no such user. + UserNotFound, + + /// The user is the only administrator, so cannot be demoted. + LastAdministrator, +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/AdministratorService.cs b/src/BaGet.Identity.Application/Services/Accounts/AdministratorService.cs new file mode 100644 index 000000000..25fad74dc --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AdministratorService.cs @@ -0,0 +1,159 @@ +using System; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Reads and changes . Read from the database on +/// every check, so a demotion takes effect on the next request. +/// +public class AdministratorService +{ + /// The administrator creates on a server with no users. + public const string DefaultAdministratorUserName = "Admin"; + + /// + /// The default administrator's initial password. It is public knowledge, so it must be changed + /// right after the first sign-in; every startup warns while it still works. + /// + public const string DefaultAdministratorPassword = "Admin1234!"; + + private readonly UserManager _users; + private readonly IContext _context; + private readonly SystemTime _time; + private readonly ILogger _logger; + + /// Creates the service. + public AdministratorService(UserManager users, IContext context, SystemTime time, ILogger logger) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// On a server with no users at all, create the administrator + /// with the password , so that a fresh install can be signed in to + /// and configured. Its email counts as confirmed, so it can sign in while SMTP is configured, although it has no + /// address. Once any user exists this does nothing, even if that user is later deleted. + /// + /// Whether the administrator was created. + public async Task CreateDefaultAdministratorAsync(CancellationToken cancellationToken) + { + if (await _context.Users.AnyAsync(cancellationToken)) return false; + + var user = new BaGetUser + { + UserName = DefaultAdministratorUserName, + EmailConfirmed = true, + IsAdministrator = true, + Created = _time.UtcNow, + }; + + var result = await _users.CreateAsync(user, DefaultAdministratorPassword); + + // Several instances starting at once on an empty database may race; the unique user name lets + // only one of them create the account, and the others have nothing left to do. + if (!result.Succeeded && result.Errors.Any(e => e.Code == nameof(IdentityErrorDescriber.DuplicateUserName))) return false; + if (!result.Succeeded) + { + throw new InvalidOperationException(string.Join(" ", result.Errors.Select(e => e.Description))); + } + + _logger.LogWarning( + "There were no users, so the administrator {User} was created with the default password. Sign in and change it now.", + DefaultAdministratorUserName); + + return true; + } + + /// Whether exists and still has the default password. + public async Task HasDefaultPasswordAsync() + { + var user = await _users.FindByNameAsync(DefaultAdministratorUserName); + + return user != null && await _users.CheckPasswordAsync(user, DefaultAdministratorPassword); + } + + /// Whether the signed in user is an administrator, according to the database. + public async Task IsAdministratorAsync(ClaimsPrincipal? principal, CancellationToken cancellationToken) + { + var id = principal == null ? null : _users.GetUserId(principal); + + return !string.IsNullOrEmpty(id) + && await _context.Users.AnyAsync(u => u.Id == id && u.IsAdministrator, cancellationToken); + } + + /// Makes the user an administrator, and approves the account if it was waiting for approval. + /// The user to promote. + /// Who asks, for the log. + /// The cancellation token. + public Task PromoteAsync(string? userName, string? actor, CancellationToken cancellationToken) + => SetAsync(userName, true, actor, cancellationToken); + + /// Removes the user's administrator flag, unless they are the last administrator. + /// The user to demote. + /// Who asks, for the log. + /// The cancellation token. + public Task DemoteAsync(string? userName, string? actor, CancellationToken cancellationToken) + => SetAsync(userName, false, actor, cancellationToken); + + /// Whether the user is an administrator and no other administrator exists. + public async Task IsLastAdministratorAsync(BaGetUser? user, CancellationToken cancellationToken) + { + if (user == null || !user.IsAdministrator) return false; + + return await _context.Users.CountAsync(u => u.IsAdministrator, cancellationToken) <= 1; + } + + /// + /// Bootstraps a server without administrators: promotes the semicolon separated user + /// names, but only while no administrator exists. Once one does, it does nothing, so a + /// listed name registered later is not promoted and a demotion is not reversed at restart. + /// A name with no account is logged and skipped. + /// + public async Task PromoteInitialAdministratorsAsync(string? names, CancellationToken cancellationToken) + { + if (await _context.Users.AnyAsync(u => u.IsAdministrator, cancellationToken)) return; + + var separators = new[] { ';' }; + foreach (var name in (names ?? string.Empty).Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(n => n.Trim()).Where(n => n.Length > 0)) + { + if (await SetAsync(name, true, "configuration", cancellationToken) == AdministratorChange.UserNotFound) + { + _logger.LogWarning("Initial administrator {User} does not exist and was not promoted", name); + } + } + } + + private async Task SetAsync(string? userName, bool value, string? actor, CancellationToken cancellationToken) + { + var user = string.IsNullOrWhiteSpace(userName) ? null : await _users.FindByNameAsync(userName.Trim()); + if (user == null) return AdministratorChange.UserNotFound; + // An administrator is by definition approved: promotion also enables an account that waits for approval + // (Accounts:RequireApproval), else a recovery could leave the only administrator unable to sign in. + var approves = value && user.PendingApproval; + if (user.IsAdministrator == value && !approves) return AdministratorChange.Unchanged; + if (!value && await IsLastAdministratorAsync(user, cancellationToken)) return AdministratorChange.LastAdministrator; + + user.IsAdministrator = value; + if (value) user.PendingApproval = false; + var result = await _users.UpdateAsync(user); // the concurrency stamp rejects a racing edit of the same user + if (!result.Succeeded) + { + throw new InvalidOperationException(string.Join(" ", result.Errors.Select(e => e.Description))); + } + + _logger.LogWarning("{Actor} {Action} {User} as administrator", actor, value ? "promoted" : "demoted", user.UserName); + + return AdministratorChange.Changed; + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/ApiKeyService.cs b/src/BaGet.Identity.Application/Services/Accounts/ApiKeyService.cs new file mode 100644 index 000000000..8a504a102 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/ApiKeyService.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Creates, lists and revokes users' API keys. A key is shown once, when it is created; +/// only its hash is stored. +/// +public class ApiKeyService +{ + /// + /// Marks a BaGet key, so a leaked one is recognisable by secret scanners. + /// + internal const string KeyPrefix = "bgt_"; + + private readonly IContext _context; + private readonly SystemTime _time; + + public ApiKeyService(IContext context, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + /// + /// Create a key and return it in plain text. It cannot be recovered afterwards. + /// + public Task CreateAsync( + string? userId, + string? description, + IReadOnlyList? scopes, + string packageGlobPattern, + DateTime? expires, + CancellationToken cancellationToken) + => CreateAsync(userId, description, scopes, packageGlobPattern, expires, repositoryKeys: null, cancellationToken); + + /// + /// Create a key limited to (), or usable in every + /// repository when null or empty, and return it in plain text. It cannot be recovered afterwards. + /// + /// A repository key does not name an existing repository. + public async Task CreateAsync( + string? userId, + string? description, + IReadOnlyList? scopes, + string packageGlobPattern, + DateTime? expires, + IReadOnlyCollection? repositoryKeys, + CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(userId)) throw new ArgumentException("A user is required.", nameof(userId)); + + var unknown = scopes?.FirstOrDefault(s => !ApiKeyScopes.Assignable.Contains(s, StringComparer.Ordinal)); + if (scopes == null || scopes.Count == 0 || unknown != null) + { + throw new ArgumentException($"Scopes must be some of: {string.Join(", ", ApiKeyScopes.Assignable)}.", nameof(scopes)); + } + + if (scopes.Contains(ApiKeyScopes.Admin, StringComparer.Ordinal) + && !await _context.Users.AnyAsync(u => u.Id == userId && u.IsAdministrator, cancellationToken)) + { + throw new ArgumentException($"The scope {ApiKeyScopes.Admin} is for administrators.", nameof(scopes)); + } + + var limit = repositoryKeys?.Distinct().ToList() ?? new List(); + if (limit.Count > 0) + { + var known = await _context.Repositories! + .Where(r => limit.Contains(r.Key)) + .Select(r => r.Key) + .ToListAsync(cancellationToken); + + if (known.Count != limit.Count) + { + throw new ArgumentException("A chosen repository does not exist.", nameof(repositoryKeys)); + } + } + + var key = KeyPrefix + Base64Url(RandomNumberGenerator.GetBytes(32)); + + var entity = new ApiKey + { + UserId = userId, + Description = description, + HashedKey = Hash(key), + Scopes = scopes.Distinct(StringComparer.Ordinal).ToArray(), + PackageGlobPattern = string.IsNullOrWhiteSpace(packageGlobPattern) ? "*" : packageGlobPattern.Trim(), + Created = _time.UtcNow, + Expires = expires?.ToUniversalTime(), + }; + _context.ApiKeys?.Add(entity); + + // Saved with the key in one transaction: a key never exists half-limited (which would mean unlimited). + foreach (var repositoryKey in limit) + { + _context.ApiKeyRepositories!.Add(new ApiKeyRepository { RepositoryKey = repositoryKey, ApiKey = entity }); + } + + await _context.SaveChangesAsync(cancellationToken); + + return key; + } + + public async Task> ListAsync(string? userId, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + return await _context.ApiKeys + .AsNoTracking() + .Where(k => k.UserId == userId) + .OrderBy(k => k.Key) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + } + + /// + /// The keys of the repositories is limited to, or null when it may be used in every one. + /// + public async Task?> RepositoryKeysAsync(int apiKey, CancellationToken cancellationToken) + { + var keys = await _context.ApiKeyRepositories! + .AsNoTracking() + .Where(r => r.ApiKeyKey == apiKey) + .Select(r => r.RepositoryKey) + .ToListAsync(cancellationToken); + + return keys.Count == 0 ? null : keys; + } + + /// + /// The names of the repositories each of is limited to, by key number; a key that may be + /// used everywhere has no entry. Names are ordered. + /// + public async Task>> RepositoryNamesAsync( + IEnumerable keys, + CancellationToken cancellationToken) + { + var numbers = keys.Select(k => k.Key).ToList(); + if (numbers.Count == 0) return new Dictionary>(); + + var rows = await ( + from limit in _context.ApiKeyRepositories!.AsNoTracking() + join repository in _context.Repositories!.AsNoTracking() on limit.RepositoryKey equals repository.Key + where numbers.Contains(limit.ApiKeyKey) + select new { limit.ApiKeyKey, repository.Name }) + .ToListAsync(cancellationToken); + + return rows + .GroupBy(r => r.ApiKeyKey) + .ToDictionary( + g => g.Key, + g => (IReadOnlyList)g.Select(r => r.Name ?? string.Empty).OrderBy(n => n, StringComparer.Ordinal).ToList()); + } + + /// + /// Text for a key's repository limit: the names, or "all repositories" when it has none + /// ( null or empty). + /// + public static string DescribeRepositories(IReadOnlyList? names) + => names == null || names.Count == 0 ? "all repositories" : string.Join(", ", names); + + /// + /// Revoke one of the user's keys. False if the user has no such key. + /// + public async Task RevokeAsync(string? userId, int key, CancellationToken cancellationToken) + { + #pragma warning disable CS8602 + var apiKey = await _context.ApiKeys?.FirstOrDefaultAsync(k => k.Key == key && k.UserId == userId, cancellationToken); + #pragma warning restore CS8602 + if (apiKey == null) return false; + + _context.ApiKeys?.Remove(apiKey); + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + /// + /// The stored key that matches, if it exists and has not expired. + /// + public async Task FindValidOrNullAsync(string? key, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(key) || !key.StartsWith(KeyPrefix, StringComparison.Ordinal)) return null; + + var hash = Hash(key); + #pragma warning disable CS8604 + var apiKey = await _context.ApiKeys + .AsNoTracking() + .FirstOrDefaultAsync(k => k.HashedKey == hash, cancellationToken); + #pragma warning restore CS8604 + + if (apiKey == null) return null; + if (apiKey.Expires.HasValue && DateTime.SpecifyKind(apiKey.Expires.Value, DateTimeKind.Utc) <= _time.UtcNow) return null; + + return apiKey; + } + + /// + /// A key is 256 random bits, so a fast unsalted hash is enough: there is nothing + /// to brute force, and the lookup by hash must be exact. + /// + internal static string Hash(string key) + { + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(key)); + + return Convert.ToHexString(hash).ToLowerInvariant(); + } + + private static string Base64Url(byte[] bytes) + => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} \ No newline at end of file diff --git a/src/BaGet.Identity.Application/Services/Accounts/AvatarService.cs b/src/BaGet.Identity.Application/Services/Accounts/AvatarService.cs new file mode 100644 index 000000000..92a03c268 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/AvatarService.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Works out the Gravatar address of an account. Each address is a request to gravatar.com +/// that carries a hash of the account's email, so turns +/// them all off; callers then fall back to an initial-letter placeholder. +/// +public class AvatarService +{ + private readonly IContext _context; + private readonly IOptionsSnapshot _site; + + public AvatarService(IContext context, IOptionsSnapshot site) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _site = site ?? throw new ArgumentNullException(nameof(site)); + } + + public bool Enabled => _site.Value.UseGravatar; + + /// + /// The avatar address by account name (case-insensitive), or an empty map when Gravatar + /// is off. A user with an email is identified by it; an organization, or a user without + /// one, by the lowercased name. + /// + public async Task> GetUrlsAsync( + IEnumerable names, + int size, + CancellationToken cancellationToken) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (!Enabled) return result; + + var distinct = names.Where(n => !string.IsNullOrEmpty(n)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + if (distinct.Count == 0) return result; + + var lowered = distinct.Select(n => n?.ToLowerInvariant()).ToList(); + #pragma warning disable CS8602 + var users = await _context.Users + .AsNoTracking() + .Where(u => lowered.Contains(u.UserName.ToLower())) + .Select(u => new { u.UserName, u.Email }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602 + #pragma warning disable CS8621, CS8714 + var emails = users.ToDictionary(u => u.UserName, u => u.Email, StringComparer.OrdinalIgnoreCase); + #pragma warning restore CS8621, CS8714 + + foreach (var name in distinct) + { + emails.TryGetValue(name, out var email); + #pragma warning disable CS8604 + result[name] = GetUrl(string.IsNullOrWhiteSpace(email) ? name : email, size); + #pragma warning restore CS8604 + } + + return result; + } + + /// + /// The Gravatar address of a key: the MD5 of the trimmed, lowercased email (or name). + /// The picture is requested at twice for high-density screens. + /// + public static string GetUrl(string key, int size) + { + var normalized = key.Trim().ToLowerInvariant(); + var hash = Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(normalized))).ToLowerInvariant(); + + return $"https://www.gravatar.com/avatar/{hash}?s={size * 2}&d=retro"; + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/DeletionBlockers.cs b/src/BaGet.Identity.Application/Services/Accounts/DeletionBlockers.cs new file mode 100644 index 000000000..e76082628 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/DeletionBlockers.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// What stops a user from deleting their account. +/// +/// +/// Package IDs the user is the only direct owner of, in any repository (ownership is per repository, so the same +/// ID in two repositories counts once each). Same rule as +/// : an owned ID keeps an owner. +/// +/// +/// Organizations the user is the last administrator of while others still belong to it, or +/// that own packages and so cannot be left without anyone to run them. Same rule as +/// . +/// +/// +/// The same IDs per repository (the same ID sole-owned in two repositories is two entries), with the repository's +/// name so a page can name it and link to that repository's Manage page. +/// +/// +/// The user is the server's only administrator, so deleting them would leave nobody able to +/// change the settings. +/// +public record DeletionBlockers( + IReadOnlyList LastOwnerPackageIds, + IReadOnlyList Organizations, + bool LastAdministrator = false, + IReadOnlyList? LastOwnerPackages = null) +{ + /// Per-repository detail of ; never null. + public IReadOnlyList LastOwnerPackages { get; init; } = LastOwnerPackages ?? Array.Empty(); + + /// Whether anything blocks the deletion. + public bool Any => LastOwnerPackageIds.Count > 0 || Organizations.Count > 0 || LastAdministrator; +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/ExternalClaims.cs b/src/BaGet.Identity.Application/Services/Accounts/ExternalClaims.cs new file mode 100644 index 000000000..580c43bb2 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/ExternalClaims.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; +using System.Security.Claims; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Reads a claim of an external principal by the name a provider uses in its tokens. The authentication handler maps some well-known names to the +/// .NET claim types (email to ), so both spellings are tried. +/// +public static class ExternalClaims +{ + // What the OpenID Connect handler does to incoming claim types (MapInboundClaims): raw name -> .NET type (role and roles -> ClaimTypes.Role, group -> the Group URI, ...). + private static readonly IDictionary Inbound = Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.DefaultInboundClaimTypeMap; + + /// The claims named (exact name first, else the .NET type the handler maps it to through JsonWebTokenHandler.DefaultInboundClaimTypeMap). + public static IReadOnlyList Values(ClaimsPrincipal principal, string? name) + { + var result = new List(); + if (string.IsNullOrWhiteSpace(name)) return result; + + foreach (var type in Types(name.Trim())) + { + foreach (var claim in principal.FindAll(type)) + { + if (!string.IsNullOrEmpty(claim.Value)) result.Add(claim.Value); + } + + if (result.Count > 0) break; + } + + return result; + } + + /// The first value of the claim, or null. + public static string? First(ClaimsPrincipal principal, string? name) + { + var values = Values(principal, name); + + return values.Count > 0 ? values[0] : null; + } + + // The name as written, then the type the handler maps it to, then every other raw name that maps to the same type as a claim written as such. + private static IEnumerable Types(string name) + { + yield return name; + if (Inbound.TryGetValue(name, out var mapped)) yield return mapped; + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/ExternalLogins.cs b/src/BaGet.Identity.Application/Services/Accounts/ExternalLogins.cs new file mode 100644 index 000000000..773b5c400 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/ExternalLogins.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Models.Account; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// What screens need to know about the configured external providers and a user's linked logins. +public sealed class ExternalLogins +{ + private readonly UserManager _users; + private readonly OpenIdConnectProviderSet _providers; + + /// Creates the service. + public ExternalLogins(UserManager users, OpenIdConnectProviderSet providers) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _providers = providers ?? throw new ArgumentNullException(nameof(providers)); + } + + /// The service for the providers configures (what the constructors that predate several providers build their own from). + public static ExternalLogins For(UserManager users, Microsoft.Extensions.Options.IOptions accounts) + => new(users, OpenIdConnectProviders.Resolve((accounts ?? throw new ArgumentNullException(nameof(accounts))).Value)); + + /// Every configured provider. + public IReadOnlyList Configured + => _providers.All.Select(p => new ExternalProviderInfo(p.Id, p.DisplayName)).ToList(); + + /// The configured providers has a linked login at. + public async Task> LinkedAsync(BaGetUser? user) + { + if (user == null || !_providers.Any) return Array.Empty(); + + var logins = await _users.GetLoginsAsync(user); + + return _providers.All + .Where(p => logins.Any(l => string.Equals(l.LoginProvider, p.Id, StringComparison.Ordinal))) + .Select(p => new ExternalProviderInfo(p.Id, p.DisplayName)) + .ToList(); + } + + /// Every configured provider with whether has linked a login at it. + public async Task> StatusAsync(BaGetUser? user) + { + var linked = (await LinkedAsync(user)).Select(p => p.Id).ToHashSet(StringComparer.Ordinal); + + return Configured.Select(p => new ExternalLoginStatus(p.Id, p.DisplayName, linked.Contains(p.Id))).ToList(); + } + + /// Whether can prove presence again with a provider: one of the configured providers is linked to the account. + public async Task CanReauthenticateAsync(BaGetUser? user) => (await LinkedAsync(user)).Count > 0; +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/ExternalProviderMapping.cs b/src/BaGet.Identity.Application/Services/Accounts/ExternalProviderMapping.cs new file mode 100644 index 000000000..3aa1b96b5 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/ExternalProviderMapping.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// Applies a provider's role and group mapping when a user signs in through it. Only a provider with an administrator claim (and value) or a +/// group claim with mappings has an effect, and only on the users signing in through it. Everything goes through the existing services +/// (, ) so the rules (never the last administrator) and the access-model cache +/// are the same as for an administrator doing it by hand, and every change is audited with the provider as actor. +/// +public sealed class ExternalProviderMapping +{ + private readonly AdministratorService _administrators; + private readonly IAccessAdministration? _access; + private readonly IAdminAudit _audit; + private readonly MaintenanceGate? _gate; + private readonly ILogger _logger; + + /// Creates the service. + public ExternalProviderMapping( + AdministratorService administrators, + IAdminAudit audit, + ILogger logger, + IAccessAdministration? access = null, + MaintenanceGate? gate = null) + { + _administrators = administrators ?? throw new ArgumentNullException(nameof(administrators)); + _audit = audit ?? throw new ArgumentNullException(nameof(audit)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _access = access; + _gate = gate; + } + + /// The name recorded as the actor of a change made by . + public static string ActorOf(OpenIdConnectProvider provider) => "provider:" + provider.Id; + + /// + /// Brings in line with the claims the provider sent. Does nothing for a provider with no mapping, and while the + /// read-only gate is closed (a sign-in must still work; the mapping applies at the next one). + /// + public async Task ApplyAsync(OpenIdConnectProvider provider, BaGetUser user, ClaimsPrincipal principal, CancellationToken cancellationToken) + { + var options = provider.Options; + var hasAdministrator = !string.IsNullOrWhiteSpace(options.AdministratorClaim) && !string.IsNullOrWhiteSpace(options.AdministratorValue); + var hasGroups = !string.IsNullOrWhiteSpace(options.GroupClaim) && options.GroupMappings is { Count: > 0 }; + if (!hasAdministrator && !hasGroups) return; + + if (_gate is { IsClosed: true }) + { + _logger.LogWarning("The server is read-only: the mapping of provider {Provider} was not applied to {User}", provider.Id, user.UserName); + + return; + } + + var actor = ActorOf(provider); + if (hasAdministrator) await ApplyAdministratorAsync(provider, user, principal, actor, cancellationToken); + if (hasGroups) await ApplyGroupsAsync(provider, user, principal, actor, cancellationToken); + } + + private async Task ApplyAdministratorAsync(OpenIdConnectProvider provider, BaGetUser user, ClaimsPrincipal principal, string actor, CancellationToken cancellationToken) + { + var options = provider.Options; + var present = ExternalClaims.Values(principal, options.AdministratorClaim).Contains(options.AdministratorValue!.Trim(), StringComparer.Ordinal); + + if (present == user.IsAdministrator) return; + + var change = present + ? await _administrators.PromoteAsync(user.UserName, actor, cancellationToken) + : await _administrators.DemoteAsync(user.UserName, actor, cancellationToken); + + switch (change) + { + case AdministratorChange.Changed: + _audit.Record(actor, present ? "account.promote" : "account.demote", $"user {user.UserName}", $"administrator claim '{options.AdministratorClaim}' at provider {provider.Id}"); + break; + case AdministratorChange.LastAdministrator: + _logger.LogWarning("Provider {Provider} no longer vouches for administrator {User}, who is the last one: kept", provider.Id, user.UserName); + break; + } + } + + private async Task ApplyGroupsAsync(OpenIdConnectProvider provider, BaGetUser user, ClaimsPrincipal principal, string actor, CancellationToken cancellationToken) + { + if (_access == null) return; + + var options = provider.Options; + var values = ExternalClaims.Values(principal, options.GroupClaim).ToHashSet(StringComparer.Ordinal); + + // A group is wanted when any of the values mapped to it is present. + var wanted = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var mapping in options.GroupMappings) + { + var group = mapping.Value.Trim(); + wanted[group] = wanted.TryGetValue(group, out var already) && already || values.Contains(mapping.Key); + } + + IReadOnlyList current; + try + { + current = await _access.GroupsOfUserAsync(user.Id, cancellationToken); + } + catch (InvalidOperationException e) + { + _logger.LogWarning(e, "The groups of {User} could not be read: provider {Provider}'s group mapping was skipped", user.UserName, provider.Id); + + return; + } + + var member = current.ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var (group, want) in wanted) + { + if (want == member.Contains(group)) continue; + + try + { + if (await _access.GetGroupAsync(group, cancellationToken) == null) + { + _logger.LogWarning("Provider {Provider} maps to the group {Group}, which does not exist: skipped", provider.Id, group); + continue; + } + + if (want) await _access.AddGroupMemberAsync(group, user.Id, actor, cancellationToken); + else await _access.RemoveGroupMemberAsync(group, user.Id, actor, cancellationToken); + } + catch (AccessModelException e) + { + _logger.LogWarning(e, "Provider {Provider}'s mapping to the group {Group} could not be applied to {User}", provider.Id, group, user.UserName); + } + } + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/NewUserPasswordMode.cs b/src/BaGet.Identity.Application/Services/Accounts/NewUserPasswordMode.cs new file mode 100644 index 000000000..a74f13f02 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/NewUserPasswordMode.cs @@ -0,0 +1,17 @@ +namespace BaGet.Identity.Application.Services.Accounts; + +/// How an administrator-created account gets its first password. +public enum NewUserPasswordMode +{ + /// The administrator typed one. + Given, + + /// The server generates one, shown to the administrator once. + Generated, + + /// + /// The account gets an unknown random password and is mailed a reset link to choose its own. Needs an + /// email address and a configured SMTP server; the caller checks that and queues the mail. + /// + Invited, +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/NewUserResult.cs b/src/BaGet.Identity.Application/Services/Accounts/NewUserResult.cs new file mode 100644 index 000000000..3d04d6d0d --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/NewUserResult.cs @@ -0,0 +1,13 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// The outcome of . +/// The new user, or null if none was created. +/// Why nothing was created, or null. +/// The password for , to show once. +public record NewUserResult(BaGetUser? User, string? Error, string? GeneratedPassword = null) +{ + /// Whether the account was created. + public bool Succeeded => User != null; +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/NpmTokenService.cs b/src/BaGet.Identity.Application/Services/Accounts/NpmTokenService.cs new file mode 100644 index 000000000..b536fa859 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/NpmTokenService.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// over the accounts: npm login trades the user name and password for an API key of +/// that user limited to the repository (and, for a virtual one, its members and deploy repository; ), +/// which npm then sends as Authorization: Bearer. The password check is the sign-in page's: the same lockout counter, the +/// same confirmed-email rule. An account with two-factor authentication cannot sign in with a password alone, so it is refused +/// here and creates a key on its API keys page. The key has no expiry and is revoked from that page or by npm logout. +/// +public class NpmTokenService : INpmTokenService +{ + private readonly UserManager _users; + private readonly SignInManager _signIn; + private readonly ApiKeyService _apiKeys; + private readonly ILogger _logger; + private readonly IVirtualRepositories? _virtual; + + /// The user store. + /// Checks passwords the way the sign-in page does. + /// Creates and revokes keys. + /// The logger. + /// Resolves the members and the deploy repository of a virtual repository. + public NpmTokenService( + UserManager users, + SignInManager signIn, + ApiKeyService apiKeys, + ILogger logger, + IVirtualRepositories? virtualRepositories = null) + { + _virtual = virtualRepositories; + _users = users ?? throw new ArgumentNullException(nameof(users)); + _signIn = signIn ?? throw new ArgumentNullException(nameof(signIn)); + _apiKeys = apiKeys ?? throw new ArgumentNullException(nameof(apiKeys)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private const string Bad = "Bad username or password."; + + /// + public async Task LoginAsync(string? userName, string? password, RepositoryInfo repository, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) return new NpmLoginResult(null, Bad); + + var user = await _users.FindByNameAsync(userName); + if (user == null) return new NpmLoginResult(null, Bad); + + var result = await _signIn.CheckPasswordSignInAsync(user, password, lockoutOnFailure: true); + if (result.IsLockedOut) return new NpmLoginResult(null, "The account is locked out: try again later.", LockedOut: true); + if (result.IsNotAllowed) + { + // For an account awaiting approval the sign-in manager answers "not allowed" to the right password only + // (a wrong one is a counted failure), so this explanation reveals nothing to a guesser. + return new NpmLoginResult(null, user.PendingApproval + ? "The account is waiting for an administrator to enable it." + : "The account may not sign in yet: confirm its email address first."); + } + if (!result.Succeeded) return new NpmLoginResult(null, Bad); + + if (await _users.GetTwoFactorEnabledAsync(user)) + { + return new NpmLoginResult(null, "This account uses two-factor authentication: create an API key on the account's API keys page and use it as the _authToken."); + } + + // A virtual repository holds no packages of its own: reading through it asks the caller's rights on each member, and + // a push goes to its deploy repository, so a token limited to the virtual repository alone could neither read a + // private member nor push. The token covers the virtual repository and the repositories it answers with. + var keys = new List { repository.Key }; + if (repository.Kind == RepositoryKind.Virtual && _virtual != null) + { + keys.AddRange((await _virtual.EffectiveMembersAsync(repository, cancellationToken)).Select(m => m.Key)); + var deploy = await _virtual.DeployTargetAsync(repository, cancellationToken); + if (deploy != null) keys.Add(deploy.Key); + } + + var token = await _apiKeys.CreateAsync( + user.Id, + $"npm login ({repository.Name})", + ApiKeyScopes.All, + "*", + expires: null, + repositoryKeys: keys.Distinct().ToList(), + cancellationToken); + + _logger.LogInformation("{UserName} logged in to the npm registry of {Repository}.", user.UserName, repository.Name); + + return new NpmLoginResult(token); + } + + /// + public async Task RevokeAsync(BaGetPrincipal caller, string token, CancellationToken cancellationToken) + { + if (caller == null) throw new ArgumentNullException(nameof(caller)); + + var key = await _apiKeys.FindValidOrNullAsync(token, cancellationToken); + if (key == null || caller.UserId == null || key.UserId != caller.UserId) return false; + + return await _apiKeys.RevokeAsync(caller.UserId, key.Key, cancellationToken); + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/OpenIdConnectProviderSetup.cs b/src/BaGet.Identity.Application/Services/Accounts/OpenIdConnectProviderSetup.cs new file mode 100644 index 000000000..6c090157c --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/OpenIdConnectProviderSetup.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Identity; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// Fills the authentication handler's options for one (what AddBaGetAccounts registers per provider). +public static class OpenIdConnectProviderSetup +{ + /// Request parameters a provider's Parameters can never set or replace: BaGet's own protocol values. + internal static readonly HashSet ReservedParameters = new(StringComparer.OrdinalIgnoreCase) + { + "client_id", "client_secret", "response_type", "response_mode", "scope", "redirect_uri", "state", "nonce", + "code_challenge", "code_challenge_method", "prompt", "max_age", "id_token_hint", + }; + + /// Configures for . + public static void Configure(OpenIdConnectOptions options, OpenIdConnectProvider provider) + { + var source = provider.Options; + options.SignInScheme = IdentityConstants.ExternalScheme; + options.Authority = source.Authority; + options.ClientId = source.ClientId; + options.ClientSecret = source.ClientSecret; + options.ResponseType = "code"; + options.Scope.Add("profile"); + options.Scope.Add("email"); + options.CallbackPath = provider.CallbackPath; + options.SignedOutCallbackPath = provider.SignedOutCallbackPath; + options.RemoteSignOutPath = provider.RemoteSignOutPath; + + foreach (var scope in OpenIdConnectProviders.ExtraScopes(source)) options.Scope.Add(scope); + + // Default claim mapping and ClaimActions keep the id_token's auth_time as it is sent; the re-authentication check relies on it. + var parameters = source.Parameters; + if (parameters is { Count: > 0 }) + { + var previous = options.Events.OnRedirectToIdentityProvider; + options.Events.OnRedirectToIdentityProvider = async context => + { + if (previous != null) await previous(context); + ApplyExtraParameters(context.ProtocolMessage, parameters); + }; + } + } + + /// + /// Adds the extra parameters to an authorization request unless BaGet or the challenge already set that parameter (a re-authentication's + /// prompt and max_age) or it is one of . + /// + public static void ApplyExtraParameters(OpenIdConnectMessage message, IReadOnlyDictionary parameters) + { + foreach (var pair in parameters) + { + if (string.IsNullOrWhiteSpace(pair.Key) || ReservedParameters.Contains(pair.Key)) continue; + if (message.Parameters.ContainsKey(pair.Key)) continue; + + message.SetParameter(pair.Key, pair.Value); + } + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/SignInProviderSettings.cs b/src/BaGet.Identity.Application/Services/Accounts/SignInProviderSettings.cs new file mode 100644 index 000000000..f013efdb8 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/SignInProviderSettings.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Models.Settings; +using Microsoft.Extensions.Configuration; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// +/// The named OpenID Connect providers the Settings screen edits: lists them (what is saved, against what the running server registered), and adds, +/// changes or removes one by writing Accounts:OpenIdConnectProviders:<id>:* to the overrides file through . +/// Handlers are registered at startup, so every change needs a restart. Only providers the overrides file holds can be changed here. +/// +public sealed class SignInProviderSettings +{ + private static readonly JsonSerializerOptions Fingerprint = new() { WriteIndented = false }; + + private readonly SettingsService _settings; + private readonly IConfiguration _configuration; + private readonly OpenIdConnectProviderSet _active; + + /// Creates the service. + public SignInProviderSettings(SettingsService settings, IConfiguration configuration, OpenIdConnectProviderSet active) + { + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + _active = active ?? throw new ArgumentNullException(nameof(active)); + } + + /// The named providers: those configured now (saved or from the configuration) and those the running server still has. + public IReadOnlyList List() + { + var configured = ReadConfigured(); + var saved = _settings.GetSavedChildNames(OpenIdConnectProviders.SectionKey); + var ids = configured.Keys.Concat(_active.All.Where(p => !p.IsLegacy).Select(p => p.Id)).Distinct(StringComparer.Ordinal).OrderBy(i => i, StringComparer.Ordinal); + + var result = new List(); + foreach (var id in ids) + { + var active = _active.Find(id) is { IsLegacy: false } found ? found : null; + var options = configured.TryGetValue(id, out var current) ? current : active!.Options; + var view = ViewOf(id, options); + view.Editable = saved.Contains(id); + view.Active = active != null; + view.PendingRestart = Differs(configured.TryGetValue(id, out var now) ? now : null, active?.Options); + result.Add(view); + } + + return result; + } + + /// The ids that differ from what the running server registered (added, changed or removed since startup). + public IReadOnlyList PendingRestartKeys() => List().Where(p => p.PendingRestart).Select(p => OpenIdConnectProviders.SectionKey + ":" + p.Id).ToList(); + + /// Adds or changes the provider named by the form after validating it. The result says why nothing was saved. + public async Task SaveAsync(SignInProviderForm form, string? actor, CancellationToken cancellationToken) + { + var id = form.Id?.Trim() ?? string.Empty; + var problem = OpenIdConnectProviders.ValidateId(id); + if (problem != null) return SettingsSaveResult.Failed(new[] { problem }); + + var configured = ReadConfigured(); + var saved = _settings.GetSavedChildNames(OpenIdConnectProviders.SectionKey); + var exists = configured.ContainsKey(id); + if (exists && !saved.Contains(id)) + { + return SettingsSaveResult.Failed(new[] { $"The provider '{id}' is set by a configuration file or the environment, so it cannot be changed here." }); + } + + if (!exists && id == OpenIdConnectProviders.LegacyId && _active.All.Any(p => p.IsLegacy)) + { + return SettingsSaveResult.Failed(new[] { $"The id '{id}' belongs to the single 'Accounts:OpenIdConnect' block, which is configured. Choose another id." }); + } + + var parameters = ParseLines(form.Parameters, "parameter", StringComparer.OrdinalIgnoreCase, out var parameterErrors); + var mappings = ParseLines(form.GroupMappings, "group mapping", StringComparer.OrdinalIgnoreCase, out var mappingErrors); + var errors = parameterErrors.Concat(mappingErrors).ToList(); + + var candidate = new OpenIdConnectProviderOptions + { + Authority = Clean(form.Authority), + ClientId = Clean(form.ClientId), + AdministratorClaim = Clean(form.AdministratorClaim), + AdministratorValue = Clean(form.AdministratorValue), + GroupClaim = Clean(form.GroupClaim), + Parameters = new Dictionary(parameters, StringComparer.OrdinalIgnoreCase), + GroupMappings = new Dictionary(mappings, StringComparer.Ordinal), + }; + errors.AddRange(OpenIdConnectProviders.Validate(candidate)); + if (errors.Count > 0) return SettingsSaveResult.Failed(errors.Distinct()); + + var prefix = OpenIdConnectProviders.SectionKey + ":" + id; + var changes = new Dictionary(); + void Set(string field, string? value, bool sensitive = false) => changes[Describe(prefix + ":" + field, sensitive)] = value!; + + Set("DisplayName", Clean(form.DisplayName)); + Set("Authority", candidate.Authority); + Set("ClientId", candidate.ClientId); + if (!string.IsNullOrEmpty(form.ClientSecret)) Set("ClientSecret", form.ClientSecret, sensitive: true); + Set("Scopes", Clean(form.Scopes)); + Set("UserNameClaim", Clean(form.UserNameClaim)); + Set("EmailClaim", Clean(form.EmailClaim)); + Set("EmailVerifiedClaim", Clean(form.EmailVerifiedClaim)); + Set("AdministratorClaim", candidate.AdministratorClaim); + Set("AdministratorValue", candidate.AdministratorValue); + Set("GroupClaim", candidate.GroupClaim); + changes[Describe(prefix + ":Parameters")] = null!; + foreach (var pair in parameters) Set("Parameters:" + pair.Key, pair.Value); + changes[Describe(prefix + ":GroupMappings")] = null!; + foreach (var pair in mappings) Set("GroupMappings:" + pair.Key, pair.Value); + + return await _settings.SaveAsync(changes, actor, cancellationToken); + } + + /// Removes a provider the overrides file holds. + public async Task RemoveAsync(string? id, string? actor, CancellationToken cancellationToken) + { + id = id?.Trim() ?? string.Empty; + if (!_settings.GetSavedChildNames(OpenIdConnectProviders.SectionKey).Contains(id)) + { + return SettingsSaveResult.Failed(new[] + { + ReadConfigured().ContainsKey(id) + ? $"The provider '{id}' is set by a configuration file or the environment, so it cannot be removed here." + : $"There is no saved provider '{id}'.", + }); + } + + var changes = new Dictionary { [Describe(OpenIdConnectProviders.SectionKey + ":" + id)] = null! }; + + return await _settings.SaveAsync(changes, actor, cancellationToken); + } + + private Dictionary ReadConfigured() + { + var result = new Dictionary(StringComparer.Ordinal); + foreach (var child in _configuration.GetSection(OpenIdConnectProviders.SectionKey).GetChildren()) + { + var options = child.Get() ?? new OpenIdConnectProviderOptions(); + result[child.Key.ToLowerInvariant()] = options; + } + + return result; + } + + private static SettingDescriptor Describe(string key, bool sensitive = false) + => new(key, "Accounts", "Accounts", SettingKind.String, typeof(string), Array.Empty(), sensitive, true, "A sign-in provider."); + + private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static SignInProviderView ViewOf(string id, OpenIdConnectProviderOptions options) => new() + { + Id = id, + DisplayName = options.DisplayName, + Authority = options.Authority, + ClientId = options.ClientId, + HasSecret = !string.IsNullOrEmpty(options.ClientSecret), + Scopes = options.Scopes, + Parameters = string.Join("\n", options.Parameters.Select(p => p.Key + "=" + p.Value)), + UserNameClaim = options.UserNameClaim, + EmailClaim = options.EmailClaim, + EmailVerifiedClaim = options.EmailVerifiedClaim, + AdministratorClaim = options.AdministratorClaim, + AdministratorValue = options.AdministratorValue, + GroupClaim = options.GroupClaim, + GroupMappings = string.Join("\n", options.GroupMappings.Select(p => p.Key + "=" + p.Value)), + }; + + // Whether what is configured now is not what the running server registered; the secret takes part (a changed secret needs a restart) without being shown. + private static bool Differs(OpenIdConnectProviderOptions? now, OpenIdConnectProviderOptions? running) + { + if (now is { IsConfigured: false }) now = null; + if (now == null && running == null) return false; + if (now == null || running == null) return true; + + return JsonSerializer.Serialize(Normalize(now), Fingerprint) != JsonSerializer.Serialize(Normalize(running), Fingerprint); + } + + private static object Normalize(OpenIdConnectProviderOptions o) => new + { + o.Authority, o.ClientId, o.ClientSecret, DisplayName = o.DisplayName ?? string.Empty, o.Scopes, o.UserNameClaim, o.EmailClaim, o.EmailVerifiedClaim, + o.AdministratorClaim, o.AdministratorValue, o.GroupClaim, + Parameters = o.Parameters.OrderBy(p => p.Key, StringComparer.OrdinalIgnoreCase).Select(p => p.Key.ToLowerInvariant() + "=" + p.Value).ToArray(), + GroupMappings = o.GroupMappings.OrderBy(p => p.Key, StringComparer.Ordinal).Select(p => p.Key + "=" + p.Value).ToArray(), + }; + + private static Dictionary ParseLines(string? text, string what, StringComparer comparer, out List errors) + { + errors = new List(); + var result = new Dictionary(comparer); + foreach (var raw in (text ?? string.Empty).Split('\n')) + { + var line = raw.Trim(); + if (line.Length == 0) continue; + + var at = line.IndexOf('='); + if (at <= 0 || at == line.Length - 1) + { + errors.Add($"A {what} line is name=value (got '{line}')."); + continue; + } + + var name = line[..at].Trim(); + if (!result.TryAdd(name, line[(at + 1)..].Trim())) errors.Add($"The {what} '{name}' is given twice (names that differ only by case are the same)."); + } + + return result; + } +} diff --git a/src/BaGet.Identity.Application/Services/Accounts/SoleOwnedPackage.cs b/src/BaGet.Identity.Application/Services/Accounts/SoleOwnedPackage.cs new file mode 100644 index 000000000..ae32a9aaf --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Accounts/SoleOwnedPackage.cs @@ -0,0 +1,14 @@ +using BaGet.Core; + +namespace BaGet.Identity.Application.Services.Accounts; + +/// A package ID in one repository that only one user owns. +/// The repository's key. +/// The repository's name ( for the default). +/// The package ID. +/// The repository's format (an npm package is unpublished, a NuGet package deleted). +public record SoleOwnedPackage(int RepositoryKey, string RepositoryName, string? PackageId, RepositoryFormat Format = RepositoryFormat.NuGet) +{ + /// The ID for the default repository, ID (name) for any other, for messages that mix repositories. + public string Label => RepositoryKey == Repository.DefaultKey ? PackageId ?? string.Empty : $"{PackageId} ({RepositoryName})"; +} diff --git a/src/BaGet.Identity.Application/Services/Organizations/OrganizationChange.cs b/src/BaGet.Identity.Application/Services/Organizations/OrganizationChange.cs new file mode 100644 index 000000000..ca1fb1cd6 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Organizations/OrganizationChange.cs @@ -0,0 +1,23 @@ +namespace BaGet.Identity.Application.Services.Organizations; + +/// The outcome of an administrator's change to an organization. +public enum OrganizationChange +{ + /// Done. + Success, + + /// No organization (or no such member) with that name. + NotFound, + + /// The new name is empty, too long or has characters that cannot be in a URL path segment. + InvalidName, + + /// The new name is another user's or organization's: they share one namespace. + NameTaken, + + /// The organization owns package IDs (in some repository), so it cannot be deleted. + OwnsPackages, + + /// An organization must keep at least one administrator. + LastAdministrator, +} diff --git a/src/BaGet.Identity.Application/Services/Organizations/OrganizationMembership.cs b/src/BaGet.Identity.Application/Services/Organizations/OrganizationMembership.cs new file mode 100644 index 000000000..96004d44a --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Organizations/OrganizationMembership.cs @@ -0,0 +1,4 @@ +namespace BaGet.Identity.Application.Services.Organizations; + +/// An organization a user belongs to, as the account deletion sees it: whether the user is its last administrator and how many other members it has. +internal sealed record OrganizationMembership(int Key, string? Name, bool IsLastAdmin, int OtherMembers); diff --git a/src/BaGet.Identity.Application/Services/Organizations/OrganizationOutcome.cs b/src/BaGet.Identity.Application/Services/Organizations/OrganizationOutcome.cs new file mode 100644 index 000000000..8125d4bb9 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Organizations/OrganizationOutcome.cs @@ -0,0 +1,6 @@ +namespace BaGet.Identity.Application.Services.Organizations; + +/// What happens to one organization when an administrator deletes a member. +/// The organization. +/// A sentence for the confirmation page. +public record OrganizationOutcome(string? Name, string Outcome); diff --git a/src/BaGet.Identity.Application/Services/Organizations/OrganizationSummary.cs b/src/BaGet.Identity.Application/Services/Organizations/OrganizationSummary.cs new file mode 100644 index 000000000..a2b97c25a --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Organizations/OrganizationSummary.cs @@ -0,0 +1,11 @@ +using System; + +namespace BaGet.Identity.Application.Services.Organizations; + +/// An organization as the administrator's list shows it. +/// The name. +/// When it was created. +/// How many members it has. +/// How many of them administer it. +/// How many package IDs it owns, counted per repository. +public record OrganizationSummary(string? Name, DateTime Created, int Members, int Administrators, int PackageIds); diff --git a/src/BaGet.Identity.Application/Services/Ownership/OwnerChangeResult.cs b/src/BaGet.Identity.Application/Services/Ownership/OwnerChangeResult.cs new file mode 100644 index 000000000..451b03925 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Ownership/OwnerChangeResult.cs @@ -0,0 +1,20 @@ +namespace BaGet.Identity.Application.Services.Ownership; + +public enum OwnerChangeResult +{ + Success, + + /// + /// No user or organization has that name. + /// + UnknownAccount, + + AlreadyOwner, + + NotOwner, + + /// + /// A package ID with owners must keep at least one. + /// + LastOwner, +} diff --git a/src/BaGet.Identity.Application/Services/Ownership/OwnershipAuthorizationService.cs b/src/BaGet.Identity.Application/Services/Ownership/OwnershipAuthorizationService.cs new file mode 100644 index 000000000..fd2eaf7ee --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Ownership/OwnershipAuthorizationService.cs @@ -0,0 +1,159 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace BaGet.Identity.Application.Services.Ownership; + +/// +/// The rules for changing packages, in two layers. First the access model (): the caller must hold the matching action (Deploy to push, Delete to unlist or delete, Annotate to edit deprecation and +/// vulnerabilities) on the package in the current repository. Then package ownership, as nuget.org applies it: +/// +/// The superuser may do anything. +/// A key acts only within its scopes and its package glob. +/// An administrator skips ownership, never the key's own limits (scopes and glob): a +/// push-only key an administrator made for CI stays push-only. It may push a version of, +/// or unlist, any existing ID, ownerless ones included; a new ID still needs +/// . +/// Pushing a new package ID needs , and makes the +/// pusher its owner. +/// Anything else needs the user to own the ID, directly or through an +/// organization. +/// An ID that already exists but has no owners predates accounts, and only the +/// superuser may change it, so nothing becomes inaccessible on upgrade. +/// +/// +public class OwnershipAuthorizationService : IPackageAuthorizationService +{ + private readonly PackageOwnershipService _ownership; + private readonly IPackageDatabase _packages; + private readonly IContext? _context; + private readonly ILogger _logger; + private readonly IAccessEvaluator _access; + private readonly IRepositoryContext _repository; + + public OwnershipAuthorizationService( + PackageOwnershipService ownership, + IPackageDatabase packages, + ILogger logger, + IAccessEvaluator access, + IRepositoryContext repository, + IContext? context = null) + { + _context = context; + _access = access ?? throw new ArgumentNullException(nameof(access)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task AuthorizeAsync( + BaGetPrincipal? principal, + PackageAction action, + string? packageId, + CancellationToken cancellationToken) + { + if (principal == null) return false; + if (principal.IsSuperuser) return true; + if (!principal.MatchesPackage(packageId)) return false; + + // The access model first: a permission is necessary, ownership (below) remains necessary too. Administrators + // hold every action (the evaluator says so), the superuser returned above. + if (!await _access.IsAllowedAsync(principal, _repository.Current, packageId, Required(action), cancellationToken)) return false; + + // An administrator skips ownership, never the key's own limits: a push-only key an + // administrator made for CI stays push-only. + if (principal.IsAdministrator) + { + switch (action) + { + case PackageAction.Push: + var exists = await ExistsAsync(packageId, cancellationToken) + || await _ownership.HasOwnersAsync(packageId, cancellationToken); + + return exists + ? principal.HasScope(ApiKeyScopes.Push) || principal.HasScope(ApiKeyScopes.PushVersion) + : principal.HasScope(ApiKeyScopes.Push); + + case PackageAction.Manage: + case PackageAction.Annotate: + return principal.HasScope(ApiKeyScopes.Unlist); + + default: + return false; + } + } + + var isOwner = await _ownership.IsOwnerAsync(principal.UserId, principal.UserName, packageId, cancellationToken); + + switch (action) + { + case PackageAction.Push: + if (isOwner) + { + return principal.HasScope(ApiKeyScopes.Push) || principal.HasScope(ApiKeyScopes.PushVersion); + } + + // A new ID may be claimed; an existing one without owners may not. + return principal.HasScope(ApiKeyScopes.Push) + && !await _ownership.HasOwnersAsync(packageId, cancellationToken) + && !await ExistsAsync(packageId, cancellationToken); + + case PackageAction.Manage: + case PackageAction.Annotate: + return isOwner && principal.HasScope(ApiKeyScopes.Unlist); + + default: + return false; + } + } + + // Whether the ID names a package of the current repository, whatever its format: a NuGet package id, an npm package name, or a Maven group:artifact. + private async Task ExistsAsync(string? packageId, CancellationToken cancellationToken) + { + if (_repository.Current.Format == RepositoryFormat.Npm && _context != null) + { + var name = packageId?.ToLowerInvariant(); + + return await _context.NpmPackages!.AnyAsync(p => p.Name == name, cancellationToken); + } + + if (_repository.Current.Format == RepositoryFormat.Maven && _context != null) + { + // A Maven artifact is "group:artifact"; both parts are case-sensitive. + if (!MavenNames.TryParseArtifactName(packageId, out var groupId, out var artifactId)) return false; + + return await _context.MavenArtifacts!.AnyAsync(a => a.GroupId == groupId && a.ArtifactId == artifactId, cancellationToken); + } + + return await _packages.ExistsAsync(packageId, cancellationToken); + } + + private static AccessAction Required(PackageAction action) => action switch + { + PackageAction.Push => AccessAction.Deploy, + PackageAction.Annotate => AccessAction.Annotate, + _ => AccessAction.Delete, + }; + + public async Task OnPushedAsync(BaGetPrincipal? principal, string? packageId, bool isNewId, CancellationToken cancellationToken) + { + // Only a new ID is claimed: an administrator may push to an existing ownerless one, + // and that must leave it ownerless. + if (!isNewId || principal == null || principal.IsSuperuser || packageId == null) return; + if (await _ownership.HasOwnersAsync(packageId, cancellationToken)) return; + + // Two users pushing the same new ID at once may both become owners. That is + // safe, if surprising: each could only have done so with the push scope. + var result = await _ownership.AddOwnerAsync(packageId, principal.UserName, cancellationToken); + + _logger.LogInformation( + "{UserName} pushed new package {PackageId} and became its owner: {Result}", + principal.UserName, + packageId, + result); + } +} \ No newline at end of file diff --git a/src/BaGet.Identity.Application/Services/Ownership/PackageOwnershipService.cs b/src/BaGet.Identity.Application/Services/Ownership/PackageOwnershipService.cs new file mode 100644 index 000000000..65687be55 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Ownership/PackageOwnershipService.cs @@ -0,0 +1,431 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using BaGet.Identity.Application.Services.Organizations; + +namespace BaGet.Identity.Application.Services.Ownership; + +/// +/// Package owners, and the organizations users own packages through. +/// +public class PackageOwnershipService +{ + private readonly IContext _context; + private readonly SystemTime _time; + + public PackageOwnershipService(IContext context, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + public async Task> GetOwnersAsync(string? packageId, CancellationToken cancellationToken) + { + var id = packageId?.ToLowerInvariant(); + + #pragma warning disable CS8602, CS8604 + return await _context.PackageOwners + .AsNoTracking() + .Where(o => o.PackageId.ToLower() == id) + .OrderBy(o => o.OwnerName) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + } + + /// + /// The account names a user acts as: their own and every organization they belong to. + /// + public async Task?> GetAccountNamesAsync(string? userId, string? userName, CancellationToken cancellationToken) + { + #pragma warning disable CS8602, CS8604 + var organizations = await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.UserId == userId && m.Organization != null) + .Select(m => m.Organization.Name) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + #pragma warning disable CS8619 + return new[] { userName }.Concat(organizations).ToList(); + #pragma warning restore CS8619 + } + + public async Task IsOwnerAsync(string? userId, string? userName, string? packageId, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var names = (await GetAccountNamesAsync(userId, userName, cancellationToken)) + .Select(n => n.ToLowerInvariant()) + .ToList(); + #pragma warning restore CS8604 + var id = packageId?.ToLowerInvariant(); + + #pragma warning disable CS8602, CS8604 + return await _context.PackageOwners + .AnyAsync(o => o.PackageId.ToLower() == id && names.Contains(o.OwnerName.ToLower()), cancellationToken); + #pragma warning restore CS8602, CS8604 + } + + /// + /// The package IDs the user owns, directly or through an organization. + /// + public async Task?> GetOwnedPackageIdsAsync(string? userId, string? userName, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var names = (await GetAccountNamesAsync(userId, userName, cancellationToken)) + .Select(n => n.ToLowerInvariant()) + .ToList(); + #pragma warning restore CS8604 + + #pragma warning disable CS8602, CS8604 + var ids = await _context.PackageOwners + .AsNoTracking() + .Where(o => names.Contains(o.OwnerName.ToLower())) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + #pragma warning disable CS8619 + return ids.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(i => i, StringComparer.OrdinalIgnoreCase).ToList(); + #pragma warning restore CS8619 + } + + public async Task HasOwnersAsync(string? packageId, CancellationToken cancellationToken) + { + var id = packageId?.ToLowerInvariant(); + + #pragma warning disable CS8602 + return await _context.PackageOwners?.AnyAsync(o => o.PackageId.ToLower() == id, cancellationToken); + #pragma warning restore CS8602 + } + + public async Task AccountExistsAsync(string? name, CancellationToken cancellationToken) + { + var normalized = name?.ToUpperInvariant(); + var lower = name?.ToLowerInvariant(); + + #pragma warning disable CS8602 + return await _context.Users.AnyAsync(u => u.NormalizedUserName == normalized, cancellationToken) + || await _context.Organizations?.AnyAsync(o => o.Name.ToLower() == lower, cancellationToken); + #pragma warning restore CS8602 + } + + public async Task AddOwnerAsync(string? packageId, string? ownerName, CancellationToken cancellationToken) + { + if (!await AccountExistsAsync(ownerName, cancellationToken)) return OwnerChangeResult.UnknownAccount; + + var owners = await GetOwnersAsync(packageId, cancellationToken); + if (owners.Any(o => string.Equals(o.OwnerName, ownerName, StringComparison.OrdinalIgnoreCase))) + { + return OwnerChangeResult.AlreadyOwner; + } + + _context.PackageOwners?.Add(new PackageOwner { PackageId = packageId, OwnerName = ownerName }); + await _context.SaveChangesAsync(cancellationToken); + + return OwnerChangeResult.Success; + } + + public async Task RemoveOwnerAsync(string? packageId, string ownerName, CancellationToken cancellationToken) + { + var id = packageId?.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var owners = await _context.PackageOwners + .Where(o => o.PackageId.ToLower() == id) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + var owner = owners.FirstOrDefault(o => string.Equals(o.OwnerName, ownerName, StringComparison.OrdinalIgnoreCase)); + if (owner == null) return OwnerChangeResult.NotOwner; + if (owners.Count == 1) return OwnerChangeResult.LastOwner; + + _context.PackageOwners.Remove(owner); + await _context.SaveChangesAsync(cancellationToken); + + return OwnerChangeResult.Success; + } + + /// + /// Mark or unmark the ID as reserved for its owners. Only the superuser may do this. + /// + public async Task SetVerifiedAsync(string packageId, bool verified, CancellationToken cancellationToken) + { + var id = packageId.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var owners = await _context.PackageOwners + .Where(o => o.PackageId.ToLower() == id) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + if (owners.Count == 0) return false; + + owners.ForEach(o => o.IsVerified = verified); + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + public async Task IsVerifiedAsync(string packageId, CancellationToken cancellationToken) + { + var id = packageId.ToLowerInvariant(); + + #pragma warning disable CS8602 + return await _context.PackageOwners?.AnyAsync(o => o.PackageId.ToLower() == id && o.IsVerified, cancellationToken); + #pragma warning restore CS8602 + } + + public async Task?> GetOrganizationsAsync(string? userId, CancellationToken cancellationToken) + { + #pragma warning disable CS8602, CS8604, CS8619 + return await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.UserId == userId && m.Organization != null) + .Select(m => m.Organization) + .OrderBy(o => o.Name) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604, CS8619 + } + + /// + /// Create an organization with its creator as the first administrator. False if + /// the name is already a user or an organization. + /// + public async Task CreateOrganizationAsync(string name, string? creatorUserId, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(name) || await AccountExistsAsync(name, cancellationToken)) return false; + + var organization = new Organization { Name = name.Trim(), Created = _time.UtcNow }; + _context.Organizations?.Add(organization); + _context.OrganizationMembers?.Add(new OrganizationMember + { + Organization = organization, + UserId = creatorUserId, + IsAdmin = true, + }); + + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + public async Task> GetMembersAsync(string? organizationName, CancellationToken cancellationToken) + { + var name = organizationName?.ToLowerInvariant(); + + #pragma warning disable CS8602, CS8604 + return await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.Organization != null && m.Organization.Name.ToLower() == name) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + } + + public async Task IsOrganizationAdminAsync(string? organizationName, string? userId, CancellationToken cancellationToken) + { + var members = await GetMembersAsync(organizationName, cancellationToken); + + return members.Any(m => m.UserId == userId && m.IsAdmin); + } + + public async Task AddMemberAsync(string organizationName, string userId, bool isAdmin, CancellationToken cancellationToken) + { + var name = organizationName.ToLowerInvariant(); + #pragma warning disable CS8602 + var organization = await _context.Organizations?.FirstOrDefaultAsync(o => o.Name.ToLower() == name, cancellationToken); + #pragma warning restore CS8602 + if (organization == null) return false; + + var members = await GetMembersAsync(organizationName, cancellationToken); + if (members.Any(m => m.UserId == userId)) return false; + + _context.OrganizationMembers?.Add(new OrganizationMember + { + OrganizationKey = organization.Key, + UserId = userId, + IsAdmin = isAdmin, + }); + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + /// + /// Remove a member. The last administrator cannot be removed. + /// + public async Task RemoveMemberAsync(string organizationName, string userId, CancellationToken cancellationToken) + { + var name = organizationName.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var members = await _context.OrganizationMembers + .Where(m => m.Organization != null && m.Organization.Name.ToLower() == name) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + var member = members.FirstOrDefault(m => m.UserId == userId); + if (member == null) return false; + if (member.IsAdmin && members.Count(m => m.IsAdmin) == 1) return false; + + _context.OrganizationMembers.Remove(member); + await _context.SaveChangesAsync(cancellationToken); + + return true; + } + + /// + /// Every organization with its member and owned-package counts, by name. Ownership is counted in + /// every repository. + /// + public async Task> GetAllOrganizationsAsync(CancellationToken cancellationToken) + { + #pragma warning disable CS8602, CS8604 + var organizations = await _context.Organizations.AsNoTracking().OrderBy(o => o.Name).ToListAsync(cancellationToken); + var members = await _context.OrganizationMembers.AsNoTracking() + .Where(m => m.OrganizationKey != null) + .Select(m => new { m.OrganizationKey, m.IsAdmin }) + .ToListAsync(cancellationToken); + var owned = await _context.PackageOwners.IgnoreQueryFilters().AsNoTracking() + .Select(o => new { o.OwnerName, o.RepositoryKey, o.PackageId }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + var ownedBy = owned + .GroupBy(o => o.OwnerName?.ToLowerInvariant() ?? string.Empty) + .ToDictionary(g => g.Key, g => g.Select(o => (o.RepositoryKey, o.PackageId?.ToLowerInvariant())).Distinct().Count()); + + return organizations + .Select(o => new OrganizationSummary( + o.Name, + o.Created, + members.Count(m => m.OrganizationKey == o.Key), + members.Count(m => m.OrganizationKey == o.Key && m.IsAdmin), + ownedBy.GetValueOrDefault(o.Name?.ToLowerInvariant() ?? string.Empty))) + .ToList(); + } + + /// The organization with that name (any case), or null. + public async Task FindOrganizationAsync(string? name, CancellationToken cancellationToken) + { + var lower = name?.ToLowerInvariant(); + + #pragma warning disable CS8602, CS8604 + return await _context.Organizations.AsNoTracking().FirstOrDefaultAsync(o => o.Name.ToLower() == lower, cancellationToken); + #pragma warning restore CS8602, CS8604 + } + + /// + /// The package IDs the account owns, counted per repository (every repository, not the request's). + /// + public async Task CountOwnedPackageIdsAsync(string? ownerName, CancellationToken cancellationToken) + { + var name = ownerName?.ToLowerInvariant(); + + #pragma warning disable CS8602, CS8604 + var owned = await _context.PackageOwners.IgnoreQueryFilters().AsNoTracking() + .Where(o => o.OwnerName.ToLower() == name) + .Select(o => new { o.RepositoryKey, o.PackageId }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + return owned.Select(o => (o.RepositoryKey, o.PackageId?.ToLowerInvariant())).Distinct().Count(); + } + + /// + /// Rename an organization. Every row naming it, in every repository, follows in the + /// same save, so ownership is never split between the two names. The new name must be free: users and + /// organizations share one namespace (the organization's own name is free, so a change of case works). + /// + public async Task RenameOrganizationAsync(string? name, string? newName, CancellationToken cancellationToken) + { + var lower = name?.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var organization = await _context.Organizations.FirstOrDefaultAsync(o => o.Name.ToLower() == lower, cancellationToken); + #pragma warning restore CS8602, CS8604 + if (organization == null) return OrganizationChange.NotFound; + + var trimmed = newName?.Trim(); + if (string.IsNullOrEmpty(trimmed) + || trimmed.Length > AbstractContext.MaxAccountNameLength + || trimmed.Any(c => char.IsControl(c) || UnsafeNameCharacters.Contains(c))) + { + return OrganizationChange.InvalidName; + } + + var taken = await AccountExistsAsync(trimmed, cancellationToken) + && !string.Equals(trimmed, organization.Name, StringComparison.OrdinalIgnoreCase); + if (taken) return OrganizationChange.NameTaken; + + var oldLower = organization.Name?.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var owners = await _context.PackageOwners.IgnoreQueryFilters() + .Where(o => o.OwnerName.ToLower() == oldLower) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + organization.Name = trimmed; + foreach (var owner in owners) owner.OwnerName = trimmed; + + await _context.SaveChangesAsync(cancellationToken); + + return OrganizationChange.Success; + } + + // Names appear in URL paths (/admin/organizations/{name}), so these cannot be in one. + private const string UnsafeNameCharacters = "/\\?#%"; + + /// + /// Delete an organization and its memberships. Refused while it owns a package ID in any repository: the + /// IDs would be left without an owner. (Remove it as an owner first, or hand the IDs over.) The permission grants and + /// project roles that name the organization go with it, in the same save as the deletion, and an access audit entry + /// (organization.delete) records it; is the user name that did it. + /// + public async Task DeleteOrganizationAsync(string? name, CancellationToken cancellationToken, string? actor = null) + { + var lower = name?.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var organization = await _context.Organizations.FirstOrDefaultAsync(o => o.Name.ToLower() == lower, cancellationToken); + #pragma warning restore CS8602, CS8604 + if (organization == null) return OrganizationChange.NotFound; + + if (await CountOwnedPackageIdsAsync(organization.Name, cancellationToken) > 0) return OrganizationChange.OwnsPackages; + + #pragma warning disable CS8602, CS8604 + var members = await _context.OrganizationMembers.Where(m => m.OrganizationKey == organization.Key).ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + _context.OrganizationMembers.RemoveRange(members); + var cleaned = await AccessAdministration.StageCleanupAsync(_context, PrincipalType.Organization, organization.Key.ToString(), cancellationToken); + _context.Organizations.Remove(organization); + if (_context.AccessAuditEntries != null) + { + AccessAdministration.Audit(_context, _time.UtcNow, actor, "organization.delete", organization.Name, new { members = members.Count, accessRows = cleaned }); + } + + await _context.SaveChangesAsync(cancellationToken); + + return OrganizationChange.Success; + } + + /// + /// Make a member an administrator of the organization, or not. The last administrator cannot be demoted. + /// + public async Task SetMemberAdminAsync(string organizationName, string userId, bool isAdmin, CancellationToken cancellationToken) + { + var name = organizationName.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var members = await _context.OrganizationMembers + .Where(m => m.Organization != null && m.Organization.Name.ToLower() == name) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + var member = members.FirstOrDefault(m => m.UserId == userId); + if (member == null) return OrganizationChange.NotFound; + if (member.IsAdmin && !isAdmin && members.Count(m => m.IsAdmin) == 1) return OrganizationChange.LastAdministrator; + + member.IsAdmin = isAdmin; + await _context.SaveChangesAsync(cancellationToken); + + return OrganizationChange.Success; + } +} \ No newline at end of file diff --git a/src/BaGet.Identity.Application/Services/Sessions/ExchangeTokenLedger.cs b/src/BaGet.Identity.Application/Services/Sessions/ExchangeTokenLedger.cs new file mode 100644 index 000000000..7793e20fe --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/ExchangeTokenLedger.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using BaGet.Core; + +namespace BaGet.Identity.Application.Services.Sessions; + +/// +/// Remembers the exchange tokens of the external sign-in that were used, until they would have expired anyway, so each works once (the tokens themselves are stateless). +/// Only a hash is kept. In a cluster (Ha:Enabled) the shared store is used, otherwise memory (per process). +/// +public sealed class ExchangeTokenLedger +{ + private readonly SystemTime _time; + private readonly IClusterStore? _shared; + private readonly ConcurrentDictionary _used = new(); + + /// Creates the ledger. + public ExchangeTokenLedger(SystemTime time, ClusterRuntime? cluster = null) + { + _time = time ?? throw new ArgumentNullException(nameof(time)); + _shared = cluster?.Store; + } + + /// Records the token as used; false when it was used before. + /// The exchange token. + /// When it expires: the record is kept until then. + public bool TryUse(string token, DateTime expiresAt) + { + var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + var now = _time.UtcNow; + var keep = expiresAt - now + TimeSpan.FromSeconds(5); + if (keep < TimeSpan.FromSeconds(1)) keep = TimeSpan.FromSeconds(1); + + if (_shared != null) return _shared.SetIfAbsent("exchange:" + key, "1", keep); + + if (_used.Count > 1024) + { + foreach (var pair in _used) + { + if (pair.Value <= now) _used.TryRemove(pair.Key, out _); + } + } + + return _used.TryAdd(key, expiresAt + TimeSpan.FromSeconds(5)); + } +} diff --git a/src/BaGet.Identity.Application/Services/Sessions/IssuedSessionToken.cs b/src/BaGet.Identity.Application/Services/Sessions/IssuedSessionToken.cs new file mode 100644 index 000000000..ea20b958a --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/IssuedSessionToken.cs @@ -0,0 +1,8 @@ +using System; + +namespace BaGet.Identity.Application.Services.Sessions; + +/// A token just issued and when it expires. +/// The value to send as Authorization: Bearer (never logged or stored). +/// When it stops being accepted (UTC). +public sealed record IssuedSessionToken(string Token, DateTime ExpiresAt); diff --git a/src/BaGet.Identity.Application/Services/Sessions/SessionAuthentication.cs b/src/BaGet.Identity.Application/Services/Sessions/SessionAuthentication.cs new file mode 100644 index 000000000..ab2251b5f --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/SessionAuthentication.cs @@ -0,0 +1,16 @@ +using System; +using System.Security.Claims; +using BaGet.Core; + +namespace BaGet.Identity.Application.Services.Sessions; + +/// A session token that was accepted: the account it stands for, as the services see a signed-in user. +/// The claims principal (user id and name), what the cookie session would put in HttpContext.User. +/// The same user as the authorization services see them: every scope, no repository limit, . +/// The account. +/// When the user signed in (a refresh keeps it). +public sealed record SessionAuthentication(ClaimsPrincipal User, BaGetPrincipal Principal, BaGetUser Account, DateTime AuthenticatedAt) +{ + /// When the token stops being accepted. + public DateTime ExpiresAt { get; init; } +} diff --git a/src/BaGet.Identity.Application/Services/Sessions/SessionAuthenticator.cs b/src/BaGet.Identity.Application/Services/Sessions/SessionAuthenticator.cs new file mode 100644 index 000000000..4d12f46b6 --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/SessionAuthenticator.cs @@ -0,0 +1,49 @@ +using System; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Security; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.Services.Sessions; + +/// +/// Turns a session token into the account it stands for, checking on every use what a stateless token cannot: the account still exists, is not awaiting +/// approval, and its security stamp is the one the token was issued with (so a password change or "sign out everywhere" voids every token). +/// A refusal says nothing about why. +/// +public sealed class SessionAuthenticator +{ + private readonly SessionTokenService _tokens; + private readonly UserManager _users; + + /// Creates the authenticator. + public SessionAuthenticator(SessionTokenService tokens, UserManager users) + { + _tokens = tokens ?? throw new ArgumentNullException(nameof(tokens)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + } + + /// The account behind of , or null when the token is not acceptable. + public async Task AuthenticateAsync(SessionTokenKind kind, string? token) + { + var claims = _tokens.Validate(kind, token); + if (claims == null) return null; + + var account = await _users.FindByIdAsync(claims.UserId); + + // Like a cookie session: an account that is locked out (by someone guessing its password) keeps the sessions it has; only a sign-in is refused. + if (account == null || account.PendingApproval) return null; + + var stamp = _users.SupportsUserSecurityStamp ? await _users.GetSecurityStampAsync(account) : string.Empty; + if (!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(stamp ?? string.Empty), Encoding.UTF8.GetBytes(claims.SecurityStamp))) return null; + + var identity = new ClaimsIdentity("BaGetSession", ClaimTypes.Name, ClaimTypes.Role); + identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, account.Id)); + if (account.UserName != null) identity.AddClaim(new Claim(ClaimTypes.Name, account.UserName)); + + return new SessionAuthentication(new ClaimsPrincipal(identity), SessionPrincipalFactory.For(account), account, claims.AuthenticatedAt) { ExpiresAt = claims.ExpiresAt }; + } +} diff --git a/src/BaGet.Identity.Application/Services/Sessions/SessionHeaders.cs b/src/BaGet.Identity.Application/Services/Sessions/SessionHeaders.cs new file mode 100644 index 000000000..daa3cb6aa --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/SessionHeaders.cs @@ -0,0 +1,24 @@ +namespace BaGet.Identity.Application.Services.Sessions; + +/// +/// The response headers that carry a renewed pair of tokens. An action that changes the account's security stamp on purpose (turning two-factor on, +/// resetting the authenticator, changing the password) keeps the current cookie session signed in; for a token session it answers new tokens in these +/// headers instead, and the client replaces the ones it holds. Every other session of the account ends. +/// +public static class SessionHeaders +{ + /// The new access token. + public const string AccessToken = "X-Session-Access-Token"; + + /// When the new access token expires (UTC, ISO 8601). + public const string AccessExpires = "X-Session-Access-Expires"; + + /// The new refresh token. + public const string RefreshToken = "X-Session-Refresh-Token"; + + /// When the new refresh token expires (UTC, ISO 8601). + public const string RefreshExpires = "X-Session-Refresh-Expires"; + + /// All of them, for Access-Control-Expose-Headers. + public static readonly string[] All = { AccessToken, AccessExpires, RefreshToken, RefreshExpires }; +} diff --git a/src/BaGet.Identity.Application/Services/Sessions/SessionTokenClaims.cs b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenClaims.cs new file mode 100644 index 000000000..1e7f335cb --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenClaims.cs @@ -0,0 +1,10 @@ +using System; + +namespace BaGet.Identity.Application.Services.Sessions; + +/// What a valid session token says. +/// The account it was issued to. +/// The account's security stamp when it was issued: a different stamp now (password change, sign out everywhere) voids the token. +/// When the user proved who they are (the sign-in); a refresh keeps it. +/// When the token stops being accepted. +public sealed record SessionTokenClaims(string UserId, string SecurityStamp, DateTime AuthenticatedAt, DateTime ExpiresAt); diff --git a/src/BaGet.Identity.Application/Services/Sessions/SessionTokenKind.cs b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenKind.cs new file mode 100644 index 000000000..07afac2fa --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenKind.cs @@ -0,0 +1,17 @@ +namespace BaGet.Identity.Application.Services.Sessions; + +/// What a session token may be used for. Each kind is protected under its own purpose, so one can never be presented as another. +public enum SessionTokenKind +{ + /// Authenticates a request to /api/ui as the signed-in user. + Access, + + /// Only exchanged for a new pair of tokens (POST /api/ui/session/refresh). + Refresh, + + /// Proves the password step of a sign-in with two-factor authentication; only completes it with a code. + TwoFactor, + + /// Handed to the browser in the URL fragment after the external provider's sign-in and exchanged at POST /api/ui/session/exchange within a minute: keeps the real tokens out of URLs. + Exchange, +} diff --git a/src/BaGet.Identity.Application/Services/Sessions/SessionTokenPayload.cs b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenPayload.cs new file mode 100644 index 000000000..ebc780f7c --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenPayload.cs @@ -0,0 +1,22 @@ +using System.Text.Json.Serialization; + +namespace BaGet.Identity.Application.Services.Sessions; + +/// What a session token holds before it is protected (see ). +internal sealed class SessionTokenPayload +{ + [JsonPropertyName("v")] + public int Version { get; set; } = 1; + + [JsonPropertyName("sub")] + public string? UserId { get; set; } + + [JsonPropertyName("stamp")] + public string? SecurityStamp { get; set; } + + [JsonPropertyName("auth")] + public long AuthenticatedAt { get; set; } + + [JsonPropertyName("exp")] + public long Expires { get; set; } +} diff --git a/src/BaGet.Identity.Application/Services/Sessions/SessionTokenService.cs b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenService.cs new file mode 100644 index 000000000..ae4fa3b7e --- /dev/null +++ b/src/BaGet.Identity.Application/Services/Sessions/SessionTokenService.cs @@ -0,0 +1,130 @@ +using System; +using System.Security.Cryptography; +using System.Text.Json; +using BaGet.Core; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Options; + +namespace BaGet.Identity.Application.Services.Sessions; + +/// +/// Issues and reads the tokens of an interactive session (/api/ui/session): stateless, ASP.NET Core data protection over a JSON payload +/// (user id, security stamp, authentication time, expiry), one purpose per , a that tells them from +/// API keys. Nothing is stored; re-validates the account and the stamp on every use, so changing the password or +/// signing out everywhere ends every token. Only /api/ui accepts them (a protocol route reads them as an invalid key). +/// +public sealed class SessionTokenService +{ + /// The start of every session token, so it is never mistaken for an API key. + public const string Prefix = "bgs."; + + /// How long the password step of a two-factor sign-in stays valid. + public static readonly TimeSpan TwoFactorLifetime = TimeSpan.FromMinutes(5); + + /// How long the exchange token of an external sign-in stays valid. + public static readonly TimeSpan ExchangeLifetime = TimeSpan.FromSeconds(60); + + private const string Purpose = "BaGet.Session.Token.v1"; + private const int MaxLength = 4 * 1024; + + private readonly IDataProtectionProvider? _protection; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + + /// Creates the service. + public SessionTokenService(SystemTime time, IOptionsSnapshot options, IDataProtectionProvider? protection = null) + { + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _protection = protection; + } + + /// Whether data protection exists, without which no token can be issued. + public bool IsAvailable => _protection != null; + + /// Whether looks like a session token (it may still be invalid). + public static bool IsSessionToken(string? credential) + => credential != null && credential.StartsWith(Prefix, StringComparison.Ordinal); + + /// The lifetime of a token of . + public TimeSpan LifetimeOf(SessionTokenKind kind) + { + var accounts = _options.Value; + + return kind switch + { + SessionTokenKind.Access => AtLeast(accounts.SessionTokenLifetime, TimeSpan.FromSeconds(10)), + SessionTokenKind.Refresh => AtLeast(accounts.SessionRefreshLifetime, TimeSpan.FromMinutes(1)), + SessionTokenKind.Exchange => ExchangeLifetime, + _ => TwoFactorLifetime, + }; + } + + private static TimeSpan AtLeast(TimeSpan value, TimeSpan floor) => value < floor ? floor : value; + + /// Issues a token for the account; is the time of the sign-in it belongs to. + public IssuedSessionToken Issue(SessionTokenKind kind, string userId, string securityStamp, DateTime authenticatedAt) + { + if (_protection == null) throw new InvalidOperationException("Session tokens need ASP.NET Core data protection, which this host does not provide."); + + var expires = DateTime.SpecifyKind(_time.UtcNow, DateTimeKind.Utc) + LifetimeOf(kind); + + // However often it is refreshed, a session ends SessionMaxLifetime after the sign-in. + if (kind is SessionTokenKind.Access or SessionTokenKind.Refresh) + { + var end = DateTime.SpecifyKind(authenticatedAt, DateTimeKind.Utc) + AtLeast(_options.Value.SessionMaxLifetime, TimeSpan.FromMinutes(1)); + if (end < expires) expires = end; + } + var payload = new SessionTokenPayload + { + UserId = userId, + SecurityStamp = securityStamp, + AuthenticatedAt = Seconds(authenticatedAt), + Expires = Seconds(expires), + }; + + var bytes = Protector(kind).Protect(JsonSerializer.SerializeToUtf8Bytes(payload)); + + return new IssuedSessionToken(Prefix + Base64Url(bytes), DateTimeOffset.FromUnixTimeSeconds(payload.Expires).UtcDateTime); + } + + /// The claims of a valid, unexpired token of , or null (tampered with, expired, another kind, another key ring). + public SessionTokenClaims? Validate(SessionTokenKind kind, string? token) + { + if (_protection == null || !IsSessionToken(token) || token!.Length > MaxLength) return null; + + try + { + var payload = JsonSerializer.Deserialize(Protector(kind).Unprotect(FromBase64Url(token.Substring(Prefix.Length)))); + if (payload == null || payload.Version != 1 || string.IsNullOrEmpty(payload.UserId)) return null; + + var expires = DateTimeOffset.FromUnixTimeSeconds(payload.Expires).UtcDateTime; + if (expires <= _time.UtcNow) return null; + + return new SessionTokenClaims( + payload.UserId, + payload.SecurityStamp ?? string.Empty, + DateTimeOffset.FromUnixTimeSeconds(payload.AuthenticatedAt).UtcDateTime, + expires); + } + catch (Exception e) when (e is CryptographicException or FormatException or JsonException or ArgumentException) + { + return null; + } + } + + private IDataProtector Protector(SessionTokenKind kind) => _protection!.CreateProtector(Purpose, kind.ToString()); + + private static long Seconds(DateTime value) + => new DateTimeOffset(DateTime.SpecifyKind(value, DateTimeKind.Utc)).ToUnixTimeSeconds(); + + private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static byte[] FromBase64Url(string text) + { + var padded = text.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + (4 - padded.Length % 4) % 4, '='); + + return Convert.FromBase64String(padded); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Access/AccessAuthorization.cs b/src/BaGet.Identity.Application/UseCases/Access/AccessAuthorization.cs new file mode 100644 index 000000000..dbb43128a --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AccessAuthorization.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// +/// Who may open an access screen beyond the server administrators: the administrators of the project the screen acts on. One place for the view +/// controllers' and the JSON twins' gates. +/// +public static class AccessAuthorization +{ + /// The projects list: server administrators, and anyone who administers at least one project. + public static async Task ProjectsAsync(IAccessAdministration access, bool isServerAdministrator, string? userId, CancellationToken cancellationToken) + => isServerAdministrator || (await AdministeredAsync(access, userId, cancellationToken)).Count > 0; + + /// A project screen: server administrators, and the project's own administrators (the project is the name route value). + public static async Task ProjectAsync(IAccessAdministration access, bool isServerAdministrator, string? userId, string? projectName, CancellationToken cancellationToken) + { + if (isServerAdministrator) return true; + + return !string.IsNullOrEmpty(projectName) && userId != null && await access.IsProjectAdminAsync(userId, projectName, cancellationToken); + } + + /// A permission target screen: server administrators, and the administrators of the target's project for a project target. + public static async Task TargetAsync(IAccessAdministration access, bool isServerAdministrator, string? userId, string? targetName, CancellationToken cancellationToken) + { + if (isServerAdministrator) return true; + if (string.IsNullOrEmpty(targetName) || userId == null) return false; + + var target = await access.GetTargetAsync(targetName, cancellationToken); + + return target?.Target.ProjectName != null && await access.IsProjectAdminAsync(userId, target.Target.ProjectName, cancellationToken); + } + + /// The names of the projects the user administers. + public static async Task> AdministeredAsync(IAccessAdministration access, string? userId, CancellationToken cancellationToken) + => userId == null + ? Array.Empty() + : (await access.ProjectRolesOfUserAsync(userId, cancellationToken)) + .Where(r => r.Role == ProjectRole.Admin).Select(r => r.Project).Distinct(StringComparer.Ordinal).ToList(); +} diff --git a/src/BaGet.Identity.Application/UseCases/Access/AccessCaller.cs b/src/BaGet.Identity.Application/UseCases/Access/AccessCaller.cs new file mode 100644 index 000000000..f4bb469de --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AccessCaller.cs @@ -0,0 +1,11 @@ +using System.Security.Claims; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// +/// Who is using an access-control screen: the signed-in account (or the key owner's) and whether it is a server administrator rather than only a +/// project administrator. The screen gate decided that before the use case runs; the use case only needs it for the rules inside a screen. +/// +/// The signed-in user (for an API key, the key's owner). +/// Whether the caller is a server administrator. +public sealed record AccessCaller(ClaimsPrincipal Principal, bool IsServerAdministrator); diff --git a/src/BaGet.Identity.Application/UseCases/Access/AccessPatternSupport.cs b/src/BaGet.Identity.Application/UseCases/Access/AccessPatternSupport.cs new file mode 100644 index 000000000..609594f01 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AccessPatternSupport.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Models.Policies; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// The parts of the access screens that read and write pattern and action text; shared by the use cases and the controller bases. +public static class AccessPatternSupport +{ + /// The single actions, in display order. + public static readonly AccessAction[] AllActions = + { + AccessAction.Read, AccessAction.Annotate, AccessAction.Deploy, AccessAction.Delete, AccessAction.Manage, + }; + + /// Parses the ticked action boxes (names of values). + public static AccessAction ParseActions(IEnumerable? names) + { + var actions = AccessAction.None; + foreach (var name in names ?? Array.Empty()) + { + if (Enum.TryParse(name, ignoreCase: true, out var action) && action != AccessAction.All) actions |= action; + } + + return actions; + } + + /// The actions in as words, or "none". + public static string Words(AccessAction actions) + => actions == AccessAction.None ? "none" : string.Join(", ", AllActions.Where(a => (actions & a) == a)); + + /// Patterns one per line, the way the editors show them. + public static string Lines(IEnumerable patterns) => string.Join("\n", patterns); + + /// The package filter and repository patterns as one line a person can read back. + public static string Join(IEnumerable patterns) => string.Join(", ", patterns); + + /// What a set of patterns selects: the matching repository names and, for a typed package ID, whether it applies. + public static async Task PreviewAsync( + IRepositoryService repositories, + string[] repositoryPatterns, + string[] includePatterns, + string[] excludePatterns, + string? testPackage, + CancellationToken cancellationToken) + { + var all = await repositories.ListAsync(cancellationToken); + var names = all + .Where(r => AccessPatterns.IsMatch(repositoryPatterns, r.Name)) + .Select(r => r.Name) + .OrderBy(n => n, StringComparer.Ordinal) + .ToList(); + var package = testPackage?.Trim(); + + return new PatternPreview( + names, + string.IsNullOrEmpty(package) ? null : package, + string.IsNullOrEmpty(package) ? null : AccessPatterns.Test(includePatterns, excludePatterns, package)); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Access/AccessUseCaseBase.cs b/src/BaGet.Identity.Application/UseCases/Access/AccessUseCaseBase.cs new file mode 100644 index 000000000..7a9882cef --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AccessUseCaseBase.cs @@ -0,0 +1,92 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// +/// What the use cases of the access-control screens (groups, permission targets, projects, audit) share: the caller, the password confirmation of a +/// change, the audit actor and the conversion of an into the message shown on the screen. The gate that runs first +/// has already decided who may use the screen (an administrator, or a project's administrator, see ); everything else +/// (password, the 404 and administrator-only rules of each action, the audit through ) is in the use case. +/// +public abstract class AccessUseCaseBase : AdminUseCaseBase +{ + /// Creates the base. + protected AccessUseCaseBase( + UserManager users, + PasswordConfirmation confirmation, + IAccessAdministration access, + IRepositoryService repositories, + MaintenanceGate? gate) + : base(users, confirmation, gate) + { + Access = access ?? throw new ArgumentNullException(nameof(access)); + Repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + } + + /// The access model's administration. + protected IAccessAdministration Access { get; } + + /// The repositories. + protected IRepositoryService Repositories { get; } + + /// The user name recorded in the audit log. + protected static string? Actor(AccessCaller caller) => caller.Principal.Identity?.Name; + + /// The caller's user id, or null (the global API key has no account). + protected string? UserIdOf(AccessCaller caller) => Users.GetUserId(caller.Principal); + + /// Fills what the confirmation partial needs; the page to come back to after signing in again is the current request's URL. + protected Task LoadConfirmationAsync(ConfirmationModel model, AccessCaller caller) + => Confirmation.LoadForRequestAsync(model, caller.Principal); + + /// + /// Runs one change: refuses it while the server is read-only, asks for the password when , turns an + /// into the error shown, then answers with (given the message and the error). + /// + /// Who changes. + /// What the user typed. + /// Whether the change asks for the password (grants, memberships, deletions). + /// The change; returns the message to show. + /// Where to go afterwards. + protected async Task> ActAsync( + AccessCaller caller, + string? password, + bool confirm, + Func> change, + Func> back) + { + ThrowIfClosed(); + + if (confirm) + { + var current = await CurrentAsync(caller.Principal); + if (current == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(current, password)) return back(null, NotConfirmed); + } + + string message; + try + { + message = await change(); + } + catch (AccessModelException e) + { + return back(null, e.Message); + } + + return back(message, null); + } + + /// What a set of patterns selects, for the pattern editors. + protected Task PreviewAsync(string[] repositoryPatterns, string[] includePatterns, string[] excludePatterns, string? testPackage, CancellationToken cancellationToken) + => AccessPatternSupport.PreviewAsync(Repositories, repositoryPatterns, includePatterns, excludePatterns, testPackage, cancellationToken); +} diff --git a/src/BaGet.Identity.Application/UseCases/Access/AdminAuditUseCase.cs b/src/BaGet.Identity.Application/UseCases/Access/AdminAuditUseCase.cs new file mode 100644 index 000000000..d389f7820 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AdminAuditUseCase.cs @@ -0,0 +1,53 @@ +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Models.Access; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// +/// The access audit log: one entry per change to groups, memberships, permission targets, grants, projects, the repositories' project and +/// anonymous-read switch, newest first, filtered by who made the change, what it was done to and the dates (UTC, yyyy-MM-dd, both inclusive). +/// Read only; server administrators only (the gate decides). +/// +public sealed class AdminAuditUseCase +{ + /// How many entries the screen lists at most. + public const int PageSize = 200; + + private readonly IAccessAdministration _access; + + /// Creates the use case. + public AdminAuditUseCase(IAccessAdministration access) + { + _access = access ?? throw new ArgumentNullException(nameof(access)); + } + + /// Lists the entries that match the filter. + public async Task> GetAsync(AuditQuery query, CancellationToken cancellationToken) + { + var model = new AuditViewModel { ActorFilter = query.Actor, Subject = query.Subject, From = query.From, To = query.To }; + var from = ParseDay(model, model.From, "From", 0); + var to = ParseDay(model, model.To, "To", 1); + + model.Entries = await _access.AuditAsync(new AuditFilter(model.ActorFilter, model.Subject, from, to), PageSize, cancellationToken); + + return ScreenResult.Ok(model); + } + + private static DateTime? ParseDay(AuditViewModel model, string? text, string field, int addDays) + { + if (string.IsNullOrWhiteSpace(text)) return null; + + if (DateTime.TryParseExact(text.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var day)) + { + return day.AddDays(addDays); + } + + model.FilterError = $"{field} is not a date (use yyyy-MM-dd)."; + return null; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Access/AdminGroupsUseCase.cs b/src/BaGet.Identity.Application/UseCases/Access/AdminGroupsUseCase.cs new file mode 100644 index 000000000..48776b13c --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AdminGroupsUseCase.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// +/// The groups screens of the administrator: the list with the new-group form, and one group (rename, members found by a user-name search, +/// delete). A group is a named set of users that permission targets and project roles can name; the built-in Everyone and +/// Authenticated have implicit members and cannot be renamed or deleted. Membership changes and deletion ask for the password again; every +/// change is refused with 503 while the is closed and goes through , which audits it. +/// +public sealed class AdminGroupsUseCase : AccessUseCaseBase +{ + /// How many users a member search lists. + public const int SearchSize = 20; + + private static readonly ScreenRef ListScreen = ScreenCatalog.AdminGroups; + private static readonly ScreenRef DetailScreen = ScreenCatalog.AdminGroupDetail; + + /// Creates the use case. + public AdminGroupsUseCase( + UserManager users, + PasswordConfirmation confirmation, + IAccessAdministration access, + IRepositoryService repositories, + MaintenanceGate? gate = null) + : base(users, confirmation, access, repositories, gate) + { + } + + /// Lists the groups. + public async Task> ListAsync(AccessCaller caller, CancellationToken cancellationToken) + => ScreenResult.Ok(await LoadListAsync(new GroupsViewModel(), caller, cancellationToken)); + + /// Creates a group and opens it; a refusal shows the list with the reason. + public async Task> CreateAsync(AccessCaller caller, GroupCreation form, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = new GroupsViewModel { Name = form.Name, Description = form.Description }; + try + { + var group = await Access.CreateGroupAsync(form.Name ?? string.Empty, form.Description, Actor(caller), cancellationToken); + + return Back(DetailScreen, Route(("name", group.Name)), $"Group {group.Name} was created.", null); + } + catch (AccessModelException e) + { + model.Error = e.Message; + + return ScreenResult.Ok(await LoadListAsync(model, caller, cancellationToken)); + } + } + + /// Shows the group, with the member search for ; not found when there is none. + public async Task> GetAsync(AccessCaller caller, string? name, string? q, CancellationToken cancellationToken) + { + var model = new GroupDetailViewModel { Name = name, Q = q }; + + return await LoadAsync(model, caller, cancellationToken) + ? ScreenResult.Ok(model) + : ScreenResult.NotFound(); + } + + /// Renames the group. + public Task> RenameAsync(AccessCaller caller, string? name, GroupRename form, CancellationToken cancellationToken) + { + var current = name; + + return ActAsync(caller, null, confirm: false, async () => + { + await Access.RenameGroupAsync(name ?? string.Empty, form.NewName ?? string.Empty, Actor(caller), cancellationToken); + current = form.NewName; + + return $"Group {name} is now called {form.NewName}."; + }, (message, error) => Back(DetailScreen, Route(("name", current)), message, error)); + } + + /// Adds a user to the group. + public Task> AddMemberAsync(AccessCaller caller, string? name, GroupMemberChange form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.AddGroupMemberAsync(name ?? string.Empty, form.UserId ?? string.Empty, Actor(caller), cancellationToken); + + return "The member was added."; + }, (message, error) => Back(DetailScreen, Route(("name", name)), message, error)); + + /// Removes a user from the group. + public Task> RemoveMemberAsync(AccessCaller caller, string? name, GroupMemberChange form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.RemoveGroupMemberAsync(name ?? string.Empty, form.UserId ?? string.Empty, Actor(caller), cancellationToken); + + return "The member was removed."; + }, (message, error) => Back(DetailScreen, Route(("name", name)), message, error)); + + /// Deletes the group with the grants and project roles that name it; on success the list is shown with the outcome. + public Task> DeleteAsync(AccessCaller caller, string? name, PasswordForm form, CancellationToken cancellationToken) + { + var deleted = false; + + return ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.DeleteGroupAsync(name ?? string.Empty, Actor(caller), cancellationToken); + deleted = true; + + return $"Group {name} was deleted."; + }, (message, error) => deleted + ? Back(ListScreen, null, message, error) + : Back(DetailScreen, Route(("name", name)), message, error)); + } + + private async Task LoadListAsync(GroupsViewModel model, AccessCaller caller, CancellationToken cancellationToken) + { + model.IsServerAdministrator = caller.IsServerAdministrator; + model.Groups = await Access.ListGroupsAsync(cancellationToken); + + return model; + } + + private async Task LoadAsync(GroupDetailViewModel model, AccessCaller caller, CancellationToken cancellationToken) + { + model.IsServerAdministrator = caller.IsServerAdministrator; + await LoadConfirmationAsync(model, caller); + + model.Group = await Access.GetGroupAsync(model.Name ?? string.Empty, cancellationToken); + if (model.Group == null) return false; + + if (!model.Group.Group.IsBuiltIn && !string.IsNullOrWhiteSpace(model.Q)) + { + var members = new HashSet(StringComparer.Ordinal); + foreach (var member in model.Group.Members) members.Add(member.UserId); + + var found = await Access.SearchUsersAsync(model.Q, SearchSize, cancellationToken); + var fresh = new List(); + foreach (var user in found) + { + if (!members.Contains(user.UserId)) fresh.Add(user); + } + + model.Found = fresh; + } + + return true; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Access/AdminPermissionsUseCase.cs b/src/BaGet.Identity.Application/UseCases/Access/AdminPermissionsUseCase.cs new file mode 100644 index 000000000..df28b9b07 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AdminPermissionsUseCase.cs @@ -0,0 +1,246 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// +/// The permission target screens of the administrator: the list with the new-target form (server administrators only), and one target (also open to the +/// administrators of the target's project for a project target): its repository and package patterns (with a preview of the repositories they match and a +/// test box for package IDs), and the grants, which users, groups or organizations hold which of Read, Annotate, Deploy, Delete and Manage through it. +/// Saving patterns, setting or removing a grant and deleting ask for the password again; every change is refused with 503 while the +/// is closed and goes through , which audits it. +/// +public sealed class AdminPermissionsUseCase : AccessUseCaseBase +{ + private static readonly ScreenRef ListScreen = ScreenCatalog.AdminPermissions; + private static readonly ScreenRef DetailScreen = ScreenCatalog.AdminPermissionDetail; + + /// Creates the use case. + public AdminPermissionsUseCase( + UserManager users, + PasswordConfirmation confirmation, + IAccessAdministration access, + IRepositoryService repositories, + MaintenanceGate? gate = null) + : base(users, confirmation, access, repositories, gate) + { + } + + /// Lists the targets. + public async Task> ListAsync(AccessCaller caller, CancellationToken cancellationToken) + => ScreenResult.Ok(await LoadListAsync(new PermissionsViewModel(), caller, cancellationToken)); + + /// Creates a target and opens it; a refusal shows the list with the reason. + public async Task> CreateAsync(AccessCaller caller, PermissionTargetForm form, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = ListModel(form); + try + { + int? projectKey = null; + if (!string.IsNullOrWhiteSpace(form.Project)) + { + var project = await Access.GetProjectAsync(form.Project.Trim(), cancellationToken) + ?? throw new AccessModelException($"There is no project named '{form.Project}'."); + projectKey = project.Project.Key; + } + + var target = await Access.CreateTargetAsync( + form.Name ?? string.Empty, + AccessPatterns.Split(form.RepositoryPatterns), + AccessPatterns.Split(form.IncludePatterns), + AccessPatterns.Split(form.ExcludePatterns), + projectKey, + Actor(caller), + cancellationToken); + + return Back(DetailScreen, Route(("name", target.Name)), $"Permission target {target.Name} was created. Add grants to it.", null); + } + catch (AccessModelException e) + { + model.Error = e.Message; + + return ScreenResult.Ok(await LoadListAsync(model, caller, cancellationToken)); + } + } + + /// Previews the form patterns without saving anything. + public async Task> PreviewAsync(AccessCaller caller, PermissionTargetForm form, CancellationToken cancellationToken) + { + var model = await LoadListAsync(ListModel(form), caller, cancellationToken); + model.Preview = await PreviewAsync( + AccessPatterns.Split(form.RepositoryPatterns), AccessPatterns.Split(form.IncludePatterns), AccessPatterns.Split(form.ExcludePatterns), form.TestPackage, cancellationToken); + + return ScreenResult.Ok(model); + } + + /// Re-creates the built-in groups and targets that are missing (the upgrade defaults). + public Task> RestoreBuiltInsAsync(AccessCaller caller, PasswordForm form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.RestoreBuiltInsAsync(Actor(caller), cancellationToken); + + return "The built-in groups and permission targets were restored where they were missing."; + }, (message, error) => Back(ListScreen, null, message, error)); + + /// Shows the target (not found when there is none); and pre-fill the grant form. + public async Task> GetAsync( + AccessCaller caller, string? name, string? testPackage, PrincipalType? principalType, string? principalName, CancellationToken cancellationToken) + { + var model = DetailModel(name, new PermissionTargetForm(TestPackage: testPackage, PrincipalType: principalType, PrincipalName: principalName)); + if (!await LoadAsync(model, caller, cancellationToken)) return ScreenResult.NotFound(); + + var target = model.Target!; + model.RepositoryPatterns = AccessPatternSupport.Lines(target.Target.RepositoryPatterns); + model.IncludePatterns = AccessPatternSupport.Lines(target.Target.IncludePatterns); + model.ExcludePatterns = AccessPatternSupport.Lines(target.Target.ExcludePatterns); + model.Preview = await RestrictToProjectAsync(model, await PreviewAsync( + target.Target.RepositoryPatterns.ToArray(), target.Target.IncludePatterns.ToArray(), target.Target.ExcludePatterns.ToArray(), model.TestPackage, cancellationToken), cancellationToken); + + if (!string.IsNullOrWhiteSpace(model.PrincipalName)) + { + var id = await Access.ResolvePrincipalAsync(model.PrincipalType, model.PrincipalName, cancellationToken); + var existing = target.Grants.FirstOrDefault(g => g.PrincipalType == model.PrincipalType && g.PrincipalId == id); + model.FormActions = existing?.Actions ?? AccessAction.None; + } + + return ScreenResult.Ok(model); + } + + /// Previews the form patterns (and the test package) without saving anything. + public async Task> PreviewDetailAsync(AccessCaller caller, string? name, PermissionTargetForm form, CancellationToken cancellationToken) + { + var model = DetailModel(name, form); + if (!await LoadAsync(model, caller, cancellationToken)) return ScreenResult.NotFound(); + + model.Preview = await RestrictToProjectAsync(model, await PreviewAsync( + AccessPatterns.Split(model.RepositoryPatterns), AccessPatterns.Split(model.IncludePatterns), AccessPatterns.Split(model.ExcludePatterns), model.TestPackage, cancellationToken), cancellationToken); + + return ScreenResult.Ok(model); + } + + /// Replaces the target's patterns. + public Task> SaveAsync(AccessCaller caller, string? name, PermissionTargetForm form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.UpdateTargetAsync( + name ?? string.Empty, + AccessPatterns.Split(form.RepositoryPatterns), + AccessPatterns.Split(form.IncludePatterns), + AccessPatterns.Split(form.ExcludePatterns), + Actor(caller), + cancellationToken); + + return "The patterns were saved."; + }, (message, error) => Back(DetailScreen, Route(("name", name)), message, error)); + + /// Gives a principal the ticked actions through the target, replacing an earlier grant to it. + public Task> SetGrantAsync(AccessCaller caller, string? name, GrantForm form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + var type = form.PrincipalType ?? PrincipalType.Group; + var id = await Access.ResolvePrincipalAsync(type, form.PrincipalName ?? string.Empty, cancellationToken) + ?? throw new AccessModelException($"There is no {type.ToString().ToLowerInvariant()} named '{form.PrincipalName}'."); + var granted = AccessPatternSupport.ParseActions(form.Actions); + await Access.SetGrantAsync(name ?? string.Empty, type, id, granted, Actor(caller), cancellationToken); + + return granted == AccessAction.None + ? $"{form.PrincipalName} holds nothing through this target any more." + : $"{form.PrincipalName} now holds {AccessPatternSupport.Words(granted)} through this target."; + }, (message, error) => Back(DetailScreen, Route(("name", name)), message, error)); + + /// Removes a principal's grant. + public Task> RemoveGrantAsync(AccessCaller caller, string? name, PrincipalRemoval form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.SetGrantAsync(name ?? string.Empty, form.Type, form.PrincipalId ?? string.Empty, AccessAction.None, Actor(caller), cancellationToken); + + return "The grant was removed."; + }, (message, error) => Back(DetailScreen, Route(("name", name)), message, error)); + + /// Deletes the target and its grants; a project administrator is taken back to the project. + public async Task> DeleteAsync(AccessCaller caller, string? name, PasswordForm form, CancellationToken cancellationToken) + { + var deleted = false; + var project = (await Access.GetTargetAsync(name ?? string.Empty, cancellationToken))?.Target.ProjectName; + + return await ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.DeleteTargetAsync(name ?? string.Empty, Actor(caller), cancellationToken); + deleted = true; + + return $"Permission target {name} was deleted."; + }, (message, error) => + { + if (!deleted) return Back(DetailScreen, Route(("name", name)), message, error); + + return caller.IsServerAdministrator || project == null + ? Back(ListScreen, null, message, error) + : Back(ScreenCatalog.AdminProjectDetail, Route(("name", project)), message, error); + }); + } + + private static PermissionsViewModel ListModel(PermissionTargetForm form) + => new() + { + Name = form.Name, + RepositoryPatterns = form.RepositoryPatterns, + IncludePatterns = form.IncludePatterns, + ExcludePatterns = form.ExcludePatterns, + Project = form.Project, + TestPackage = form.TestPackage, + }; + + private static PermissionDetailViewModel DetailModel(string? name, PermissionTargetForm form) + => new() + { + Name = name, + RepositoryPatterns = form.RepositoryPatterns, + IncludePatterns = form.IncludePatterns, + ExcludePatterns = form.ExcludePatterns, + TestPackage = form.TestPackage, + PrincipalType = form.PrincipalType ?? PrincipalType.Group, + PrincipalName = form.PrincipalName, + }; + + private async Task LoadListAsync(PermissionsViewModel model, AccessCaller caller, CancellationToken cancellationToken) + { + model.IsServerAdministrator = caller.IsServerAdministrator; + await LoadConfirmationAsync(model, caller); + model.Targets = await Access.ListTargetsAsync(cancellationToken); + model.Projects = await Access.ListProjectsAsync(cancellationToken); + + return model; + } + + // A project target only ever applies to the project's repositories, so that is all the preview may show (and all a + // project administrator may learn about). + private async Task RestrictToProjectAsync(PermissionDetailViewModel model, PatternPreview preview, CancellationToken cancellationToken) + { + var projectName = model.Target?.Target.ProjectName; + if (projectName == null) return preview; + + var project = await Access.GetProjectAsync(projectName, cancellationToken); + var own = project?.Repositories ?? Array.Empty(); + + return preview with { Repositories = preview.Repositories.Where(r => own.Contains(r, StringComparer.Ordinal)).ToList() }; + } + + private async Task LoadAsync(PermissionDetailViewModel model, AccessCaller caller, CancellationToken cancellationToken) + { + model.IsServerAdministrator = caller.IsServerAdministrator; + await LoadConfirmationAsync(model, caller); + model.Target = await Access.GetTargetAsync(model.Name ?? string.Empty, cancellationToken); + + return model.Target != null; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Access/AdminProjectsUseCase.cs b/src/BaGet.Identity.Application/UseCases/Access/AdminProjectsUseCase.cs new file mode 100644 index 000000000..6e16ae4cc --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Access/AdminProjectsUseCase.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.UseCases.Access; + +/// +/// The project screens: the list with the new-project form, and one project (its repositories, members with their roles, and the permission targets that +/// apply only to its repositories). Server administrators see every project and create and delete them and assign repositories; a project's own +/// administrators (the project is the name route value, checked by the gate with ) see the projects they +/// administer and manage members and targets. Member changes and deletions ask for the password again; every change is refused with 503 while the +/// is closed and goes through , which audits it. +/// +public sealed class AdminProjectsUseCase : AccessUseCaseBase +{ + private static readonly ScreenRef ListScreen = ScreenCatalog.AdminProjects; + private static readonly ScreenRef DetailScreen = ScreenCatalog.AdminProjectDetail; + + /// Creates the use case. + public AdminProjectsUseCase( + UserManager users, + PasswordConfirmation confirmation, + IAccessAdministration access, + IRepositoryService repositories, + MaintenanceGate? gate = null) + : base(users, confirmation, access, repositories, gate) + { + } + + /// Lists the projects the caller may open. + public async Task> ListAsync(AccessCaller caller, CancellationToken cancellationToken) + => ScreenResult.Ok(await LoadListAsync(new ProjectsViewModel(), caller, cancellationToken)); + + /// Creates a project (administrators only) and opens it; a refusal shows the list with the reason. + public async Task> CreateAsync(AccessCaller caller, ProjectCreation form, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + if (!caller.IsServerAdministrator) return ScreenResult.NotFound(); + + var model = new ProjectsViewModel { Name = form.Name, DisplayName = form.DisplayName }; + try + { + var project = await Access.CreateProjectAsync( + form.Name ?? string.Empty, + string.IsNullOrWhiteSpace(form.DisplayName) ? null : form.DisplayName.Trim(), + Actor(caller), + cancellationToken); + + return Back(DetailScreen, Route(("name", project.Name)), $"Project {project.Name} was created.", null); + } + catch (AccessModelException e) + { + model.Error = e.Message; + + return ScreenResult.Ok(await LoadListAsync(model, caller, cancellationToken)); + } + } + + /// Shows the project; not found when there is none. + public async Task> GetAsync(AccessCaller caller, string? name, CancellationToken cancellationToken) + { + var model = new ProjectDetailViewModel { Name = name }; + + return await LoadAsync(model, caller, cancellationToken) + ? ScreenResult.Ok(model) + : ScreenResult.NotFound(); + } + + /// Gives a user or group a role in the project, replacing an earlier one. + public Task> SetMemberAsync(AccessCaller caller, string? name, ProjectMemberForm form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + if (form.Type == PrincipalType.Organization) throw new AccessModelException("A project member is a user or a group."); + + var id = await Access.ResolvePrincipalAsync(form.Type, form.PrincipalName ?? string.Empty, cancellationToken) + ?? throw new AccessModelException($"There is no {form.Type.ToString().ToLowerInvariant()} named '{form.PrincipalName}'."); + await Access.SetProjectMemberAsync(name ?? string.Empty, form.Type, id, form.Role, Actor(caller), cancellationToken); + + return $"{form.PrincipalName} is now {form.Role} of {name}."; + }, (message, error) => BackToProject(name, message, error)); + + /// Takes a user or group out of the project. + public Task> RemoveMemberAsync(AccessCaller caller, string? name, PrincipalRemoval form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + await Access.RemoveProjectMemberAsync(name ?? string.Empty, form.Type, form.PrincipalId ?? string.Empty, Actor(caller), cancellationToken); + + return "The member was removed."; + }, (message, error) => BackToProject(name, message, error)); + + /// Puts a repository in the project (server administrators only); it leaves any project it was in. + public Task> AssignRepositoryAsync(AccessCaller caller, string? name, ProjectRepositoryForm form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + if (!caller.IsServerAdministrator) throw new AccessModelException("Only server administrators assign repositories to projects."); + + await Access.SetRepositoryProjectAsync(form.Repository ?? string.Empty, name, Actor(caller), cancellationToken); + + return $"Repository {form.Repository} is now in {name}."; + }, (message, error) => BackToProject(name, message, error)); + + /// Takes a repository out of the project (server administrators only). + public Task> UnassignRepositoryAsync(AccessCaller caller, string? name, ProjectRepositoryForm form, CancellationToken cancellationToken) + => ActAsync(caller, form.Password, confirm: true, async () => + { + if (!caller.IsServerAdministrator) throw new AccessModelException("Only server administrators take repositories out of projects."); + + await Access.SetRepositoryProjectAsync(form.Repository ?? string.Empty, null, Actor(caller), cancellationToken); + + return $"Repository {form.Repository} is no longer in {name}."; + }, (message, error) => BackToProject(name, message, error)); + + /// Creates a permission target that applies only to the project's repositories and opens it; a refusal shows the project with the reason. + public async Task> CreateTargetAsync(AccessCaller caller, string? name, ProjectTargetForm form, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = DetailModel(name, form); + if (!await LoadAsync(model, caller, cancellationToken)) return ScreenResult.NotFound(); + + try + { + var target = await Access.CreateTargetAsync( + form.TargetName ?? string.Empty, + AccessPatterns.Split(form.RepositoryPatterns), + AccessPatterns.Split(form.IncludePatterns), + AccessPatterns.Split(form.ExcludePatterns), + model.Project!.Project.Key, + Actor(caller), + cancellationToken); + + return Back(ScreenCatalog.AdminPermissionDetail, Route(("name", target.Name)), $"Permission target {target.Name} was created. Add grants to it.", null); + } + catch (AccessModelException e) + { + model.Error = e.Message; + + return ScreenResult.Ok(model); + } + } + + /// Previews the new target's patterns without saving anything. + public async Task> PreviewAsync(AccessCaller caller, string? name, ProjectTargetForm form, CancellationToken cancellationToken) + { + var model = DetailModel(name, form); + if (!await LoadAsync(model, caller, cancellationToken)) return ScreenResult.NotFound(); + + // Only the project's own repositories can be reached, whatever the patterns say. + var preview = await PreviewAsync( + AccessPatterns.Split(form.RepositoryPatterns), AccessPatterns.Split(form.IncludePatterns), AccessPatterns.Split(form.ExcludePatterns), form.TestPackage, cancellationToken); + model.Preview = preview with { Repositories = preview.Repositories.Where(r => model.Project!.Repositories.Contains(r, StringComparer.Ordinal)).ToList() }; + + return ScreenResult.Ok(model); + } + + /// Deletes the project (server administrators only) with its members and targets; the repositories stay. On success the list is shown. + public Task> DeleteAsync(AccessCaller caller, string? name, PasswordForm form, CancellationToken cancellationToken) + { + var deleted = false; + + return ActAsync(caller, form.Password, confirm: true, async () => + { + if (!caller.IsServerAdministrator) throw new AccessModelException("Only server administrators delete projects."); + + await Access.DeleteProjectAsync(name ?? string.Empty, Actor(caller), cancellationToken); + deleted = true; + + return $"Project {name} was deleted."; + }, (message, error) => deleted + ? Back(ListScreen, null, message, error) + : BackToProject(name, message, error)); + } + + private static ScreenResult BackToProject(string? name, string? message, string? error) + => Back(DetailScreen, Route(("name", name)), message, error); + + private static ProjectDetailViewModel DetailModel(string? name, ProjectTargetForm form) + => new() + { + Name = name, + TargetName = form.TargetName, + RepositoryPatterns = form.RepositoryPatterns, + IncludePatterns = form.IncludePatterns, + ExcludePatterns = form.ExcludePatterns, + TestPackage = form.TestPackage, + }; + + private async Task LoadListAsync(ProjectsViewModel model, AccessCaller caller, CancellationToken cancellationToken) + { + model.IsServerAdministrator = caller.IsServerAdministrator; + var all = await Access.ListProjectsAsync(cancellationToken); + if (caller.IsServerAdministrator) + { + model.Projects = all; + return model; + } + + var mine = new HashSet(await AccessAuthorization.AdministeredAsync(Access, UserIdOf(caller), cancellationToken), StringComparer.Ordinal); + model.Projects = all.Where(p => mine.Contains(p.Name)).ToList(); + + return model; + } + + private async Task LoadAsync(ProjectDetailViewModel model, AccessCaller caller, CancellationToken cancellationToken) + { + model.IsServerAdministrator = caller.IsServerAdministrator; + await LoadConfirmationAsync(model, caller); + + model.Project = await Access.GetProjectAsync(model.Name ?? string.Empty, cancellationToken); + if (model.Project == null) return false; + + // Only a server administrator assigns repositories; the view shows the list to nobody else, so the model must not carry it. + if (caller.IsServerAdministrator) + { + var all = await Repositories.ListAsync(cancellationToken); + model.Assignable = all + .Where(r => !model.Project.Repositories.Contains(r.Name, StringComparer.Ordinal)) + .Select(r => r.Name) + .OrderBy(n => n, StringComparer.Ordinal) + .ToList(); + } + + return true; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/AccountOverviewUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/AccountOverviewUseCase.cs new file mode 100644 index 000000000..246491c09 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/AccountOverviewUseCase.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Organizations; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.Services.Ownership; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// The signed-in user's own overview screens: their organizations (create one, manage the members of those they administer), "My packages" and +/// "My access", and the redirect from "my profile" to the profile page. Every method needs a signed-in session; none changes credentials. +/// +public sealed class AccountOverviewUseCase +{ + private readonly UserManager _users; + private readonly PackageOwnershipService _ownership; + private readonly IServiceProvider _services; + + /// Creates the use case. + public AccountOverviewUseCase(UserManager users, PackageOwnershipService ownership, IServiceProvider services) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + // ----- organizations + + /// The organizations of the user. + public async Task> ShowOrganizationsAsync(ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var model = new OrganizationsViewModel(); + await LoadOrganizationsAsync(caller, model, cancellationToken); + + return ScreenResult.Ok(model); + } + + /// Create an organization. + public async Task> CreateOrganizationAsync(ClaimsPrincipal caller, CreateOrganizationForm? form, CancellationToken cancellationToken) + { + var name = form?.Name; + var created = await _ownership.CreateOrganizationAsync(name!, _users.GetUserId(caller), cancellationToken); + + return await DoneAsync(caller, created ? $"Created {name}." : "That name is taken.", cancellationToken); + } + + /// Add a member (organization administrators only). + public async Task> AddMemberAsync(ClaimsPrincipal caller, AddOrganizationMemberForm? form, CancellationToken cancellationToken) + { + var organization = form?.Organization; + if (!await _ownership.IsOrganizationAdminAsync(organization, _users.GetUserId(caller), cancellationToken)) + { + return ScreenResult.Forbidden(); + } + + var userName = form!.UserName; + var user = string.IsNullOrWhiteSpace(userName) ? null : await _users.FindByNameAsync(userName.Trim()); + if (user == null) + { + return await DoneAsync(caller, "There is no user with that name.", cancellationToken); + } + + var added = await _ownership.AddMemberAsync(organization!, user.Id, form.IsAdmin, cancellationToken); + + return await DoneAsync(caller, added ? $"{user.UserName} joined {organization}." : $"{user.UserName} is already a member.", cancellationToken); + } + + /// Remove a member (an administrator removes anyone; any member may leave). + public async Task> RemoveMemberAsync(ClaimsPrincipal caller, RemoveOrganizationMemberForm? form, CancellationToken cancellationToken) + { + var organization = form?.Organization; + var currentUserId = _users.GetUserId(caller); + var user = await _users.FindByNameAsync(form?.UserName ?? string.Empty); + + // An administrator may remove anyone; any member may leave. + if (user == null + || (user.Id != currentUserId && !await _ownership.IsOrganizationAdminAsync(organization, currentUserId, cancellationToken))) + { + return ScreenResult.Forbidden(); + } + + var removed = await _ownership.RemoveMemberAsync(organization!, user.Id, cancellationToken); + + return await DoneAsync( + caller, + removed ? $"{user.UserName} left {organization}." : "An organization must keep at least one administrator.", + cancellationToken); + } + + private async Task> DoneAsync(ClaimsPrincipal caller, string message, CancellationToken cancellationToken) + { + var model = new OrganizationsViewModel { Message = message }; + await LoadOrganizationsAsync(caller, model, cancellationToken); + + return ScreenResult.Ok(model); + } + + private async Task LoadOrganizationsAsync(ClaimsPrincipal caller, OrganizationsViewModel model, CancellationToken cancellationToken) + { + var userId = _users.GetUserId(caller); + var views = new List(); + + #pragma warning disable CS8602 + foreach (var organization in await _ownership.GetOrganizationsAsync(userId, cancellationToken)) + #pragma warning restore CS8602 + { + var members = await _ownership.GetMembersAsync(organization.Name, cancellationToken); + var names = new List(); + foreach (var member in members) + { + #pragma warning disable CS8604 + var user = await _users.FindByIdAsync(member.UserId); + #pragma warning restore CS8604 + if (user?.UserName != null) names.Add(new AccountOrganizationMember(user.UserName, member.IsAdmin)); + } + + views.Add(new AccountOrganization + { + Name = organization.Name, + IsAdmin = members.Any(m => m.UserId == userId && m.IsAdmin), + Members = names.OrderBy(n => n.UserName, StringComparer.OrdinalIgnoreCase).ToList(), + }); + } + + model.Organizations = views; + } + + // ----- my packages + + /// + /// The package IDs the signed-in user owns, directly or through an organization, grouped by the repositories the user may read (ownership is + /// per repository); a repository where the user owns nothing is not listed. + /// + public async Task> ShowPackagesAsync(ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var access = _services.GetRequiredService(); + var scopes = _services.GetRequiredService(); + var userId = _users.GetUserId(caller); + var groups = new List(); + + foreach (var repository in await access.ReadableAsync(caller, cancellationToken)) + { + // A scope pinned to the repository: ownership and packages are repository-scoped tables. + using var scope = scopes.CreateRepositoryScope(repository); + + // Ownership, not the package table, decides what is listed: an ID whose every + // version was deleted is still the user's, and hiding it would hide the page + // where its owners are managed. + var ids = await scope.ServiceProvider.GetRequiredService().GetOwnedPackageIdsAsync( + userId, + caller.Identity?.Name, + cancellationToken); + + if (ids == null || ids.Count == 0) continue; + + if (repository.Format == RepositoryFormat.Npm) + { + groups.Add(new RepositoryPackages(repository, await PackagesModel.SummariseNpmAsync(scope.ServiceProvider.GetRequiredService(), ids, cancellationToken))); + continue; + } + + if (repository.Format == RepositoryFormat.Maven) + { + groups.Add(new RepositoryPackages(repository, await PackagesModel.SummariseMavenAsync(scope.ServiceProvider.GetRequiredService(), ids, cancellationToken))); + continue; + } + + groups.Add(new RepositoryPackages( + repository, + PackagesModel.Summarise(ids, await PackagesModel.ListVersionsAsync( + scope.ServiceProvider.GetRequiredService(), ids, cancellationToken)))); + } + + return ScreenResult.Ok(new AccountPackagesViewModel { Groups = groups }); + } + + // ----- my access + + /// + /// The signed-in user's own effective permissions: for each repository where they hold any action, which of Read, Annotate, Deploy, Delete and + /// Manage, and the permission targets or project roles that grant them (optionally for one package ID, to see how include/exclude patterns + /// apply). Repositories where the user holds nothing are not listed, so the screen discloses nothing about private repositories. + /// + public async Task> ShowAccessAsync(ClaimsPrincipal caller, string? package, CancellationToken cancellationToken) + { + var principal = await _services.GetRequiredService().CreateAsync(caller); + if (principal == null) return ScreenResult.SignIn(); + + var model = new AccountAccessViewModel { Package = package }; + model.ModelAvailable = _services.GetRequiredService() is not NullContext; + var evaluator = _services.GetRequiredService(); + var packageId = string.IsNullOrWhiteSpace(model.Package) ? null : model.Package.Trim(); + + var rows = new List(); + foreach (var repository in await _services.GetRequiredService().ListAsync(cancellationToken)) + { + var explanation = await evaluator.ExplainAsync(principal, repository, packageId, cancellationToken); + if (explanation.Actions != AccessAction.None) rows.Add(new RepositoryAccessRow(repository, explanation)); + } + + model.Rows = rows + .OrderBy(r => r.Repository.IsDefault ? 0 : 1) + .ThenBy(r => r.Repository.Name, StringComparer.Ordinal) + .ToList(); + + if (model.ModelAvailable && principal.UserId != null) + { + model.AdministeredProjects = (await _services.GetRequiredService().ProjectRolesOfUserAsync(principal.UserId, cancellationToken)) + .Where(r => r.Role == ProjectRole.Admin) + .Select(r => r.Project) + .Distinct(StringComparer.Ordinal) + .ToList(); + } + + return ScreenResult.Ok(model); + } + + // ----- my profile + + /// The signed-in user's own profile: continues at /profiles/{name}. + public ScreenResult ShowMyProfile(ClaimsPrincipal caller) + { + #pragma warning disable CS8604 + return ScreenResult.GoTo(ScreenNext.Local($"~/profiles/{Uri.EscapeDataString(caller.Identity?.Name)}")); + #pragma warning restore CS8604 + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/AccountSettingsUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/AccountSettingsUseCase.cs new file mode 100644 index 000000000..c51716043 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/AccountSettingsUseCase.cs @@ -0,0 +1,364 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Models.Account; +using Microsoft.AspNetCore.Authentication; +using System.Linq; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Links; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// The signed-in user's account settings: change the password, change the email address, delete the account. Each form has its own method and +/// takes its fields as parameters, so one form's rules never block another's. A sensitive action asks the password again (an account without one +/// signs in again with its provider: ). Cookie sessions only: an API key never changes credentials. +/// +public sealed class AccountSettingsUseCase +{ + private readonly UserManager _users; + private readonly SignInManager _signIn; + private readonly AccountDeletionService _deletion; + private readonly IHttpContextAccessor _http; + private readonly IOptions _accounts; + private readonly IOptions _email; + private readonly IOptions _site; + private readonly IEmailSender _sender; + private readonly ExternalLogins _logins; + + /// Creates the use case. + public AccountSettingsUseCase( + UserManager users, + SignInManager signIn, + AccountDeletionService deletion, + IHttpContextAccessor http, + IOptions accounts, + IOptions email, + IOptions site, + IEmailSender sender) + : this(users, signIn, deletion, http, accounts, email, site, sender, ExternalLogins.For(users, accounts)) + { + } + + /// Creates the use case. + public AccountSettingsUseCase( + UserManager users, + SignInManager signIn, + AccountDeletionService deletion, + IHttpContextAccessor http, + IOptions accounts, + IOptions email, + IOptions site, + IEmailSender sender, + ExternalLogins logins) + { + _logins = logins ?? throw new ArgumentNullException(nameof(logins)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + _signIn = signIn ?? throw new ArgumentNullException(nameof(signIn)); + _deletion = deletion ?? throw new ArgumentNullException(nameof(deletion)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _email = email ?? throw new ArgumentNullException(nameof(email)); + _site = site ?? throw new ArgumentNullException(nameof(site)); + _sender = sender ?? throw new ArgumentNullException(nameof(sender)); + } + + private bool EmailConfigured => _email.Value.IsConfigured; + + private HttpContext Http => _http.HttpContext ?? throw new InvalidOperationException("The account settings need a request."); + + /// The settings screen. + public async Task> ShowAsync(ClaimsPrincipal caller) + { + var model = new SettingsViewModel(); + + return await LoadAsync(caller, model) ? ScreenResult.Ok(model) : ScreenResult.SignIn(); + } + + /// Change the password. + public async Task> ChangePasswordAsync(ClaimsPrincipal caller, ChangePasswordForm? form) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var model = new SettingsViewModel(); + var newPassword = form?.NewPassword; + + if (string.IsNullOrEmpty(newPassword) || newPassword != form?.ConfirmPassword) + { + model.Error = "The new passwords do not match."; + } + else + { + var hasPassword = await _users.HasPasswordAsync(user); + + // Adding the first password to an external-only account would turn a stolen + // session into a password for it, so it needs the same fresh proof. + // The current password goes through the same check as every confirmation (lockout first, a wrong one counted), so this + // form cannot be used to guess it without limit. + var result = hasPassword + ? await AccountConfirmation.IsConfirmedAsync(_users, Http, user, form!.CurrentPassword) + ? await _users.ChangePasswordAsync(user, form.CurrentPassword ?? string.Empty, newPassword) + : IdentityResult.Failed(new IdentityError { Code = "PasswordMismatch", Description = "Incorrect password." }) + : await AccountConfirmation.HasReauthenticatedRecentlyAsync(Http) + ? await _users.AddPasswordAsync(user, newPassword) + : IdentityResult.Failed(new IdentityError { Description = "Sign in again with your provider first, then set the password." }); + + if (result.Succeeded) + { + // The security stamp changed; keep this session signed in. + await _signIn.RefreshSignInAsync(user); + model.Message = "Your password has been changed."; + } + else + { + model.Error = AccountConfirmation.Describe(result); + } + } + + return await DoneAsync(caller, model); + } + + /// + /// Change the email address. The password is asked again, like for deleting the account: the address is where password resets go, so a + /// stolen session must not be able to repoint it. + /// + public async Task> ChangeEmailAsync(ClaimsPrincipal caller, ChangeEmailForm? form) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var model = new SettingsViewModel(); + var newEmail = form?.NewEmail?.Trim(); + + if (!await AccountConfirmation.IsConfirmedAsync(_users, Http, user, form?.Password)) + { + model.Error = "The confirmation is incorrect, so the email address was not changed."; + } + else if (string.IsNullOrEmpty(newEmail) || !new EmailAddressAttribute().IsValid(newEmail)) + { + model.Error = "Enter a valid email address."; + } + else if (!EmailConfigured) + { + var result = await _users.SetEmailAsync(user, newEmail); + if (result.Succeeded) + { + await _signIn.RefreshSignInAsync(user); + model.Message = "Your email address has been changed."; + } + else model.Error = AccountConfirmation.Describe(result); + } + else + { + var token = await _users.GenerateChangeEmailTokenAsync(user, newEmail); + var link = AccountLinks.ConfirmEmail(_site, user.Id, token, newEmail); + + try + { + await _sender.SendConfirmationLinkAsync(user, newEmail, link); + model.Message = "We sent a confirmation link to the new address. Your address changes when you follow it."; + } + catch (Exception) + { + model.Error = "We could not send the confirmation email. Try again later."; + } + } + + return await DoneAsync(caller, model); + } + + /// + /// Delete the account. The password is asked again, so a stolen session cannot delete it. An account without a password (external sign-in + /// only) signs in again with its provider. Success signs the user out and continues at the site root. + /// + public async Task> DeleteAsync(ClaimsPrincipal caller, PasswordConfirmationForm? form, CancellationToken cancellationToken) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var model = new SettingsViewModel(); + + if (!await AccountConfirmation.IsConfirmedAsync(_users, Http, user, form?.Password)) + { + model.Error = "The confirmation is incorrect, so the account was not deleted."; + } + else + { + var (blockers, result) = await _deletion.DeleteAsync(user, cancellationToken); + + if (blockers.Any) + { + model.Blockers = blockers; + model.Error = "The account cannot be deleted yet."; + } + else if (!result.Succeeded) + { + model.Error = AccountConfirmation.Describe(result); + } + else + { + await _signIn.SignOutAsync(); + + return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Root)); + } + } + + return await DoneAsync(caller, model); + } + + // ----- external logins (link and unlink a provider) + + /// + /// "Link " was posted: after the password check, the challenge that sends the browser to the provider (browser-only; the answer is + /// ). A provider that is not configured is . + /// + public async Task<(ExternalChallenge? Challenge, ScreenResult? Screen)> StartLinkAsync(ClaimsPrincipal caller, string? provider, string? password, string callbackUrl) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return (null, ScreenResult.SignIn()); + + var configured = _logins.Configured.FirstOrDefault(p => string.Equals(p.Id, provider, StringComparison.OrdinalIgnoreCase)); + if (configured == null) return (null, ScreenResult.NotFound()); + + var model = new SettingsViewModel(); + if (!await AccountConfirmation.IsConfirmedAsync(_users, Http, user, password)) + { + model.Error = "The confirmation is incorrect, so nothing was linked."; + + return (null, await DoneAsync(caller, model)); + } + + if ((await _logins.LinkedAsync(user)).Any(p => p.Id == configured.Id)) + { + model.Error = $"{configured.DisplayName} is already linked to this account."; + + return (null, await DoneAsync(caller, model)); + } + + // The anti-forgery value of the challenge is the user's id, so an answer started by another session is not accepted. + var properties = _signIn.ConfigureExternalAuthenticationProperties(configured.Id, callbackUrl, user.Id); + + return (new ExternalChallenge(configured.Id, properties), null); + } + + /// The provider answered a link started by : its account is linked to the signed-in user, unless another account here already has it. + public async Task> CompleteLinkAsync(ClaimsPrincipal caller) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var model = new SettingsViewModel(); + var info = await _signIn.GetExternalLoginInfoAsync(user.Id); + await Http.SignOutAsync(IdentityConstants.ExternalScheme); + + if (info == null || !_logins.Configured.Any(p => p.Id == info.LoginProvider)) + { + model.Error = "The sign-in with the provider failed, so nothing was linked."; + } + else if (await _users.FindByLoginAsync(info.LoginProvider, info.ProviderKey) is { } owner) + { + model.Error = owner.Id == user.Id + ? "That account is already linked to this one." + : "That account at the provider is already linked to another account here. Unlink it there first."; + } + else + { + var result = await _users.AddLoginAsync(user, info); + if (result.Succeeded) + { + await _signIn.RefreshSignInAsync(user); + model.Message = $"{_logins.Configured.First(p => p.Id == info.LoginProvider).DisplayName} is linked to your account."; + } + else model.Error = AccountConfirmation.Describe(result); + } + + return await DoneAsync(caller, model); + } + + /// + /// Unlinks the account login at the form's provider after the password check. Refused when it is the only way to sign in (no password and + /// no other login): the account would be lost. + /// + public async Task> UnlinkAsync(ClaimsPrincipal caller, UnlinkExternalForm? form) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var configured = _logins.Configured.FirstOrDefault(p => string.Equals(p.Id, form?.Provider, StringComparison.OrdinalIgnoreCase)); + if (configured == null) return ScreenResult.NotFound(); + + var model = new SettingsViewModel(); + var logins = await _users.GetLoginsAsync(user); + var mine = logins.Where(l => l.LoginProvider == configured.Id).ToList(); + + if (!await AccountConfirmation.IsConfirmedAsync(_users, Http, user, form?.Password)) + { + model.Error = "The confirmation is incorrect, so nothing was unlinked."; + } + else if (mine.Count == 0) + { + model.Error = $"{configured.DisplayName} is not linked to this account."; + } + else if (!await _users.HasPasswordAsync(user) + && !logins.Any(l => l.LoginProvider != configured.Id && _logins.Configured.Any(p => p.Id == l.LoginProvider))) + { + // Logins at providers that are no longer configured cannot sign in: they do not count as another way in. + model.Error = "That is the only way to sign in to this account. Set a password first."; + } + else + { + foreach (var login in mine) + { + var result = await _users.RemoveLoginAsync(user, login.LoginProvider, login.ProviderKey); + if (!result.Succeeded) + { + model.Error = AccountConfirmation.Describe(result); + break; + } + } + + if (model.Error == null) + { + // Keep this session signed in whether or not the store touched the security stamp. + await _signIn.RefreshSignInAsync(user); + model.Message = $"{configured.DisplayName} was unlinked from your account."; + } + } + + return await DoneAsync(caller, model); + } + + // The screen again with what the action said: a refusal is Invalid (the model carries the message the page prints), anything else Ok. + private async Task> DoneAsync(ClaimsPrincipal caller, SettingsViewModel model) + { + await LoadAsync(caller, model); + + return model.Error == null ? ScreenResult.Ok(model) : ScreenResult.Invalid(model, model.Error); + } + + private async Task LoadAsync(ClaimsPrincipal caller, SettingsViewModel model) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return false; + + model.Email = user.Email; + model.EmailConfirmed = user.EmailConfirmed; + model.HasPassword = await _users.HasPasswordAsync(user); + model.Reauthenticated = !model.HasPassword && await AccountConfirmation.HasReauthenticatedRecentlyAsync(Http); + model.CanReauthenticate = await _logins.CanReauthenticateAsync(user); + model.ExternalLogins = await _logins.StatusAsync(user); + model.CanSendEmail = EmailConfigured; + + return true; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/AccountSupportText.cs b/src/BaGet.Identity.Application/UseCases/Account/AccountSupportText.cs new file mode 100644 index 000000000..fb58d7d27 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/AccountSupportText.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// The identity failure text shared by the administration use cases. +internal static class AccountSupportText +{ + /// The messages of an identity failure as one sentence. + public static string Describe(IdentityResult result) + => string.Join(" ", System.Linq.Enumerable.Select(result.Errors, e => e.Description)); +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/ApiKeysUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/ApiKeysUseCase.cs new file mode 100644 index 000000000..36c540a0c --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ApiKeysUseCase.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// The signed-in user's API keys: list, create, revoke. A key's value exists only in the answer to its creation (createdKey); the listing +/// never carries a key or its hash. Cookie sessions only: a key never mints another. +/// +public sealed class ApiKeysUseCase +{ + private readonly ApiKeyService _keys; + private readonly UserManager _users; + private readonly AdministratorService _administrators; + private readonly SystemTime _time; + private readonly IServiceProvider _services; + + /// Creates the use case. + public ApiKeysUseCase( + ApiKeyService keys, + UserManager users, + AdministratorService administrators, + SystemTime time, + IServiceProvider services) + { + _keys = keys ?? throw new ArgumentNullException(nameof(keys)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + _administrators = administrators ?? throw new ArgumentNullException(nameof(administrators)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + /// The user's keys and the new-key form. + public async Task> ShowAsync(ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var model = new ApiKeysViewModel(); + await LoadAsync(caller, model, cancellationToken); + + return ScreenResult.Ok(model); + } + + /// The new-key form was posted. + /// The signed-in user. + /// The form. + /// Errors the request binding found before this ran (a value that is not a number): the key is not created while there are any. + /// Cancellation. + public async Task> CreateAsync( + ClaimsPrincipal caller, + ApiKeyForm? form, + IReadOnlyDictionary? bindingErrors, + CancellationToken cancellationToken) + { + var model = new ApiKeysViewModel(); + if (form != null) + { + model.Description = form.Description; + model.Scopes = form.Scopes ?? new List(); + model.PackageGlobPattern = form.PackageGlobPattern; + model.ExpiresInDays = form.ExpiresInDays; + model.RepositoryKeys = form.RepositoryKeys ?? new List(); + } + + var errors = ScreenValidator.Validate(form); + if (bindingErrors != null) + { + foreach (var (field, messages) in bindingErrors) + { + foreach (var message in messages) + { + if (!errors.TryGetValue(field, out var existing) || !existing.Contains(message)) ScreenValidator.With(errors, field, message); + } + } + } + + if (form != null && model.Scopes.Count == 0) + { + ScreenValidator.With(errors, nameof(ApiKeyForm.Scopes), "Choose at least one scope."); + } + + // Over /api/ui a stolen token must not mint long-lived keys: asks the password again (the screen's own form is unchanged). + var http = _services.GetService()?.HttpContext; + if (errors.Count == 0 && http != null && AccountConfirmation.IsHttpSession(http)) + { + var account = await _users.GetUserAsync(caller); + if (account == null || !await AccountConfirmation.IsConfirmedAsync(_users, http, account, form?.Password)) + { + ScreenValidator.With(errors, nameof(ApiKeyForm.Password), "Confirm your password to create an API key."); + } + } + + if (errors.Count == 0) + { + // Only a repository the user can read may be chosen: a key limited to one nobody can see is a probe. + await LoadRepositoriesAsync(caller, model, cancellationToken); + if (model.RepositoryKeys.Except(model.Repositories.Select(r => r.Key)).Any()) + { + ScreenValidator.With(errors, nameof(ApiKeyForm.RepositoryKeys), "Choose only repositories from the list."); + } + } + + if (errors.Count == 0) + { + var now = _time.UtcNow; + + try + { + model.CreatedKey = await _keys.CreateAsync( + _users.GetUserId(caller), + model.Description, + model.Scopes, + model.PackageGlobPattern, + model.ExpiresInDays.HasValue ? now.AddDays(model.ExpiresInDays.Value) : (DateTime?)null, + model.RepositoryKeys, + cancellationToken); + } + catch (ArgumentException e) + { + ScreenValidator.With(errors, nameof(ApiKeyForm.Scopes), e.Message); + } + } + + await LoadAsync(caller, model, cancellationToken); + + return errors.Count == 0 ? ScreenResult.Ok(model) : ScreenResult.Invalid(model, errors); + } + + /// A key was revoked. Continues at the keys screen. + public async Task> RevokeAsync(ClaimsPrincipal caller, int key, CancellationToken cancellationToken) + { + await _keys.RevokeAsync(_users.GetUserId(caller), key, cancellationToken); + + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AccountApiKeys)); + } + + private static IReadOnlyList ScopesFor(bool administrator) => administrator ? ApiKeyScopes.Assignable : ApiKeyScopes.All; + + private async Task LoadAsync(ClaimsPrincipal caller, ApiKeysViewModel model, CancellationToken cancellationToken) + { + model.AllScopes = ScopesFor(await _administrators.IsAdministratorAsync(caller, cancellationToken)); + var keys = await _keys.ListAsync(_users.GetUserId(caller), cancellationToken); + model.Keys = keys.Select(AccountApiKey.From).ToList(); + model.KeyRepositories = await _keys.RepositoryNamesAsync(keys, cancellationToken); + await LoadRepositoriesAsync(caller, model, cancellationToken); + } + + private async Task LoadRepositoriesAsync(ClaimsPrincipal caller, ApiKeysViewModel model, CancellationToken cancellationToken) + { + var access = _services.GetService(); + model.Repositories = access == null || !access.SupportsMultipleRepositories + ? Array.Empty() + : await access.ReadableAsync(caller, cancellationToken); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/ChangeEmailForm.cs b/src/BaGet.Identity.Application/UseCases/Account/ChangeEmailForm.cs new file mode 100644 index 000000000..6517cb839 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ChangeEmailForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.UseCases.Account; + +/// What the change-email form posts. +public sealed class ChangeEmailForm +{ + /// The new address. + public string? NewEmail { get; set; } + + /// The password, asked again (an account without one needs a fresh provider sign-in instead). + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/ChangePasswordForm.cs b/src/BaGet.Identity.Application/UseCases/Account/ChangePasswordForm.cs new file mode 100644 index 000000000..05c252369 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ChangePasswordForm.cs @@ -0,0 +1,14 @@ +namespace BaGet.Identity.Application.UseCases.Account; + +/// What the change-password form posts (the body of POST /api/ui/account/settings/change-password). +public sealed class ChangePasswordForm +{ + /// The current password (an account without one sets its first after signing in again with its provider). + public string? CurrentPassword { get; set; } + + /// The new password. + public string? NewPassword { get; set; } + + /// The new password again. + public string? ConfirmPassword { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/ConfirmationState.cs b/src/BaGet.Identity.Application/UseCases/Account/ConfirmationState.cs new file mode 100644 index 000000000..404ef7510 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ConfirmationState.cs @@ -0,0 +1,7 @@ +namespace BaGet.Identity.Application.UseCases.Account; + +/// What a password-confirmed screen shows about how the caller can confirm. +/// The caller has a password to type. +/// For an account without a password: it signed in again with its provider a moment ago. +/// An external provider is available to sign in again with. +public readonly record struct ConfirmationState(bool HasPassword, bool Reauthenticated, bool CanReauthenticate); diff --git a/src/BaGet.Identity.Application/UseCases/Account/CreateOrganizationForm.cs b/src/BaGet.Identity.Application/UseCases/Account/CreateOrganizationForm.cs new file mode 100644 index 000000000..8f164caff --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/CreateOrganizationForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.UseCases.Account; + +/// What the "create an organization" form posts. +public sealed class CreateOrganizationForm +{ + /// The organization's name. + public string? Name { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/ExternalChallenge.cs b/src/BaGet.Identity.Application/UseCases/Account/ExternalChallenge.cs new file mode 100644 index 000000000..bbcd4cc98 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ExternalChallenge.cs @@ -0,0 +1,8 @@ +using Microsoft.AspNetCore.Authentication; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// Where a browser is sent to talk to the external provider. +/// The authentication scheme to challenge. +/// The challenge's properties (callback address, anti-forgery value, prompt). +public sealed record ExternalChallenge(string Scheme, AuthenticationProperties Properties); diff --git a/src/BaGet.Identity.Application/UseCases/Account/ExternalSessionUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/ExternalSessionUseCase.cs new file mode 100644 index 000000000..b306287c7 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ExternalSessionUseCase.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Models.Session; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Security; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// The external provider (OpenID Connect) sign-in for a client that holds tokens: the same rules as the sign-in page ( +/// decides, creating the account the first time, honouring lockout, approval and the confirmed email), but no cookie is set and the answer is an +/// exchange token (60 seconds) instead of the session tokens, because the answer travels in the URL fragment: the client exchanges it at +/// POST /api/ui/session/exchange. Browser-only, like the page: the provider redirects the browser, so the controller sends the challenge and +/// returns to an address allowed. Only the external cookie is cleaned up; the browser's own session is not touched. +/// +public sealed class ExternalSessionUseCase +{ + private readonly ExternalSignInUseCase _external; + private readonly SessionUseCase _sessions; + private readonly IHttpContextAccessor _http; + private readonly SystemTime _time; + + /// Creates the use case. + public ExternalSessionUseCase(ExternalSignInUseCase external, SessionUseCase sessions, IHttpContextAccessor http, SystemTime time) + { + _external = external ?? throw new ArgumentNullException(nameof(external)); + _sessions = sessions ?? throw new ArgumentNullException(nameof(sessions)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + /// The challenge to send to the only configured provider, or null when there is not exactly one. + /// The address of the callback of this API. + public ExternalChallenge? Start(string callbackUrl) => _external.StartSignIn(null, callbackUrl); + + /// The challenge to send to the provider, or null when the provider id is unknown. + /// The provider id. + /// The address of the callback of this API. + public ExternalChallenge? Start(string provider, string callbackUrl) => string.IsNullOrEmpty(provider) ? null : _external.StartSignIn(provider, callbackUrl); + + /// The provider answered: an exchange token, a notice (account created, not usable yet), or the reason it was refused. + public async Task> CompleteAsync(CancellationToken cancellationToken) + { + try + { + var login = await _external.CompleteForSessionAsync(cancellationToken); + + switch (login.Status) + { + case ScreenStatus.Invalid: + return ScreenResult.Invalid(new SessionModel(), login.Errors); + + case ScreenStatus.Ok: + // The account was created but cannot sign in yet (approval, confirmation link): there is no session to issue. + return ScreenResult.Ok(new SessionModel { Notice = login.Model?.Notice }); + } + + var user = _external.SignedInUser; + if (user == null) return ScreenResult.SignIn("The external sign-in failed."); + + return ScreenResult.Ok(await _sessions.IssueExchangeAsync(user, _time.UtcNow)); + } + finally + { + // Only the external cookie: the browser may hold an unrelated session of the page. + var http = _http.HttpContext; + if (http != null) await http.SignOutAsync(IdentityConstants.ExternalScheme); + } + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/ExternalSignInUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/ExternalSignInUseCase.cs new file mode 100644 index 000000000..e724d54d6 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ExternalSignInUseCase.cs @@ -0,0 +1,460 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Links; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// Signing in, and proving presence again, through the external (OpenID Connect) provider. These steps are browser-only: the provider +/// redirects the browser and answers into a cookie, so they have no JSON twin; the view controller sends the challenge and handles the callback. +/// The rules are the same ones the pages applied: the provider is the gate for a new account (registration need not be open), only a provider-verified +/// address is confirmed, an unconfirmed or pending account never gets a second account made for it, and a re-authentication must be this account's own +/// login with a fresh auth_time. +/// +public sealed class ExternalSignInUseCase +{ + /// The name of the OpenID Connect scheme AddBaGetAccounts registers. + public const string OpenIdConnectScheme = "oidc"; + + /// The id token claim that tells when the user last authenticated at the provider. + public const string AuthTimeClaim = "auth_time"; + + /// Allowed difference between the provider's clock and ours. + public static readonly TimeSpan ClockSkew = TimeSpan.FromMinutes(1); + + private readonly UserManager _users; + private readonly SignInManager _signIn; + private readonly PackageOwnershipService _ownership; + private readonly IEmailSender _sender; + private readonly IHttpContextAccessor _http; + private readonly IOptions _accounts; + private readonly IOptions _email; + private readonly IOptions _site; + private readonly SystemTime _time; + private readonly SignInUseCase _signInScreens; + private readonly OpenIdConnectProviderSet _providers; + private readonly ExternalProviderMapping? _mapping; + private readonly ExternalLogins _logins; + private readonly ILogger _logger; + + /// Creates the use case. + public ExternalSignInUseCase( + UserManager users, + SignInManager signIn, + PackageOwnershipService ownership, + IEmailSender sender, + IHttpContextAccessor http, + IOptions accounts, + IOptions email, + IOptions site, + SystemTime time, + SignInUseCase signInScreens, + ILogger logger) + : this(users, signIn, ownership, sender, http, accounts, email, site, time, signInScreens, logger, OpenIdConnectProviders.Resolve(accounts.Value), ExternalLogins.For(users, accounts), null) + { + } + + /// Creates the use case; a mapping applies a provider's role and group mapping (null applies none). + public ExternalSignInUseCase( + UserManager users, + SignInManager signIn, + PackageOwnershipService ownership, + IEmailSender sender, + IHttpContextAccessor http, + IOptions accounts, + IOptions email, + IOptions site, + SystemTime time, + SignInUseCase signInScreens, + ILogger logger, + OpenIdConnectProviderSet providers, + ExternalLogins logins, + ExternalProviderMapping? mapping = null) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _signIn = signIn ?? throw new ArgumentNullException(nameof(signIn)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _sender = sender ?? throw new ArgumentNullException(nameof(sender)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _email = email ?? throw new ArgumentNullException(nameof(email)); + _site = site ?? throw new ArgumentNullException(nameof(site)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _signInScreens = signInScreens ?? throw new ArgumentNullException(nameof(signInScreens)); + _providers = providers ?? throw new ArgumentNullException(nameof(providers)); + _mapping = mapping; + _logins = logins ?? throw new ArgumentNullException(nameof(logins)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private bool EmailConfigured => _email.Value.IsConfigured; + + private HttpContext Http => _http.HttpContext ?? throw new InvalidOperationException("External sign-in needs a request."); + + // ----- sign in with the provider + + /// The "sign in with the provider" button of a server with one provider: the challenge to send, or null when there is not exactly one provider (404). + /// The address of the callback handler of the sign-in screen (built by the view with its URL helper). + public ExternalChallenge? StartSignIn(string callbackUrl) => StartSignIn(null, callbackUrl); + + /// + /// The "sign in with the provider" button: the challenge to send, or null when the provider is unknown (404). A request that names no provider + /// means the only configured one (a form of before several were supported); with several, a provider must be named. + /// + /// The provider id, or null. + /// The address of the callback handler of the sign-in screen (built by the view with its URL helper). + public ExternalChallenge? StartSignIn(string? provider, string callbackUrl) + { + var chosen = string.IsNullOrEmpty(provider) ? (_providers.All.Count == 1 ? _providers.All[0] : null) : _providers.Find(provider); + if (chosen == null) return null; + + var properties = _signIn.ConfigureExternalAuthenticationProperties(chosen.Id, callbackUrl); + + return new ExternalChallenge(chosen.Id, properties); + } + + /// + /// The provider has signed the user in. The first time, an account is created for them: the provider is the gate, so this does not + /// depend on AllowRegistration. + /// + public Task> CompleteSignInAsync(string? returnUrl, CancellationToken cancellationToken) + => CompleteCoreAsync(returnUrl, cookie: true, cancellationToken); + + /// The account the last signed in (or created), or null. + internal BaGetUser? SignedInUser { get; private set; } + + /// + /// The same decision as for a client that holds tokens: no cookie is set, so an unrelated cookie session of the browser + /// is left alone. A success is with the account in ; the second factor is the session use case's. + /// + internal Task> CompleteForSessionAsync(CancellationToken cancellationToken) + => CompleteCoreAsync(null, cookie: false, cancellationToken); + + // What ExternalLoginSignInAsync decides, without writing a cookie. + private async Task CheckExternalAsync(ExternalLoginInfo info) + { + var existing = await _users.FindByLoginAsync(info.LoginProvider, info.ProviderKey); + if (existing == null) return SignInResult.Failed; + if (await _users.IsLockedOutAsync(existing)) return SignInResult.LockedOut; + if (!await _signIn.CanSignInAsync(existing)) return SignInResult.NotAllowed; + + SignedInUser = existing; + + return SignInResult.Success; + } + + private async Task> CompleteCoreAsync(string? returnUrl, bool cookie, CancellationToken cancellationToken) + { + var model = _signInScreens.Describe(new LoginViewModel { ReturnUrl = returnUrl }); + SignedInUser = null; + + var info = await _signIn.GetExternalLoginInfoAsync(); + if (info == null) return Refuse(model, "The external sign-in failed."); + + // The provider that answered: its claim names and its role/group mapping. An answer of a handler that is no longer configured has + // none of either (the defaults apply). + var provider = _providers.Find(info.LoginProvider); + var options = provider?.Options ?? new OpenIdConnectProviderOptions(); + + var known = await _users.FindByLoginAsync(info.LoginProvider, info.ProviderKey); + if (known != null && provider != null && !await _users.IsLockedOutAsync(known) && await _signIn.CanSignInAsync(known)) + { + // The provider vouches for this sign-in, so its administrator and group claims apply before the session is created. + await ApplyMappingAsync(provider, known, info.Principal, cancellationToken); + } + + var result = cookie + ? await _signIn.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false) + : await CheckExternalAsync(info); + if (result.Succeeded) + { + return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Target(returnUrl))); + } + + if (result.RequiresTwoFactor) + { + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AccountLoginWith2fa, new Dictionary { ["ReturnUrl"] = returnUrl })); + } + + if (result.IsLockedOut) return Refuse(model, SignInUseCase.LockedMessage); + + if (result.IsNotAllowed) + { + // This provider login already belongs to an account, which cannot sign in yet + // (its email is unconfirmed). Never make another account for it. + var existing = await _users.FindByLoginAsync(info.LoginProvider, info.ProviderKey); + if (existing is { PendingApproval: true }) return Refuse(model, SignInUseCase.PendingMessage); + + if (existing != null && await TrySendConfirmationAsync(existing)) + { + model.Notice = "Confirm your email address before signing in. We sent you a new confirmation link."; + + return ScreenResult.Ok(model); + } + + return Refuse(model, SignInUseCase.UnconfirmedMessage); + } + + var email = ExternalClaims.First(info.Principal, OpenIdConnectProviders.EmailClaim(options)); + if (EmailConfigured && string.IsNullOrWhiteSpace(email)) + { + return Refuse(model, "The external account has no email address, which this server needs to confirm accounts."); + } + + var name = await ChooseUserNameAsync(info.Principal, options, cancellationToken); + if (name == null) return Refuse(model, "The external account has no usable name."); + + var user = new BaGetUser + { + UserName = name, + Email = email, + + // Only an address the provider vouches for is confirmed; any other must be + // proven by following a link, like one typed into the registration form. + EmailConfirmed = !string.IsNullOrWhiteSpace(email) && ProviderVerifiedEmail(info.Principal, options), + Created = _time.UtcNow, + PendingApproval = _accounts.Value.RequireApproval, + }; + + var created = await _users.CreateAsync(user); + if (created.Succeeded) + { + created = await _users.AddLoginAsync(user, info); + } + + if (!created.Succeeded) + { + // Do not leave an account behind that has no login to reach it. + if (user.Id != null && await _users.FindByIdAsync(user.Id) != null) await _users.DeleteAsync(user); + + return Refuse(model, string.Join(" ", created.Errors.Select(e => e.Description))); + } + + if (provider != null) await ApplyMappingAsync(provider, user, info.Principal, cancellationToken); + + if (user.PendingApproval) + { + // Approval does not replace the address check: send the link now, so approving is the last step. + if (EmailConfigured && !user.EmailConfirmed) await TrySendConfirmationAsync(user); + + model.Notice = "Your account was created. An administrator must enable it before you can sign in."; + + return ScreenResult.Ok(model); + } + + if (EmailConfigured && !user.EmailConfirmed) + { + model.Notice = await TrySendConfirmationAsync(user) + ? "Your account was created. Confirm your email address with the link we sent you, then sign in again." + : "Your account was created, but we could not send the confirmation email. Use \"Forgot password\" to get a link later."; + + return ScreenResult.Ok(model); + } + + SignedInUser = user; + if (cookie) await _signIn.SignInAsync(user, isPersistent: false); + + return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Target(returnUrl))); + } + + private Task ApplyMappingAsync(OpenIdConnectProvider provider, BaGetUser user, ClaimsPrincipal principal, CancellationToken cancellationToken) + => _mapping == null ? Task.CompletedTask : _mapping.ApplyAsync(provider, user, principal, cancellationToken); + + private static ScreenResult Refuse(LoginViewModel model, string message) + { + model.Error = message; + + return ScreenResult.Invalid(model, message); + } + + private static bool ProviderVerifiedEmail(ClaimsPrincipal principal, OpenIdConnectProviderOptions options) + => bool.TryParse(ExternalClaims.First(principal, OpenIdConnectProviders.EmailVerifiedClaim(options)), out var verified) && verified; + + private async Task TrySendConfirmationAsync(BaGetUser user) + { + if (!EmailConfigured || string.IsNullOrEmpty(user.Email) || user.EmailConfirmed) return false; + + try + { + var token = await _users.GenerateEmailConfirmationTokenAsync(user); + var link = AccountLinks.ConfirmEmail(_site, user.Id, token); + await _sender.SendConfirmationLinkAsync(user, user.Email, link); + + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Could not send a confirmation link."); + + return false; + } + } + + /// + /// The provider's preferred user name, else the email's local part, made unique across users and organizations by a numeric suffix. + /// + private async Task ChooseUserNameAsync(ClaimsPrincipal principal, OpenIdConnectProviderOptions options, CancellationToken cancellationToken) + { + var candidate = ExternalClaims.First(principal, OpenIdConnectProviders.UserNameClaim(options)) + ?? ExternalClaims.First(principal, OpenIdConnectProviders.EmailClaim(options))?.Split('@')[0] + ?? principal.FindFirstValue(ClaimTypes.Name); + + if (string.IsNullOrWhiteSpace(candidate)) return null; + + var allowed = _users.Options.User.AllowedUserNameCharacters; + candidate = new string(candidate.Where(c => allowed.Contains(c)).ToArray()); + if (candidate.Length == 0) return null; + + var name = candidate; + for (var suffix = 2; await _ownership.AccountExistsAsync(name, cancellationToken); suffix++) + { + name = candidate + suffix; + } + + return name; + } + + // ----- proof of presence for an account without a password + + /// The "sign in again" button for the only linked provider (or the screen to pick one); see the overload with a provider. + public Task<(ExternalChallenge? Challenge, ScreenResult? Screen)> StartReauthenticationAsync(ClaimsPrincipal caller, string callbackUrl, string? returnUrl) + => StartReauthenticationAsync(caller, callbackUrl, returnUrl, null); + + /// + /// The "sign in again" button: a fresh sign-in with a provider the account has linked (it is asked to prompt for credentials again, whatever + /// session it has). With several linked providers and none named, the answer is the screen that lets the user pick (no challenge). The time is kept + /// in the sign-in cookie's properties and checked by for + /// . + /// + /// The signed-in user. + /// The address of the callback handler of the screen. + /// Where to continue after the provider answered. + /// The provider to use, or null to take the only linked one (or offer the choice). + /// The challenge to send, or a screen (sign in, the refusal, or the choice of provider). + public async Task<(ExternalChallenge? Challenge, ScreenResult? Screen)> StartReauthenticationAsync(ClaimsPrincipal caller, string callbackUrl, string? returnUrl, string? provider) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return (null, ScreenResult.SignIn()); + + var linked = await _logins.LinkedAsync(user); + if (linked.Count == 0) + { + return (null, Refuse(new ReauthenticateViewModel { ReturnUrl = returnUrl }, "There is no external provider linked to this account to sign in with.")); + } + + ExternalProviderInfo? chosen; + if (string.IsNullOrEmpty(provider)) + { + if (linked.Count > 1) + { + // Several providers are linked: the user picks the one to prove it with. + return (null, ScreenResult.Ok(new ReauthenticateViewModel { ReturnUrl = returnUrl, Providers = linked.ToList() })); + } + + chosen = linked[0]; + } + else + { + chosen = linked.FirstOrDefault(p => string.Equals(p.Id, provider, StringComparison.OrdinalIgnoreCase)); + if (chosen == null) + { + return (null, Refuse(new ReauthenticateViewModel { ReturnUrl = returnUrl, Providers = linked.Count > 1 ? linked.ToList() : null }, "That provider is not linked to this account.")); + } + } + + var properties = _signIn.ConfigureExternalAuthenticationProperties(chosen.Id, callbackUrl, user.Id); + + // Ask the provider to authenticate again whatever session it holds. + properties.SetParameter(OpenIdConnectChallengeProperties.PromptKey, "login"); + properties.SetParameter(OpenIdConnectChallengeProperties.MaxAgeKey, TimeSpan.Zero); + + return (new ExternalChallenge(chosen.Id, properties), null); + } + + /// True when (seconds since the epoch) is present and within the window. + internal static bool IsFresh(string? authTime, DateTime now) + { + if (!long.TryParse(authTime, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var seconds) + || seconds < 0 || seconds > 253402300799L) + { + return false; + } + + var age = now - DateTimeOffset.FromUnixTimeSeconds(seconds).UtcDateTime; + + return age >= -ClockSkew && age <= AccountConfirmation.ReauthenticationWindow; + } + + /// The provider answered. + public async Task> CompleteReauthenticationAsync(ClaimsPrincipal caller, string? returnUrl) + { + var model = new ReauthenticateViewModel { ReturnUrl = returnUrl }; + var httpContext = Http; + + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + // The anti-forgery value is the signed-in user's id, so an answer started by + // someone else's session is not accepted. + var info = await _signIn.GetExternalLoginInfoAsync(user.Id); + await httpContext.SignOutAsync(IdentityConstants.ExternalScheme); + + // It must be this account's own login, not any account at the provider. + var owner = info == null ? null : await _users.FindByLoginAsync(info.LoginProvider, info.ProviderKey); + if (owner == null || owner.Id != user.Id) + { + return Refuse(model, "The sign-in did not match this account."); + } + + // The provider may ignore prompt=login / max_age (the handler does not enforce max_age), + // so the id_token's own auth_time (required by OIDC Core when max_age is sent) must show + // a sign-in within the window. + var now = _time.UtcNow; + if (!IsFresh(info?.Principal?.FindFirst(AuthTimeClaim)?.Value, now)) + { + return Refuse(model, "The provider did not confirm a fresh sign-in. Sign in again and enter your credentials when asked."); + } + + var authentication = await httpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme); + var properties = authentication.Properties ?? new AuthenticationProperties(); + properties.Items[AccountConfirmation.ReauthenticatedItem] = now.Ticks.ToString(); + + // What RefreshSignInAsync keeps, plus the new property; the stamp is unchanged. + var kept = new[] { ClaimTypes.AuthenticationMethod, "amr" } + .Select(type => authentication.Principal?.FindFirst(type)) + .Where(claim => claim != null) + .ToList(); + #pragma warning disable CS8620 + await _signIn.SignInWithClaimsAsync(user, properties, kept); + #pragma warning restore CS8620 + + return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.AppRelative(LocalUrls.Target(returnUrl)))); + } + + private static ScreenResult Refuse(ReauthenticateViewModel model, string message) + { + model.Error = message; + + return ScreenResult.Invalid(model, message); + } + + /// The "confirm it is you" screen. + public static ScreenResult ShowReauthenticate(string? returnUrl) + => ScreenResult.Ok(new ReauthenticateViewModel { ReturnUrl = returnUrl }); +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/IReauthenticationState.cs b/src/BaGet.Identity.Application/UseCases/Account/IReauthenticationState.cs new file mode 100644 index 000000000..30a64ff1a --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/IReauthenticationState.cs @@ -0,0 +1,15 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// Whether the session re-authenticated with the external provider a moment ago (the proof of presence a sensitive action asks of an +/// account that has no password). It reads the sign-in cookie, so the host implements it (BaGet.Identity); a use case only asks. +/// Without a session (an API key, an anonymous caller) the answer is false. +/// +public interface IReauthenticationState +{ + /// Whether the session re-authenticated within the last few minutes. + Task HasReauthenticatedRecentlyAsync(CancellationToken cancellationToken); +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/PasswordConfirmationForm.cs b/src/BaGet.Identity.Application/UseCases/Account/PasswordConfirmationForm.cs new file mode 100644 index 000000000..7c104f418 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/PasswordConfirmationForm.cs @@ -0,0 +1,8 @@ +namespace BaGet.Identity.Application.UseCases.Account; + +/// What a form that only re-asks the password posts (delete the account, turn two-factor off, reset the authenticator). +public sealed class PasswordConfirmationForm +{ + /// The password, asked again. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/ProfileUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/ProfileUseCase.cs new file mode 100644 index 000000000..cd993547c --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/ProfileUseCase.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// A user's or an organization's public page (/profiles/{name}, and under /r/{repo}/ too): the packages it owns. It reveals only +/// what the page always showed (names, owned package IDs with their download counts, an avatar address), so an API key may read it as well as a session. +/// +public sealed class ProfileUseCase +{ + private readonly UserManager _users; + private readonly PackageOwnershipService _ownership; + private readonly IContext _context; + private readonly AvatarService _avatars; + + /// Creates the use case. + public ProfileUseCase(UserManager users, PackageOwnershipService ownership, IContext context, AvatarService avatars) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _avatars = avatars ?? throw new ArgumentNullException(nameof(avatars)); + } + + /// The profile named ; not found when neither a user nor an organization has it. + public async Task> ShowAsync(ClaimsPrincipal caller, string? name, CancellationToken cancellationToken) + { + var model = new ProfileViewModel { Name = name }; + #pragma warning disable CS8604 + var user = await _users.FindByNameAsync(model.Name); + #pragma warning restore CS8604 + + IReadOnlyList ids; + if (user != null) + { + model.Name = user.UserName; + model.IsCurrentUser = caller.Identity?.IsAuthenticated == true && _users.GetUserId(caller) == user.Id; + + // Only the packages owned in the user's own name: an organization's are on its page. + #pragma warning disable CS8602 + var lowerName = user.UserName.ToLowerInvariant(); + #pragma warning disable CS8604 + ids = await _context.PackageOwners + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == lowerName) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + } + else + { + var members = await _ownership.GetMembersAsync(model.Name, cancellationToken); + var lowerName = model.Name!.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var organization = await _context.Organizations.AsNoTracking().FirstOrDefaultAsync(o => o.Name.ToLower() == lowerName, cancellationToken); + #pragma warning restore CS8602, CS8604 + if (organization == null) return ScreenResult.NotFound(); + + model.Name = organization.Name; + model.IsOrganization = true; + + var memberIds = members.Select(m => m.UserId).ToList(); + model.Members = await _context.Users + .AsNoTracking() + .Where(u => memberIds.Contains(u.Id)) + .Select(u => u.UserName) + .OrderBy(n => n) + .ToListAsync(cancellationToken); + + #pragma warning disable CS8602, CS8604 + ids = await _context.PackageOwners + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == lowerName) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + } + + var avatars = await _avatars.GetUrlsAsync(new[] { model.Name! }, 64, cancellationToken); + #pragma warning disable CS8620 + model.AvatarUrl = avatars.GetValueOrDefault(model.Name!); + #pragma warning restore CS8620 + + #pragma warning disable CS8602 + var lowerIds = ids.Select(i => i.ToLowerInvariant()).Distinct().ToList(); + #pragma warning disable CS8604 + model.Packages = await _context.Packages + .AsNoTracking() + .Where(p => lowerIds.Contains(p.Id.ToLower())) + .GroupBy(p => p.Id) + .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) + .OrderBy(p => p.Id) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + return ScreenResult.Ok(model); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/RegistrationUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/RegistrationUseCase.cs new file mode 100644 index 000000000..ed529721c --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/RegistrationUseCase.cs @@ -0,0 +1,392 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Email; +using BaGet.Identity.Application.Links; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.RateLimiting; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// Creating an account and the mail round trips around it: registration, the confirmation link, "forgot password" and the new-password form. The +/// screen answers 404 while Accounts:AllowRegistration is off (registration only). +/// +public sealed class RegistrationUseCase +{ + private const string InvalidLink = "This link is invalid, expired or already used."; + + private readonly UserManager _users; + private readonly SignInManager _signIn; + private readonly PackageOwnershipService _ownership; + private readonly IEmailSender _sender; + private readonly IOptions _accounts; + private readonly IOptions _email; + private readonly IOptions _site; + private readonly SystemTime _time; + private readonly IServiceProvider _services; + private readonly ILogger _logger; + + /// Creates the use case. + public RegistrationUseCase( + UserManager users, + SignInManager signIn, + PackageOwnershipService ownership, + IEmailSender sender, + IOptions accounts, + IOptions email, + IOptions site, + SystemTime time, + IServiceProvider services, + ILogger logger) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _signIn = signIn ?? throw new ArgumentNullException(nameof(signIn)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _sender = sender ?? throw new ArgumentNullException(nameof(sender)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _email = email ?? throw new ArgumentNullException(nameof(email)); + _site = site ?? throw new ArgumentNullException(nameof(site)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private bool EmailConfigured => _email.Value.IsConfigured; + + // ----- registration + + /// The registration form. + public ScreenResult ShowRegister(string? returnUrl) + => _accounts.Value.AllowRegistration + ? ScreenResult.Ok(new RegisterViewModel { ReturnUrl = returnUrl, EmailRequired = EmailConfigured }) + : ScreenResult.NotFound(); + + /// The registration form was posted. + public async Task> RegisterAsync(RegisterForm? form, CancellationToken cancellationToken) + { + if (!_accounts.Value.AllowRegistration) return ScreenResult.NotFound(); + + // Never the passwords: the screen's model repeats the harmless fields only. + var model = new RegisterViewModel + { + UserName = form?.UserName, + Email = form?.Email, + ReturnUrl = form?.ReturnUrl, + EmailRequired = EmailConfigured, + }; + + var errors = ScreenValidator.Validate(form); + if (form != null && EmailConfigured && string.IsNullOrWhiteSpace(form.Email)) + { + ScreenValidator.With(errors, nameof(RegisterForm.Email), "An email address is required to confirm the account."); + } + + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + // Over /api/ui (no cookie is set for such a caller) every attempt counts against the client address (a backstop). The per-email allowance is only taken once an + // account exists (below), so a refused attempt (name taken, weak password) never blocks a retry and nobody can use up the allowance of an address they do not own. + var http = _services.GetService()?.HttpContext; + var overHttp = http != null && AccountConfirmation.IsOverHttp(http); + var client = http?.Connection.RemoteIpAddress?.ToString() ?? string.Empty; + if (overHttp && !_services.GetRequiredService().TryAcquire(client, "attempt:" + Guid.NewGuid().ToString("N"))) + { + return ScreenResult.Invalid(model, "Too many attempts. Try again in a few minutes."); + } + + // User and organization names share a namespace: either can own a package. + if (await _ownership.AccountExistsAsync(form!.UserName, cancellationToken)) + { + return ScreenResult.Invalid(model, ScreenValidator.With(new Dictionary(), nameof(RegisterForm.UserName), "That name is taken.")); + } + + var user = new BaGetUser + { + UserName = form.UserName, + Email = form.Email, + Created = _time.UtcNow, + PendingApproval = _accounts.Value.RequireApproval, + }; + + #pragma warning disable CS8604 + var result = await _users.CreateAsync(user, form.Password); + #pragma warning restore CS8604 + if (!result.Succeeded) + { + return ScreenResult.Invalid( + model, + new Dictionary { [string.Empty] = result.Errors.Select(e => e.Description).ToArray() }); + } + + if (user.PendingApproval) + { + _logger.LogWarning("{User} registered and awaits approval", user.UserName); + } + + if (EmailConfigured) + { + // Over /api/ui the address is mailed once per window (a confirmation was already sent to it a moment ago otherwise: "resend" mails another later). + if (overHttp + && !string.IsNullOrWhiteSpace(user.Email) + && !_services.GetRequiredService().TryAcquire(client, "register:" + user.Email.Trim().ToLowerInvariant())) + { + model.ConfirmationSent = true; + model.AwaitingApproval = user.PendingApproval; + + return ScreenResult.Ok(model); + } + + // Signing in needs a confirmed address, so the user is not signed in yet. + var token = await _users.GenerateEmailConfirmationTokenAsync(user); + var link = AccountLinks.ConfirmEmail(_site, user.Id, token); + + try + { + #pragma warning disable CS8604 + await _sender.SendConfirmationLinkAsync(user, user.Email, link); + #pragma warning restore CS8604 + model.ConfirmationSent = true; + model.AwaitingApproval = user.PendingApproval; + + return ScreenResult.Ok(model); + } + catch (Exception) + { + // The account exists; "Forgot password" mails a link that also confirms the address. + return ScreenResult.Invalid( + model, + "Your account was created, but we could not send the confirmation email. Use \"Forgot password\" to get a link later." + + (user.PendingApproval ? " An administrator must also enable your account before you can sign in." : string.Empty)); + } + } + + if (user.PendingApproval) + { + // Not signed in: an administrator enables the account first. + model.AwaitingApproval = true; + + return ScreenResult.Ok(model); + } + + if (overHttp) + { + // No cookie for an HTTP caller (nothing would stop a cross-site page from signing a visitor in): the new account's tokens, or nothing. + model.Session = await _services.GetRequiredService().IssueAsync(user, _time.UtcNow); + + return ScreenResult.Ok(model); + } + + await _signIn.SignInAsync(user, isPersistent: false); + + return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Target(form.ReturnUrl))); + } + + // ----- the confirmation link again + + /// + /// Mails a new confirmation link to an account whose address is not confirmed yet. Like "forgot password" it answers the same, in the same time, whether or + /// not an account matches or the mail was allowed (one per account per window, and per client address); the mail is sent off the request path. + /// + public async Task> ResendConfirmationAsync(ForgotPasswordForm? form, string? clientAddress) + { + var model = new ForgotPasswordViewModel { Identifier = form?.Identifier }; + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + var identifier = form!.Identifier?.Trim(); + + #pragma warning disable CS8604 + var byName = await _users.FindByNameAsync(identifier); + #pragma warning restore CS8604 + BaGetUser? byEmail = null; + try + { + byEmail = await _users.FindByEmailAsync(identifier); + } + catch (InvalidOperationException) + { + // Several accounts share the address: none is singled out. + } + + var user = byName ?? byEmail; + if (user != null + && !user.EmailConfirmed + && !string.IsNullOrEmpty(user.Email) + && EmailConfigured + && _services.GetRequiredService().TryAcquire(clientAddress ?? string.Empty, "resend:" + user.Id)) + { + var userId = user.Id; + _services.GetRequiredService().TryEnqueue(async services => + { + var users = services.GetRequiredService>(); + var account = await users.FindByIdAsync(userId); + if (account == null || account.EmailConfirmed || string.IsNullOrEmpty(account.Email)) return; + + var token = await users.GenerateEmailConfirmationTokenAsync(account); + var link = AccountLinks.ConfirmEmail(services.GetRequiredService>(), account.Id, token); + await services.GetRequiredService>().SendConfirmationLinkAsync(account, account.Email, link); + }); + } + + model.Sent = true; + + return ScreenResult.Ok(model); + } + + // ----- the confirmation link + + /// + /// The target of the links in confirmation emails: a new account's address, or, when is present, a change of + /// address. The link is followed with a GET, so this changes state on a safe request, as the page always did (the token is the secret). + /// + public async Task> ConfirmEmailAsync(System.Security.Claims.ClaimsPrincipal caller, string? userId, string? code, string? email) + { + var model = new ConfirmEmailViewModel(); + + var user = string.IsNullOrEmpty(userId) ? null : await _users.FindByIdAsync(userId); + var token = string.IsNullOrEmpty(code) ? null : AccountConfirmation.DecodeToken(code); + if (user == null || token == null) return ScreenResult.Ok(model); + + IdentityResult result; + if (string.IsNullOrEmpty(email)) + { + result = await _users.ConfirmEmailAsync(user, token); + } + else + { + result = await _users.ChangeEmailAsync(user, email, token); + model.EmailChanged = result.Succeeded; + } + + model.Succeeded = result.Succeeded; + model.PendingApproval = model.Succeeded && user.PendingApproval; + + // The security stamp changed with the address; keep the session of the same user. + if (model.Succeeded && caller.Identity?.IsAuthenticated == true && _users.GetUserId(caller) == user.Id) + { + await _signIn.RefreshSignInAsync(user); + } + + return ScreenResult.Ok(model); + } + + // ----- forgot password + + /// The "forgot password" form. + public ScreenResult ShowForgotPassword() => ScreenResult.Ok(new ForgotPasswordViewModel()); + + /// + /// Answers the same, in the same time, whether or not an account matches, whether or not the mail could be sent and whether or not the + /// request was rate limited, so the screen cannot be used to find out who has an account. The mail itself is sent off the request path. + /// + /// The user name or email address. + /// The caller's address, for the rate limit (empty when unknown). + public async Task> ForgotPasswordAsync(ForgotPasswordForm? form, string? clientAddress) + { + var model = new ForgotPasswordViewModel { Identifier = form?.Identifier }; + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + var identifier = form!.Identifier?.Trim(); + + // Both lookups always run, so the work done does not depend on which one matches. + #pragma warning disable CS8604 + var byName = await _users.FindByNameAsync(identifier); + #pragma warning restore CS8604 + BaGetUser? byEmail = null; + try + { + byEmail = await _users.FindByEmailAsync(identifier); + } + catch (InvalidOperationException) + { + // Several accounts share the address: none is singled out. + } + + var user = byName ?? byEmail; + + // One link template either way; the user and token are filled in later. + var template = AccountLinks.ResetPasswordTemplate(_site); + + // Only an account that would be mailed uses up an allowance, so requests for names + // that do not exist can neither fill the limiter nor crowd real accounts out of it. + // The per-account limit is the protection; the client and site limits are backstops. + if (user != null + && !string.IsNullOrEmpty(user.Email) + && _services.GetRequiredService().TryAcquire(clientAddress ?? string.Empty, user.Id)) + { + PasswordResetLinkSender.TryEnqueue(_services, user.Id, template); + } + + model.Sent = true; + + return ScreenResult.Ok(model); + } + + // ----- the new-password form + + /// The link of a reset email was followed. + public ScreenResult ShowResetPassword(string? userId, string? code) + { + var model = new ResetPasswordViewModel { UserId = userId, Code = code }; + if (!model.LinkIsUsable) model.Error = "This link is invalid."; + + return ScreenResult.Ok(model); + } + + /// The new password was posted. Success continues at the sign-in screen. + public async Task> ResetPasswordAsync(ResetPasswordForm? form) + { + var model = new ResetPasswordViewModel { UserId = form?.UserId, Code = form?.Code }; + + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + #pragma warning disable CS8604 + var user = form!.LinkIsUsable ? await _users.FindByIdAsync(form.UserId) : null; + #pragma warning restore CS8604 + var token = form.LinkIsUsable ? AccountConfirmation.DecodeToken(form.Code) : null; + if (user == null || token == null) + { + return Refuse(model, InvalidLink); + } + + #pragma warning disable CS8604 + var result = await _users.ResetPasswordAsync(user, token, form.Password); + #pragma warning restore CS8604 + if (!result.Succeeded) + { + return Refuse( + model, + result.Errors.Any(e => e.Code == nameof(IdentityErrorDescriber.InvalidToken)) + ? InvalidLink + : AccountConfirmation.Describe(result)); + } + + // The link went to this address and was followed, which confirms it. + if (!user.EmailConfirmed && !string.IsNullOrEmpty(user.Email)) + { + await _users.ConfirmEmailAsync(user, await _users.GenerateEmailConfirmationTokenAsync(user)); + } + + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AccountLogin)); + } + + private static ScreenResult Refuse(ResetPasswordViewModel model, string message) + { + model.Error = message; + + return ScreenResult.Invalid(model, message); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/SessionUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/SessionUseCase.cs new file mode 100644 index 000000000..d3158217f --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/SessionUseCase.cs @@ -0,0 +1,287 @@ +using System; +using System.Security.Claims; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Models.Session; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Services.Sessions; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// Interactive sessions for a client that holds tokens instead of a cookie (a single-page application on any origin): sign in with the password +/// (and the second factor), refresh, sign out. The rules are the sign-in page's: lockout is honoured first, a wrong password is counted, an account +/// awaiting approval or with an unconfirmed email answers only to the right password, a wrong second-factor code is counted too. Tokens are +/// 's; none of this touches the cookie. +/// +public sealed class SessionUseCase +{ + private const string BadCredentials = "The user name or password is incorrect."; + private const string BadTicket = "The sign-in has expired or is not valid: sign in again."; + private const string BadExchange = "The exchange token has expired or is not valid: sign in again."; + private const string BadRefresh = "The refresh token has expired or is not valid: sign in again."; + + private readonly SignInManager _signIn; + private readonly UserManager _users; + private readonly SessionTokenService _tokens; + private readonly SessionAuthenticator _authenticator; + private readonly SystemTime _time; + private readonly MaintenanceGate _gate; + private readonly ExchangeTokenLedger _ledger; + + /// Creates the use case. + public SessionUseCase( + SignInManager signIn, + UserManager users, + SessionTokenService tokens, + SessionAuthenticator authenticator, + SystemTime time, + MaintenanceGate gate, + ExchangeTokenLedger ledger) + { + _ledger = ledger ?? throw new ArgumentNullException(nameof(ledger)); + _signIn = signIn ?? throw new ArgumentNullException(nameof(signIn)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + _tokens = tokens ?? throw new ArgumentNullException(nameof(tokens)); + _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _gate = gate ?? throw new ArgumentNullException(nameof(gate)); + } + + /// The password step of a sign-in: tokens, or the ticket for the second factor when the account has one. + public Task> SignInAsync(SessionSignInForm? form) => PasswordStepAsync(form, cookie: false); + + /// + /// Signs in with the cookie (a same-origin client): the same rules as and the second-factor steps, but the answer carries no + /// tokens (userName only) and the session cookie is set. The password step takes userName and password; when the account has two-factor the answer is the + /// ticket, and the second step takes ticket with code or recoveryCode. + /// + public async Task> CookieSignInAsync(SessionCookieForm? form) + { + if (form == null) return ScreenResult.Invalid(new SessionModel(), "The request has no content."); + + if (!string.IsNullOrEmpty(form.Ticket)) + { + return string.IsNullOrEmpty(form.RecoveryCode) + ? await TwoFactorCoreAsync(form.Ticket, form.Code, cookie: true) + : await RecoveryCoreAsync(form.Ticket, form.RecoveryCode, cookie: true); + } + + return await PasswordStepAsync(new SessionSignInForm { UserName = form.UserName, Password = form.Password }, cookie: true); + } + + private async Task> PasswordStepAsync(SessionSignInForm? form, bool cookie) + { + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(new SessionModel(), errors); + if (!_tokens.IsAvailable) return Unavailable(); + + // Like the page: only the user name finds the account. + var user = await _users.FindByNameAsync(form!.UserName!); + if (user == null) + { + // Spend the time of a password check, so the answer does not tell a missing account from a wrong password. + await Task.Run(() => _users.PasswordHasher.HashPassword(new BaGetUser(), form.Password!)); + + return ScreenResult.SignIn(BadCredentials); + } + + var result = await _signIn.CheckPasswordSignInAsync(user, form.Password!, lockoutOnFailure: true); + if (result.IsLockedOut) return ScreenResult.Forbidden(SignInUseCase.LockedMessage); + if (result.IsNotAllowed) return ScreenResult.Forbidden(user.PendingApproval ? SignInUseCase.PendingMessage : SignInUseCase.UnconfirmedMessage); + if (!result.Succeeded) return ScreenResult.SignIn(BadCredentials); + + return await CompleteAsync(user, _time.UtcNow, cookie); + } + + /// The second factor, with a code of the authenticator app. + public async Task> TwoFactorAsync(SessionTwoFactorForm? form) + { + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(new SessionModel(), errors); + + return await TwoFactorCoreAsync(form!.Ticket, form.Code, cookie: false); + } + + /// The second factor, with a recovery code (each works once). + public async Task> RecoveryCodeAsync(SessionRecoveryCodeForm? form) + { + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(new SessionModel(), errors); + + return await RecoveryCoreAsync(form!.Ticket, form.RecoveryCode, cookie: false); + } + + private async Task> TwoFactorCoreAsync(string? ticketToken, string? rawCode, bool cookie) + { + if (string.IsNullOrWhiteSpace(rawCode)) return ScreenResult.Invalid(new SessionModel(), "The code is required."); + + var ticket = await _authenticator.AuthenticateAsync(SessionTokenKind.TwoFactor, ticketToken); + if (ticket == null) return ScreenResult.SignIn(BadTicket); + + var refusal = await CheckSecondFactorAllowedAsync(ticket.Account); + if (refusal != null) return refusal; + + var code = rawCode.Replace(" ", string.Empty).Replace("-", string.Empty); + var valid = await _users.VerifyTwoFactorTokenAsync(ticket.Account, _users.Options.Tokens.AuthenticatorTokenProvider, code); + + return await FinishSecondFactorAsync(ticket, valid, "The code is not valid.", cookie); + } + + private async Task> RecoveryCoreAsync(string? ticketToken, string? rawCode, bool cookie) + { + if (string.IsNullOrWhiteSpace(rawCode)) return ScreenResult.Invalid(new SessionModel(), "The recovery code is required."); + + var ticket = await _authenticator.AuthenticateAsync(SessionTokenKind.TwoFactor, ticketToken); + if (ticket == null) return ScreenResult.SignIn(BadTicket); + + var refusal = await CheckSecondFactorAllowedAsync(ticket.Account); + if (refusal != null) return refusal; + + var redeemed = await _users.RedeemTwoFactorRecoveryCodeAsync(ticket.Account, rawCode.Replace(" ", string.Empty)); + + return await FinishSecondFactorAsync(ticket, redeemed.Succeeded, "The recovery code is not valid, or was already used.", cookie); + } + + /// Exchanges the 60-second token of an external sign-in's redirect for the session tokens (or the second-factor ticket). + public async Task> ExchangeAsync(SessionExchangeForm? form) + { + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(new SessionModel(), errors); + + var exchange = await _authenticator.AuthenticateAsync(SessionTokenKind.Exchange, form!.ExchangeToken); + if (exchange == null || !_ledger.TryUse(form.ExchangeToken!, exchange.ExpiresAt)) return ScreenResult.SignIn(BadExchange); + + return await CompleteAsync(exchange.Account, exchange.AuthenticatedAt, cookie: false); + } + + /// The exchange token of an external sign-in for the account. + internal async Task IssueExchangeAsync(BaGetUser user, DateTime authenticatedAt) + { + var token = _tokens.Issue(SessionTokenKind.Exchange, user.Id, await StampOfAsync(user), authenticatedAt); + + return new SessionModel { ExchangeToken = token.Token, ExchangeExpiresAt = token.ExpiresAt, UserName = user.UserName }; + } + + /// + /// Exchanges a refresh token for a new pair. The old refresh token stays valid until it expires (the tokens are stateless); the new pair keeps the + /// original authentication time, so a refresh never counts as a fresh sign-in. + /// + public async Task> RefreshAsync(SessionRefreshForm? form) + { + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(new SessionModel(), errors); + + var session = await _authenticator.AuthenticateAsync(SessionTokenKind.Refresh, form!.RefreshToken); + if (session == null) return ScreenResult.SignIn(BadRefresh); + + return ScreenResult.Ok(await IssueAsync(session.Account, session.AuthenticatedAt)); + } + + /// + /// Ends the session. Tokens cannot be taken back one by one, so by itself this revokes nothing (the client forgets them); with + /// the account's security stamp changes, which ends every token and cookie session of the account. The + /// caller is the access token's user, or the owner of the refresh token in the form. + /// + public async Task> SignOutAsync(ClaimsPrincipal? caller, SessionSignOutForm? form) + { + if (form?.Everywhere != true) return ScreenResult.Ok(EmptyScreen.Instance); + + var account = caller?.Identity?.IsAuthenticated == true ? await _users.GetUserAsync(caller) : null; + if (account == null && !string.IsNullOrEmpty(form.RefreshToken)) + { + account = (await _authenticator.AuthenticateAsync(SessionTokenKind.Refresh, form.RefreshToken))?.Account; + } + + if (account == null) return ScreenResult.SignIn("Send the access token or the refresh token of the session to end every session."); + + var updated = await _users.UpdateSecurityStampAsync(account); + if (!updated.Succeeded) return ScreenResult.Invalid(EmptyScreen.Instance, "The sessions could not be ended."); + + return ScreenResult.Ok(EmptyScreen.Instance); + } + + /// Finishes a sign-in whose first factor is proven (also the external provider's): the ticket for the second factor, or the tokens. + internal async Task> CompleteAsync(BaGetUser user, DateTime authenticatedAt, bool cookie = false) + { + if (_users.SupportsUserTwoFactor && await _users.GetTwoFactorEnabledAsync(user)) + { + var ticket = _tokens.Issue(SessionTokenKind.TwoFactor, user.Id, await StampOfAsync(user), authenticatedAt); + + return ScreenResult.Ok(new SessionModel + { + TwoFactorRequired = true, + TwoFactorTicket = ticket.Token, + TwoFactorTicketExpiresAt = ticket.ExpiresAt, + UserName = user.UserName, + }); + } + + if (cookie) + { + await _signIn.SignInAsync(user, isPersistent: false); + + return ScreenResult.Ok(new SessionModel { UserName = user.UserName }); + } + + return ScreenResult.Ok(await IssueAsync(user, authenticatedAt)); + } + + /// A pair of tokens for the account. + internal async Task IssueAsync(BaGetUser user, DateTime authenticatedAt) + { + var stamp = await StampOfAsync(user); + var access = _tokens.Issue(SessionTokenKind.Access, user.Id, stamp, authenticatedAt); + var refresh = _tokens.Issue(SessionTokenKind.Refresh, user.Id, stamp, authenticatedAt); + + return new SessionModel + { + AccessToken = access.Token, + ExpiresAt = access.ExpiresAt, + RefreshToken = refresh.Token, + RefreshExpiresAt = refresh.ExpiresAt, + UserName = user.UserName, + }; + } + + private async Task StampOfAsync(BaGetUser user) + => _users.SupportsUserSecurityStamp ? await _users.GetSecurityStampAsync(user) ?? string.Empty : string.Empty; + + // A locked-out account is refused without looking at the code; one that cannot sign in (approval withdrawn, email) too. + private async Task?> CheckSecondFactorAllowedAsync(BaGetUser user) + { + if (await _users.IsLockedOutAsync(user)) return ScreenResult.Forbidden(SignInUseCase.LockedMessage); + if (!await _signIn.CanSignInAsync(user)) return ScreenResult.Forbidden(user.PendingApproval ? SignInUseCase.PendingMessage : SignInUseCase.UnconfirmedMessage); + + return null; + } + + private async Task> FinishSecondFactorAsync(SessionAuthentication ticket, bool valid, string failure, bool cookie = false) + { + var user = ticket.Account; + if (valid) + { + // Like the sign-in manager: the counter is reset, unless the read-only gate refuses the write. + if (!_gate.IsClosed) await _users.ResetAccessFailedCountAsync(user); + + if (cookie) + { + await _signIn.SignInAsync(user, isPersistent: false); + + return ScreenResult.Ok(new SessionModel { UserName = user.UserName }); + } + + return ScreenResult.Ok(await IssueAsync(user, ticket.AuthenticatedAt)); + } + + // A wrong code is a failed attempt, so codes cannot be guessed without limit. + var counted = await _users.AccessFailedAsync(user); + if (counted.Succeeded && await _users.IsLockedOutAsync(user)) return ScreenResult.Forbidden(SignInUseCase.LockedMessage); + + return ScreenResult.SignIn(failure); + } + + private static ScreenResult Unavailable() + => ScreenResult.Forbidden("Session tokens need ASP.NET Core data protection, which this host does not provide."); +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/SignInUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/SignInUseCase.cs new file mode 100644 index 000000000..3105313e5 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/SignInUseCase.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// The sign-in side of the account screens: the password form, the two second-factor steps and sign-out. The rules are the sign-in pages' always +/// were: lockout, the pending-approval answer (only to the right password), the unconfirmed-email answer and the local-only return URL. Signing in sets +/// the same session cookie whether a view controller or the JSON API calls it ( writes it to the request's response). +/// Browser-only steps (the external provider's challenge and callback) are . +/// +public sealed class SignInUseCase +{ + internal const string PendingMessage = "Your account is waiting for an administrator to enable it. Try again once it has been approved."; + internal const string LockedMessage = "The account is locked after too many failed attempts. Try again later."; + internal const string UnconfirmedMessage = "Confirm your email address before signing in. Use the link we sent you, or reset your password."; + + private readonly SignInManager _signIn; + private readonly UserManager _users; + private readonly IOptions _accounts; + private readonly IOptions _email; + private readonly ExternalLogins _logins; + + /// Creates the use case. + public SignInUseCase( + SignInManager signIn, + UserManager users, + IOptions accounts, + IOptions email) + : this(signIn, users, accounts, email, ExternalLogins.For(users, accounts)) + { + } + + /// Creates the use case. + public SignInUseCase( + SignInManager signIn, + UserManager users, + IOptions accounts, + IOptions email, + ExternalLogins logins) + { + _logins = logins ?? throw new ArgumentNullException(nameof(logins)); + _signIn = signIn ?? throw new ArgumentNullException(nameof(signIn)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _email = email ?? throw new ArgumentNullException(nameof(email)); + } + + // ----- the password form + + /// The sign-in form. + public ScreenResult ShowLogin(string? returnUrl) + => ScreenResult.Ok(Describe(new LoginViewModel { ReturnUrl = returnUrl })); + + /// The password form was posted. A successful sign-in continues at the (local) return URL; the answer carries no password. + public async Task> LoginAsync(LoginForm? form) + { + var model = Describe(new LoginViewModel + { + UserName = form?.UserName, + RememberMe = form?.RememberMe ?? false, + ReturnUrl = form?.ReturnUrl, + }); + + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + #pragma warning disable CS8604 + var result = await _signIn.PasswordSignInAsync(form!.UserName, form.Password, form.RememberMe, lockoutOnFailure: true); + #pragma warning restore CS8604 + if (result.Succeeded) + { + return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Target(form.ReturnUrl))); + } + + if (result.RequiresTwoFactor) + { + return ScreenResult.GoTo(new ScreenNext( + ScreenCatalog.AccountLoginWith2fa, + new Dictionary { ["ReturnUrl"] = form.ReturnUrl, ["RememberMe"] = form.RememberMe })); + } + + if (result.IsNotAllowed && await FindPendingAsync(form) is not null) + { + // For an account awaiting approval the sign-in manager answers "not allowed" only to the right password + // (a wrong one is a counted failure, a locked-out account answers "locked out"), so this message is + // shown to the right password only and never reads like an unconfirmed email. + return Refuse(model, PendingMessage); + } + + return Refuse( + model, + result.IsLockedOut + ? LockedMessage + : result.IsNotAllowed + ? UnconfirmedMessage + : "The user name or password is incorrect."); + } + + private async Task FindPendingAsync(LoginForm form) + { + if (string.IsNullOrEmpty(form.UserName) || string.IsNullOrEmpty(form.Password)) return null; + + var user = await _users.FindByNameAsync(form.UserName); + + return user is { PendingApproval: true } ? user : null; + } + + private static ScreenResult Refuse(LoginViewModel model, string message) + { + model.Error = message; + + return ScreenResult.Invalid(model, message); + } + + /// Fills what the screen shows from the configuration. + internal LoginViewModel Describe(LoginViewModel model) + { + var accounts = _accounts.Value; + model.AllowRegistration = accounts.AllowRegistration; + var providers = _logins.Configured; + model.HasExternalProvider = providers.Count > 0; + model.ExternalProviderName = providers.Count > 0 ? providers[0].DisplayName : null; + model.ExternalProviders = providers; + model.EmailIsConfigured = _email.Value.IsConfigured; + + return model; + } + + // ----- the authenticator code + + /// Without the half-signed-in cookie there is nothing to complete: back to the first step. + public async Task> ShowTwoFactorAsync(bool rememberMe, string? returnUrl) + { + if (await _signIn.GetTwoFactorAuthenticationUserAsync() == null) return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AccountLogin)); + + return ScreenResult.Ok(new TwoFactorLoginViewModel { RememberMe = rememberMe, ReturnUrl = returnUrl }); + } + + /// The authenticator code was posted. + public async Task> TwoFactorAsync(TwoFactorLoginForm? form) + { + if (await _signIn.GetTwoFactorAuthenticationUserAsync() == null) return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AccountLogin)); + + var model = new TwoFactorLoginViewModel { RememberMe = form?.RememberMe ?? false, ReturnUrl = form?.ReturnUrl }; + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + var code = form!.Code?.Replace(" ", string.Empty).Replace("-", string.Empty); + #pragma warning disable CS8604 + var result = await _signIn.TwoFactorAuthenticatorSignInAsync(code, form.RememberMe, rememberClient: false); + #pragma warning restore CS8604 + + if (result.Succeeded) return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Target(form.ReturnUrl))); + + model.Error = result.IsLockedOut ? LockedMessage : "The code is not valid."; + + return ScreenResult.Invalid(model, model.Error); + } + + // ----- the recovery code + + /// Without the half-signed-in cookie there is nothing to complete: back to the first step. + public async Task> ShowRecoveryCodeAsync(string? returnUrl) + { + if (await _signIn.GetTwoFactorAuthenticationUserAsync() == null) return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AccountLogin)); + + return ScreenResult.Ok(new RecoveryCodeLoginViewModel { ReturnUrl = returnUrl }); + } + + /// The recovery code was posted. Each code works once. + public async Task> RecoveryCodeAsync(RecoveryCodeLoginForm? form) + { + if (await _signIn.GetTwoFactorAuthenticationUserAsync() == null) return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.AccountLogin)); + + var model = new RecoveryCodeLoginViewModel { ReturnUrl = form?.ReturnUrl }; + var errors = ScreenValidator.Validate(form); + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + #pragma warning disable CS8604 + var result = await _signIn.TwoFactorRecoveryCodeSignInAsync(form!.RecoveryCode?.Replace(" ", string.Empty)); + #pragma warning restore CS8604 + + if (result.Succeeded) return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Target(form.ReturnUrl))); + + model.Error = result.IsLockedOut ? LockedMessage : "The recovery code is not valid, or was already used."; + + return ScreenResult.Invalid(model, model.Error); + } + + // ----- sign out + + /// The sign-out button (signing out is a POST, so a link elsewhere cannot do it). + public ScreenResult ShowLogout() => ScreenResult.Ok(EmptyScreen.Instance); + + /// Signs the user out and goes to the site root. + public async Task> LogoutAsync() + { + await _signIn.SignOutAsync(); + + return ScreenResult.GoTo(ScreenNext.Local(LocalUrls.Root)); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/TwoFactorCodeForm.cs b/src/BaGet.Identity.Application/UseCases/Account/TwoFactorCodeForm.cs new file mode 100644 index 000000000..18e017eca --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/TwoFactorCodeForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.UseCases.Account; + +/// What the "turn two-factor authentication on" form posts. +public sealed class TwoFactorCodeForm +{ + /// The password, asked again. Needed over /api/ui (a session token or the cookie with an antiforgery header); the screen's form does not post it. + public string? Password { get; set; } + + /// The code from the authenticator app. + public string? Code { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/TwoFactorUseCase.cs b/src/BaGet.Identity.Application/UseCases/Account/TwoFactorUseCase.cs new file mode 100644 index 000000000..13f077fa4 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/TwoFactorUseCase.cs @@ -0,0 +1,227 @@ +using System; +using System.Linq; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using QRCoder; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Security; + +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.UseCases.Account; + +/// +/// Authenticator-app (TOTP) two-factor authentication of the signed-in user: set up with a QR code, recovery codes shown once, turn off, or start +/// over with a new key. The setup key, its QR code and the new recovery codes are in the answer because the screen shows them; the endpoints are +/// cookie sessions only, so an API key can never read them. +/// +public sealed class TwoFactorUseCase +{ + private const int RecoveryCodeCount = 10; + private const string Issuer = "BaGet Extension"; + + private readonly UserManager _users; + private readonly SignInManager _signIn; + private readonly IHttpContextAccessor _http; + private readonly ExternalLogins _logins; + + /// Creates the use case. + public TwoFactorUseCase( + UserManager users, + SignInManager signIn, + IHttpContextAccessor http, + IOptions accounts) + : this(users, signIn, http, accounts, ExternalLogins.For(users, accounts)) + { + } + + /// Creates the use case. + public TwoFactorUseCase( + UserManager users, + SignInManager signIn, + IHttpContextAccessor http, + IOptions accounts, + ExternalLogins logins) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + _signIn = signIn ?? throw new ArgumentNullException(nameof(signIn)); + _http = http ?? throw new ArgumentNullException(nameof(http)); + _ = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _logins = logins ?? throw new ArgumentNullException(nameof(logins)); + } + + private HttpContext Http => _http.HttpContext ?? throw new InvalidOperationException("Two-factor authentication needs a request."); + + /// The screen. + public async Task> ShowAsync(ClaimsPrincipal caller) + { + var model = new TwoFactorViewModel(); + + return await LoadAsync(caller, model) ? ScreenResult.Ok(model) : ScreenResult.SignIn(); + } + + /// Turn two-factor authentication on with a code from the authenticator. + public async Task> EnableAsync(ClaimsPrincipal caller, TwoFactorCodeForm? form) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var model = new TwoFactorViewModel(); + + // Over /api/ui a stolen token must not be enough to take the account over: turning two-factor on asks the password again (the screen's own form is unchanged). + if (AccountConfirmation.IsHttpSession(Http) && !await AccountConfirmation.IsConfirmedAsync(_users, Http, user, form?.Password)) + { + model.Error = "Confirm your password to turn two-factor authentication on."; + + return await DoneAsync(caller, model); + } + + var cleaned = (form?.Code ?? string.Empty).Replace(" ", string.Empty).Replace("-", string.Empty); + var valid = cleaned.Length > 0 && await _users.VerifyTwoFactorTokenAsync( + user, + _users.Options.Tokens.AuthenticatorTokenProvider, + cleaned); + + if (!valid) + { + model.Error = "The code is not valid. Check the authenticator app and try again."; + } + else + { + await _users.SetTwoFactorEnabledAsync(user, true); + await _signIn.RefreshSignInAsync(user); + #pragma warning disable CS8604 + model.RecoveryCodes = (await _users.GenerateNewTwoFactorRecoveryCodesAsync(user, RecoveryCodeCount)).ToList(); + #pragma warning restore CS8604 + model.Message = "Two-factor authentication is on. Keep these recovery codes somewhere safe: each works once, and they are not shown again."; + } + + return await DoneAsync(caller, model); + } + + /// Turn two-factor authentication off (asks the password again). + public async Task> DisableAsync(ClaimsPrincipal caller, PasswordConfirmationForm? form) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var model = new TwoFactorViewModel(); + if (!await AccountConfirmation.IsConfirmedAsync(_users, Http, user, form?.Password)) + { + model.Error = "The confirmation is incorrect, so nothing was changed."; + } + else + { + await _users.SetTwoFactorEnabledAsync(user, false); + await _signIn.RefreshSignInAsync(user); + model.Message = "Two-factor authentication is off."; + } + + return await DoneAsync(caller, model); + } + + /// + /// A new key makes the old authenticator and every recovery code useless; it must be set up and enabled again (asks the password again). + /// + public async Task> ResetAsync(ClaimsPrincipal caller, PasswordConfirmationForm? form) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + var model = new TwoFactorViewModel(); + if (!await AccountConfirmation.IsConfirmedAsync(_users, Http, user, form?.Password)) + { + model.Error = "The confirmation is incorrect, so nothing was changed."; + } + else + { + await _users.SetTwoFactorEnabledAsync(user, false); + await _users.ResetAuthenticatorKeyAsync(user); + await _signIn.RefreshSignInAsync(user); + model.Message = "The authenticator was reset. Scan the new code to turn two-factor authentication on again."; + } + + return await DoneAsync(caller, model); + } + + private async Task> DoneAsync(ClaimsPrincipal caller, TwoFactorViewModel model) + { + await LoadAsync(caller, model); + + return model.Error == null ? ScreenResult.Ok(model) : ScreenResult.Invalid(model, model.Error); + } + + private async Task LoadAsync(ClaimsPrincipal caller, TwoFactorViewModel model) + { + var user = await _users.GetUserAsync(caller); + if (user == null) return false; + + model.TwoFactorEnabled = user.TwoFactorEnabled; + model.HasPassword = await _users.HasPasswordAsync(user); + model.Reauthenticated = !model.HasPassword && await AccountConfirmation.HasReauthenticatedRecentlyAsync(Http); + model.CanReauthenticate = await _logins.CanReauthenticateAsync(user); + model.RecoveryCodesLeft = await _users.CountRecoveryCodesAsync(user); + + // Over /api/ui the setup key (and the stamp change generating it causes) is only handed to a caller who confirmed their password in X-Confirm-Password. + if (!model.TwoFactorEnabled && (!AccountConfirmation.IsHttpSession(Http) || await ConfirmedByHeaderAsync(user))) + { + var key = await _users.GetAuthenticatorKeyAsync(user); + if (string.IsNullOrEmpty(key)) + { + await _users.ResetAuthenticatorKeyAsync(user); + + // The security stamp changed with the key; keep this session signed in. + await _signIn.RefreshSignInAsync(user); + key = await _users.GetAuthenticatorKeyAsync(user); + } + + model.SharedKey = Format(key); + model.QrCodeSvg = RenderQrCode(SetupUri(user.UserName, key)); + } + + return true; + } + + private async Task ConfirmedByHeaderAsync(BaGetUser user) + { + if (!await _users.HasPasswordAsync(user)) return await AccountConfirmation.HasReauthenticatedRecentlyAsync(Http); + + var password = Http.Request.Headers[AccountConfirmation.ConfirmPasswordHeader].ToString(); + + return password.Length > 0 && await AccountConfirmation.IsConfirmedAsync(_users, Http, user, password); + } + + private static string Format(string? key) + { + var result = new StringBuilder(); + #pragma warning disable CS8602 + for (var i = 0; i < key.Length; i += 4) + #pragma warning restore CS8602 + { + if (i > 0) result.Append(' '); + result.Append(key, i, Math.Min(4, key.Length - i)); + } + + return result.ToString(); + } + + #pragma warning disable CS8604 + internal static string SetupUri(string? userName, string? key) + => $"otpauth://totp/{Uri.EscapeDataString(Issuer)}:{Uri.EscapeDataString(userName)}" + + $"?secret={key}&issuer={Uri.EscapeDataString(Issuer)}&digits=6"; + #pragma warning restore CS8604 + + internal static string RenderQrCode(string text) + { + using var generator = new QRCodeGenerator(); + using var data = generator.CreateQrCode(text, QRCodeGenerator.ECCLevel.M); + + return new SvgQRCode(data).GetGraphic(4); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Account/UnlinkExternalForm.cs b/src/BaGet.Identity.Application/UseCases/Account/UnlinkExternalForm.cs new file mode 100644 index 000000000..1265abbdc --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Account/UnlinkExternalForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.UseCases.Account; + +/// What unlinking an external provider posts. +public sealed class UnlinkExternalForm +{ + /// The id of the provider to unlink. + public string? Provider { get; set; } + + /// The password, asked again. + public string? Password { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AddOrganizationMemberForm.cs b/src/BaGet.Identity.Application/UseCases/Admin/AddOrganizationMemberForm.cs new file mode 100644 index 000000000..e0b024830 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AddOrganizationMemberForm.cs @@ -0,0 +1,14 @@ +namespace BaGet.Identity.Application.UseCases.Admin; + +/// What the "add a member" form posts. +public sealed class AddOrganizationMemberForm +{ + /// The organization. + public string? Organization { get; set; } + + /// The user to add. + public string? UserName { get; set; } + + /// Whether the new member administers the organization. + public bool IsAdmin { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminOperationsUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminOperationsUseCase.cs new file mode 100644 index 000000000..d0de0030d --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminOperationsUseCase.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Operations; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// The operational screens of the administrator: maintenance operations (catalog rebuild, downloads import, Docker garbage +/// collection) started as background jobs for a chosen repository (503 while the is closed, recorded +/// with ); the validation queue across every repository (retry, release, reject); the abuse reports of +/// every repository (resolve, reopen); and the read-only formats, cluster status and "access control unavailable" notice. +/// +public sealed class AdminOperationsUseCase : AdminUseCaseBase +{ + private const string NotConfirmedToStart = "The confirmation is incorrect, so nothing was started."; + private static readonly ScreenRef OperationsScreen = ScreenCatalog.AdminOperations; + private static readonly ScreenRef ValidationScreen = ScreenCatalog.AdminValidation; + private static readonly ScreenRef AbuseScreen = ScreenCatalog.AdminAbuse; + + private readonly IServiceProvider _services; + private readonly AdminJobService _jobs; + private readonly IRepositoryService _repositories; + private readonly IRepositoryAdministration _repositoryAdministration; + private readonly IAbuseReportAdministration _reports; + private readonly IAdminAudit _audit; + private readonly FormatRegistry _formats; + private readonly ReadinessService _readiness; + private readonly IClusterStatusService _cluster; + private readonly IValidationAdministration? _validation; + + /// Creates the use case. + public AdminOperationsUseCase( + UserManager users, + PasswordConfirmation confirmation, + IServiceProvider services, + AdminJobService jobs, + IRepositoryService repositories, + IRepositoryAdministration repositoryAdministration, + IAbuseReportAdministration reports, + IAdminAudit audit, + FormatRegistry formats, + ReadinessService readiness, + IClusterStatusService cluster, + MaintenanceGate? gate = null, + IValidationAdministration? validation = null) + : base(users, confirmation, gate) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _jobs = jobs ?? throw new ArgumentNullException(nameof(jobs)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _repositoryAdministration = repositoryAdministration ?? throw new ArgumentNullException(nameof(repositoryAdministration)); + _reports = reports ?? throw new ArgumentNullException(nameof(reports)); + _audit = audit ?? throw new ArgumentNullException(nameof(audit)); + _formats = formats ?? throw new ArgumentNullException(nameof(formats)); + _readiness = readiness ?? throw new ArgumentNullException(nameof(readiness)); + _cluster = cluster ?? throw new ArgumentNullException(nameof(cluster)); + _validation = validation; + } + + // ------------------------------------------------------------------ operations + + /// Lists the operations and their status. is the address to come back to after signing in again. + public async Task> GetOperationsAsync(ClaimsPrincipal caller, string? returnPage, CancellationToken cancellationToken) + { + var model = new OperationsViewModel(); + await Confirmation.LoadAsync(model, caller, returnPage); + + var repositories = await _repositories.ListAsync(cancellationToken); + + model.Rows = _jobs.Operations + .Where(o => o.IsAvailable(_services)) + .SelectMany(o => repositories.Where(o.AppliesTo).Select(r => new OperationRow(o, r, _jobs.Get(o.Name, r.Name)))) + .ToList(); + + return ScreenResult.Ok(model); + } + + /// Starts on . + public async Task> StartAsync(ClaimsPrincipal caller, string? operation, string? repository, string? password, CancellationToken cancellationToken) + { + var info = await _repositories.FindAsync(repository, cancellationToken); + var definition = _jobs.Operations.FirstOrDefault(o => o.Name == operation); + if (info == null || definition == null || !definition.IsAvailable(_services) || !definition.AppliesTo(info)) return ScreenResult.NotFound(); + + var user = await CurrentAsync(caller); + + // An operation that deletes data asks for the password again, like the other destructive pages. + if (definition.RequiresConfirmation) + { + if (user == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(user, password)) + { + return Back(OperationsScreen, null, null, NotConfirmedToStart); + } + } + + return _jobs.TryStart(definition.Name, info, user?.UserName, out var refusal) + ? Back(OperationsScreen, null, $"{definition.Title} started on {info.Name}.", null) + : Back(OperationsScreen, null, null, refusal); + } + + // ------------------------------------------------------------------ validation + + /// Lists the submissions. + public async Task> GetValidationAsync(ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var model = new ValidationViewModel { IsSupported = _validation?.IsSupported == true }; + if (model.IsSupported) + { + model.Submissions = await _validation!.ListAsync(cancellationToken); + } + + await Confirmation.LoadAsync(model, caller); + + return ScreenResult.Ok(model); + } + + /// Validates the submission again. + public Task> RetryAsync(ClaimsPrincipal caller, string? submissionId, CancellationToken cancellationToken) + => ValidationActAsync(caller, submissionId, null, confirm: false, (a, id, user) => a.RetryAsync(id, user, cancellationToken), "queued for validation again"); + + /// Indexes the quarantined package although validation failed. + public Task> ReleaseAsync(ClaimsPrincipal caller, string? submissionId, string? password, CancellationToken cancellationToken) + => ValidationActAsync(caller, submissionId, password, confirm: true, (a, id, user) => a.ReleaseAsync(id, user, cancellationToken), "released and indexed"); + + /// Deletes the quarantined package. + public Task> RejectAsync(ClaimsPrincipal caller, string? submissionId, string? password, CancellationToken cancellationToken) + => ValidationActAsync(caller, submissionId, password, confirm: true, (a, id, user) => a.RejectAsync(id, user, cancellationToken), "rejected and deleted"); + + private async Task> ValidationActAsync( + ClaimsPrincipal caller, + string? submissionId, + string? password, + bool confirm, + Func> action, + string done) + { + var administration = _validation; + if (administration == null || !administration.IsSupported || string.IsNullOrEmpty(submissionId)) return ScreenResult.NotFound(); + + var user = await CurrentAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + if (confirm && !await Confirmation.IsConfirmedAsync(user, password)) + { + return Back(ValidationScreen, null, null, NotConfirmed); + } + + var refusal = await action(administration, submissionId, user.UserName); + + return refusal == null + ? Back(ValidationScreen, null, $"Submission {submissionId} was {done}.", null) + : Back(ValidationScreen, null, null, refusal); + } + + // ------------------------------------------------------------------ abuse reports + + /// Lists the reports (the unresolved ones unless ). + public async Task> GetAbuseAsync(bool all, CancellationToken cancellationToken) + => ScreenResult.Ok(new AbuseViewModel + { + All = all, + IsSupported = _reports.IsSupported, + Items = await _reports.ListAsync(unresolvedOnly: !all, cancellationToken), + }); + + /// Marks a report resolved. + public Task> ResolveAsync(ClaimsPrincipal caller, int key, bool all, CancellationToken cancellationToken) + => SetResolvedAsync(caller, key, all, true, cancellationToken); + + /// Reopens a resolved report. + public Task> ReopenAsync(ClaimsPrincipal caller, int key, bool all, CancellationToken cancellationToken) + => SetResolvedAsync(caller, key, all, false, cancellationToken); + + private async Task> SetResolvedAsync(ClaimsPrincipal caller, int key, bool all, bool resolved, CancellationToken cancellationToken) + { + if (!await _reports.SetResolvedAsync(key, resolved, cancellationToken)) return ScreenResult.NotFound(); + + var user = await CurrentAsync(caller); + _audit.Record(user?.UserName, resolved ? "abuse.resolve" : "abuse.reopen", $"report {key}"); + + return Back( + AbuseScreen, + Route(("all", all ? "true" : null)), + resolved ? $"Report {key} was resolved." : $"Report {key} was reopened.", + null); + } + + // ------------------------------------------------------------------ formats, cluster and the access notice + + /// Lists the formats. + public async Task> GetFormatsAsync(CancellationToken cancellationToken) + { + var repositories = await _repositoryAdministration.ListAsync(cancellationToken); + + return ScreenResult.Ok(new FormatsViewModel + { + Rows = _formats.Modules + .Select(module => new FormatRow( + module, + repositories.Count(r => r.Format == module.Format), + Capabilities(_services, module.Format))) + .ToList(), + }); + } + + // What the module's services answer to: a capability a phase has not implemented yet is simply not listed. + private static IReadOnlyList Capabilities(IServiceProvider services, RepositoryFormat format) + { + var list = new List(); + if (services.GetFormatService(format) != null) list.Add("Deploy (indexing)"); + if (services.GetFormatService(format) != null) list.Add("Search"); + if (services.GetFormatService(format) != null) list.Add("Retention"); + if (services.GetFormatService(format) != null) list.Add("Vulnerability scanning"); + + return list; + } + + /// Reads the cluster status; runs the health checks again instead of using the last answer. + public async Task> GetClusterAsync(bool refresh, CancellationToken cancellationToken) + { + if (refresh) await _readiness.CheckAsync(force: true, cancellationToken); + + return ScreenResult.Ok(new ClusterViewModel { Status = await _cluster.GetAsync(cancellationToken) }); + } + + /// The notice shown where the configured database has no access model. + public ScreenResult GetAccessUnavailable() + => ScreenResult.Ok(AccessUnavailableViewModel.Standard); +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminOrganizationsUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminOrganizationsUseCase.cs new file mode 100644 index 000000000..ba64f7a3b --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminOrganizationsUseCase.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using BaGet.Identity.Application.Models.Organizations; +using BaGet.Identity.Application.Services.Organizations; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// The organization screens of the administrator: the list, and one organization: rename it (package ownership follows in every +/// repository, atomically), add, promote and remove members (an organization keeps at least one administrator) and delete it +/// (refused while it owns packages). Every action asks for the administrator's password again and is refused with 503 while the +/// is closed. +/// +public sealed class AdminOrganizationsUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef DetailScreen = ScreenCatalog.AdminOrganizationDetail; + private static readonly ScreenRef ListScreen = ScreenCatalog.AdminOrganizations; + + private readonly PackageOwnershipService _ownership; + private readonly ILogger _logger; + + /// Creates the use case. + public AdminOrganizationsUseCase( + UserManager users, + PasswordConfirmation confirmation, + PackageOwnershipService ownership, + ILogger logger, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// Lists the organizations. + public async Task> ListAsync(CancellationToken cancellationToken) + => ScreenResult.Ok(new AdminOrganizationsViewModel + { + Organizations = await _ownership.GetAllOrganizationsAsync(cancellationToken), + }); + + /// Shows the organization; not found when there is none. + public async Task> GetAsync(ClaimsPrincipal caller, string? name, CancellationToken cancellationToken) + { + var model = new OrganizationDetailViewModel { Name = name }; + + return await LoadAsync(model, caller, cancellationToken) + ? ScreenResult.Ok(model) + : ScreenResult.NotFound(); + } + + /// Renames the organization. + public Task> RenameAsync(ClaimsPrincipal caller, string? name, string? newName, string? password, CancellationToken cancellationToken) + => ActAsync(caller, name, password, cancellationToken, async (current, outcome) => + { + var result = await _ownership.RenameOrganizationAsync(name, newName, cancellationToken); + if (result == OrganizationChange.Success) + { + Log(current, "renamed organization {Old} to {New}", name, newName?.Trim()); + outcome.Name = newName!.Trim(); + outcome.Message = $"The organization is now called {outcome.Name}."; + } + else + { + outcome.Error = Describe(result); + } + }); + + /// Deletes the organization; on success the list is shown with the outcome. + public async Task> DeleteAsync(ClaimsPrincipal caller, string? name, string? password, CancellationToken cancellationToken) + { + var deleted = false; + string? message = null; + var result = await ActAsync(caller, name, password, cancellationToken, async (current, outcome) => + { + var change = await _ownership.DeleteOrganizationAsync(name, cancellationToken, current.UserName); + if (change == OrganizationChange.Success) + { + Log(current, "deleted organization {Old}", name, null); + message = $"{name} was deleted."; // flashed to the list + deleted = true; + } + else + { + outcome.Error = Describe(change); + } + }); + + return deleted ? Back(ListScreen, null, message, null) : result; + } + + /// Adds a user to the organization. + public Task> AddMemberAsync(ClaimsPrincipal caller, string? name, string? userName, bool isAdmin, string? password, CancellationToken cancellationToken) + => ActAsync(caller, name, password, cancellationToken, async (current, outcome) => + { + var user = string.IsNullOrWhiteSpace(userName) ? null : await Users.FindByNameAsync(userName.Trim()); + if (user == null) + { + outcome.Error = "There is no user with that name."; + } + else if (await _ownership.AddMemberAsync(name!, user.Id, isAdmin, cancellationToken)) + { + Log(current, "added {New} to organization {Old}", name, user.UserName); + outcome.Message = $"{user.UserName} joined {name}."; + } + else + { + outcome.Error = $"{user.UserName} is already a member."; + } + }); + + /// Makes a member an administrator of the organization, or not. + public Task> SetAdminAsync(ClaimsPrincipal caller, string? name, string? userName, bool isAdmin, string? password, CancellationToken cancellationToken) + => ActAsync(caller, name, password, cancellationToken, async (current, outcome) => + { + var user = string.IsNullOrWhiteSpace(userName) ? null : await Users.FindByNameAsync(userName.Trim()); + var result = user == null + ? OrganizationChange.NotFound + : await _ownership.SetMemberAdminAsync(name!, user.Id, isAdmin, cancellationToken); + if (result == OrganizationChange.Success) + { + Log(current, "set administrator={New} for a member of organization {Old}", name, isAdmin.ToString()); + outcome.Message = isAdmin ? $"{user!.UserName} now administers {name}." : $"{user!.UserName} no longer administers {name}."; + } + else + { + outcome.Error = Describe(result); + } + }); + + /// Removes a member from the organization. + public Task> RemoveMemberAsync(ClaimsPrincipal caller, string? name, string? userName, string? password, CancellationToken cancellationToken) + => ActAsync(caller, name, password, cancellationToken, async (current, outcome) => + { + var user = string.IsNullOrWhiteSpace(userName) ? null : await Users.FindByNameAsync(userName.Trim()); + if (user == null) + { + outcome.Error = "There is no user with that name."; + } + else if (await _ownership.RemoveMemberAsync(name!, user.Id, cancellationToken)) + { + Log(current, "removed {New} from organization {Old}", name, user.UserName); + outcome.Message = $"{user.UserName} left {name}."; + } + else + { + outcome.Error = "An organization must keep at least one administrator, and the user must be a member."; + } + }); + + private static string Describe(OrganizationChange change) => change switch + { + OrganizationChange.NameTaken => "That name is taken.", + OrganizationChange.InvalidName => "That is not a valid name: it must not be blank or contain / \\ ? # %.", + OrganizationChange.OwnsPackages => "The organization owns packages, so it cannot be deleted. Remove it as an owner of those packages first.", + OrganizationChange.LastAdministrator => "An organization must keep at least one administrator.", + _ => "There is no such organization or member.", + }; + + private void Log(BaGetUser admin, string template, string? oldValue, string? newValue) + => _logger.LogWarning("{Admin} " + template, admin.UserName, oldValue, newValue); + + // Refuse during maintenance, confirm the password, run the change, then show the (possibly renamed) screen. + private async Task> ActAsync( + ClaimsPrincipal caller, + string? name, + string? password, + CancellationToken cancellationToken, + Func change) + { + ThrowIfClosed(); + + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + if (await _ownership.FindOrganizationAsync(name, cancellationToken) == null) return ScreenResult.NotFound(); + + var outcome = new OrganizationChangeOutcome { Name = name }; + if (!await Confirmation.IsConfirmedAsync(current, password)) + { + outcome.Error = NotConfirmed; + } + else + { + await change(current, outcome); + } + + return Back(DetailScreen, Route(("name", outcome.Name)), outcome.Message, outcome.Error); + } + + private async Task LoadAsync(OrganizationDetailViewModel model, ClaimsPrincipal caller, CancellationToken cancellationToken) + { + model.Organization = await _ownership.FindOrganizationAsync(model.Name, cancellationToken); + if (model.Organization == null) return false; + + var rows = new List(); + foreach (var member in await _ownership.GetMembersAsync(model.Organization.Name, cancellationToken)) + { + #pragma warning disable CS8604 + var user = await Users.FindByIdAsync(member.UserId); + #pragma warning restore CS8604 + if (user != null) rows.Add(new OrganizationMemberRow(user.UserName, member.IsAdmin)); + } + + model.Members = rows.OrderBy(r => r.UserName, StringComparer.OrdinalIgnoreCase).ToList(); + model.OwnedPackageIds = await _ownership.CountOwnedPackageIdsAsync(model.Organization.Name, cancellationToken); + + await Confirmation.LoadForRequestAsync(model, caller); + + return true; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoriesUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoriesUseCase.cs new file mode 100644 index 000000000..02b228a14 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoriesUseCase.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Repositories; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// The repositories screen of the administrator: lists the repositories with their feed addresses and creates new ones: local, remote (an +/// upstream cache, see ) or virtual (an ordered group of members, filled in on its edit screen), of any +/// format whose module offers the kind; the name is validated by . Creating is refused with 503 while the +/// is closed. Creating a remote repository, which can carry credentials, asks for the administrator's password +/// again. A refusal shows the screen again (, the reason in ) with what +/// was typed, except the upstream password, which no answer carries. +/// +public sealed class AdminRepositoriesUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef ListScreen = ScreenCatalog.AdminRepositories; + private static readonly ScreenRef EditScreen = ScreenCatalog.AdminRepositoryEdit; + + private readonly IRepositoryService _repositories; + private readonly IRepositoryAdministration _administration; + private readonly IVirtualRepositoryAdministration _virtuals; + private readonly FormatRegistry _formats; + private readonly RepositoryFeedUrl _feeds; + + /// Creates the use case. + public AdminRepositoriesUseCase( + UserManager users, + PasswordConfirmation confirmation, + IRepositoryService repositories, + IRepositoryAdministration administration, + IVirtualRepositoryAdministration virtuals, + FormatRegistry formats, + RepositoryFeedUrl feeds, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _administration = administration ?? throw new ArgumentNullException(nameof(administration)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + _formats = formats ?? throw new ArgumentNullException(nameof(formats)); + _feeds = feeds ?? throw new ArgumentNullException(nameof(feeds)); + } + + /// + /// Lists the repositories, narrowed by , and (a name fragment) like + /// GET /api/v1/repositories, through . + /// + /// The signed-in administrator. + /// Only this format, or blank. + /// Only this kind, or blank. + /// Only names containing this, or blank. + /// The address to come back to after signing in again. + /// Cancels the work. + public async Task> GetAsync(ClaimsPrincipal caller, string? format, string? kind, string? name, string? returnPage, CancellationToken cancellationToken) + { + var model = new RepositoriesViewModel + { + FilterFormat = Clean(format), + FilterKind = Clean(kind), + FilterName = Clean(name), + }; + + await LoadAsync(model, caller, returnPage, cancellationToken); + model.Repositories = RepositorySummaryFilter.Apply(model.Repositories, model.FilterFormat, model.FilterKind, model.FilterName).ToList(); + FillAddresses(model); + + return ScreenResult.Ok(model); + } + + private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + /// Creates a local NuGet repository (reads Name). + public async Task> CreateAsync(ClaimsPrincipal caller, RepositoryCreateForm? form, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(form); + var name = model.Name?.Trim(); + if (!RepositoryNames.IsValid(name, out var invalid)) + { + return await RefuseAsync(model, caller, returnPage, invalid, cancellationToken); + } + + try + { + await _repositories.CreateAsync(name!, RepositoryFormat.NuGet, RepositoryKind.Local, cancellationToken); + } + catch (Exception e) when (e is NotSupportedException or RepositoryExistsException) + { + return await RefuseAsync(model, caller, returnPage, e.Message, cancellationToken); + } + + return Back(ListScreen, null, $"Repository {name} was created.", null); + } + + /// + /// Creates a local repository of the format named by Format from Name, AnonymousRead (default on) and the format + /// module's in Fields. Not found for a format with no module (or NuGet, which has its own form). + /// + public async Task> CreateFormatAsync(ClaimsPrincipal caller, RepositoryCreateForm? form, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(form); + var module = _formats.Modules.FirstOrDefault(m => string.Equals(m.Format.ToString(), form?.Format, StringComparison.OrdinalIgnoreCase) && m.Format != RepositoryFormat.NuGet); + if (module == null || !module.CreatableKinds.Contains(RepositoryKind.Local)) return ScreenResult.NotFound(); + + model.Format = module.Format.ToString(); + var name = model.Name?.Trim(); + if (!RepositoryNames.IsValid(name, out var invalid)) + { + return await RefuseAsync(model, caller, returnPage, invalid, cancellationToken); + } + + var fields = (form?.Fields ?? new Dictionary()).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal); + + try + { + await _repositories.CreateAsync(name!, module.Format, RepositoryKind.Local, fields, form?.AnonymousRead ?? true, cancellationToken); + } + catch (Exception e) when (e is NotSupportedException or RepositoryExistsException or ArgumentException) + { + return await RefuseAsync(model, caller, returnPage, e.Message, cancellationToken); + } + + return Back(ListScreen, null, $"{module.DisplayName} repository {name} was created.", null); + } + + /// + /// Creates a virtual repository with no members (reads Name, Format (NuGet when blank) and AnonymousRead, default on); the + /// members are added on its screen. Not found for a format whose module does not support virtual repositories. + /// + public async Task> CreateVirtualAsync(ClaimsPrincipal caller, RepositoryCreateForm? form, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(form); + var module = ModuleOf(form?.Format, m => m.SupportsVirtual); + if (module == null) return ScreenResult.NotFound(); + + var name = model.Name?.Trim(); + if (!RepositoryNames.IsValid(name, out var invalid)) + { + return await RefuseAsync(model, caller, returnPage, invalid, cancellationToken); + } + + try + { + await _virtuals.CreateAsync(name!, new VirtualRepositorySettings(), cancellationToken, caller.Identity?.Name, form?.AnonymousRead ?? true, module.Format); + } + catch (Exception e) when (e is NotSupportedException or RepositoryExistsException or ArgumentException) + { + return await RefuseAsync(model, caller, returnPage, e.Message, cancellationToken); + } + + return Back(EditScreen, Route(("name", name)), $"Virtual {Describe(module)}repository {name} was created. Add its members below.", null); + } + + /// + /// Creates a remote repository from Name, Format (NuGet when blank), the upstream in Remote, AnonymousRead (null: + /// anyone unless credentials are set) and the administrator's Password. + /// + public async Task> CreateRemoteAsync(ClaimsPrincipal caller, RepositoryCreateForm? form, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(form); + var module = ModuleOf(form?.Format, m => m.CreatableKinds.Contains(RepositoryKind.Remote)); + if (module == null) return ScreenResult.NotFound(); + model.Format = module.Format.ToString(); + + var current = await CurrentAsync(caller); + if (current == null || !await Confirmation.IsConfirmedAsync(current, form?.Password)) + { + return await RefuseAsync(model, caller, returnPage, NotConfirmed, cancellationToken); + } + + var name = model.Name?.Trim(); + if (!RepositoryNames.IsValid(name, out var invalid)) + { + return await RefuseAsync(model, caller, returnPage, invalid, cancellationToken); + } + + try + { + // Absent = the default: readable by anonymous clients only when no credentials are configured. + var settings = model.Remote.ToSettings(); + var anonymous = form?.AnonymousRead ?? !settings.HasCredentials; + await _repositories.CreateAsync(name!, module.Format, RepositoryKind.Remote, settings, anonymous, cancellationToken); + } + catch (Exception e) when (e is NotSupportedException or RepositoryExistsException or ArgumentException or InvalidOperationException) + { + return await RefuseAsync(model, caller, returnPage, e.Message, cancellationToken); + } + + return Back(EditScreen, Route(("name", name)), $"Remote {Describe(module)}repository {name} was created.", null); + } + + private static RepositoriesViewModel Start(RepositoryCreateForm? form) + { + var model = new RepositoriesViewModel { Name = form?.Name }; + if (form?.Remote != null) model.Remote = form.Remote; + + return model; + } + + // "npm " for a format other than NuGet, whose wording predates the format layer ("Remote repository up was created."). + private static string Describe(IFormatModule module) => module.Format == RepositoryFormat.NuGet ? string.Empty : module.DisplayName + " "; + + // The module named by a posted format (NuGet when none), when it passes 'offers'; null otherwise. + private IFormatModule? ModuleOf(string? format, Func offers) + { + var module = string.IsNullOrEmpty(format) + ? _formats.Find(RepositoryFormat.NuGet) + : _formats.Modules.FirstOrDefault(m => string.Equals(m.Format.ToString(), format, StringComparison.OrdinalIgnoreCase)); + + return module != null && offers(module) ? module : null; + } + + // Shows the screen again with a reason, keeping what was typed (the password excepted). + private async Task> RefuseAsync(RepositoriesViewModel model, ClaimsPrincipal caller, string? returnPage, string? error, CancellationToken cancellationToken) + { + model.Error = error; + await LoadAsync(model, caller, returnPage, cancellationToken); + FillAddresses(model); + + return ScreenResult.Invalid(model, error ?? "The repository was not created."); + } + + private async Task LoadAsync(RepositoriesViewModel model, ClaimsPrincipal caller, string? returnPage, CancellationToken cancellationToken) + { + model.Remote.Password = null; // never sent back + + await Confirmation.LoadAsync(model, caller, returnPage); + model.CanCreate = _repositories.SupportsMultipleRepositories; + model.AllFormats = _formats.Modules.Select(RepositoryFormatChoice.Of).ToList(); + model.RemoteFormats = _formats.Modules.Where(m => m.CreatableKinds.Contains(RepositoryKind.Remote)).Select(RepositoryFormatChoice.Of).ToList(); + model.VirtualFormats = _formats.Modules.Where(m => m.SupportsVirtual).Select(RepositoryFormatChoice.Of).ToList(); + model.OtherFormats = _formats.Modules.Where(m => m.Format != RepositoryFormat.NuGet && m.CreatableKinds.Contains(RepositoryKind.Local)).Select(RepositoryFormatChoice.Of).ToList(); + + model.Repositories = await _administration.ListAsync(cancellationToken); + model.Deployable = await DeployableAsync(model.Repositories, cancellationToken); + } + + private async Task> DeployableAsync(IReadOnlyList repositories, CancellationToken cancellationToken) + { + var deployable = new List(); + foreach (var repository in repositories.Where(r => r.Kind == RepositoryKind.Virtual)) + { + if ((await _virtuals.FindAsync(repository.Name, cancellationToken))?.DeployTarget != null) deployable.Add(repository.Name); + } + + return deployable; + } + + // The feed address, base address and links of each listed repository. + private void FillAddresses(RepositoriesViewModel model) + { + var feeds = new Dictionary(StringComparer.Ordinal); + var bases = new Dictionary(StringComparer.Ordinal); + var links = new Dictionary>(StringComparer.Ordinal); + foreach (var repository in model.Repositories) + { + var module = _formats.Find(repository.Format); + feeds[repository.Name] = _feeds.For(repository.Name, module?.FeedPath ?? "v3/index.json"); + bases[repository.Name] = _feeds.BaseFor(repository.Name); + + var takesUploads = repository.Kind switch + { + RepositoryKind.Remote => false, + RepositoryKind.Virtual => model.Deployable.Contains(repository.Name), + _ => true, + }; + links[repository.Name] = (module?.RepositoryLinks(new RepositoryInfo(repository.Key, repository.Name, repository.Format, repository.Kind)) ?? Array.Empty()) + .Where(l => !l.NeedsUploads || takesUploads) + .ToList(); + } + + model.Feeds = feeds; + model.BaseUrls = bases; + model.Links = links; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoryDeleteUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoryDeleteUseCase.cs new file mode 100644 index 000000000..5549a37b8 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoryDeleteUseCase.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Repositories; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// The screen that deletes a repository (/admin/repositories/{name}/delete) with no packages, and its history rows. The default repository +/// cannot be deleted. A repository that still holds packages is refused (delete the packages first), and so is one that a virtual repository lists as +/// a member (remove it there first). Refused with 503 while the is closed. +/// +public sealed class AdminRepositoryDeleteUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef ListScreen = ScreenCatalog.AdminRepositories; + + private readonly IRepositoryAdministration _administration; + private readonly IVirtualRepositoryAdministration _virtuals; + + /// Creates the use case. + public AdminRepositoryDeleteUseCase( + UserManager users, + PasswordConfirmation confirmation, + IRepositoryAdministration administration, + IVirtualRepositoryAdministration virtuals, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _administration = administration ?? throw new ArgumentNullException(nameof(administration)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + } + + /// Shows what the deletion does; not found when there is no such repository. + public async Task> GetAsync(string? name, CancellationToken cancellationToken) + { + var model = new RepositoryDeleteViewModel { Name = name }; + model.Repository = await _administration.FindAsync(name, cancellationToken); + if (model.Repository == null) return ScreenResult.NotFound(); + + model.ReferencedBy = await _virtuals.ReferencedByAsync(model.Repository.Name, cancellationToken); + + return ScreenResult.Ok(model); + } + + /// Deletes the repository, then returns to the list; a refusal shows the screen again with the reason. + public async Task> DeleteAsync(string? name, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = new RepositoryDeleteViewModel { Name = name }; + model.Repository = await _administration.FindAsync(name, cancellationToken); + if (model.Repository == null) return ScreenResult.NotFound(); + + try + { + await _administration.DeleteAsync(name!, cancellationToken); + } + catch (KeyNotFoundException) + { + return ScreenResult.NotFound(); + } + catch (InvalidOperationException e) when (e is RepositoryProtectedException or RepositoryNotEmptyException or RepositoryReferencedException) + { + model.Error = e.Message; + + return ScreenResult.Invalid(model, e.Message); + } + + return Back(ListScreen, null, $"Repository {name} was deleted.", null); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoryEditUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoryEditUseCase.cs new file mode 100644 index 000000000..a55c8c46e --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminRepositoryEditUseCase.cs @@ -0,0 +1,517 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Repositories; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// The screen of one repository (/admin/repositories/{name}): shows its feed address and the access model's view of it (who effectively holds +/// each action) and edits what can change: whether anonymous requests may read it. The name never changes (it is in URLs and storage paths), and neither +/// does the format or kind. A remote repository also shows and edits its upstream (URL, protocol, credentials, cache periods, offline, store locally), +/// tests the connection with the unsaved values, shows its cache and purges it (whole, or one package). Saving and purging are refused with 503 while +/// the is closed. Changing, purging and testing the connection of a remote repository ask for the administrator's +/// password again (a test saves nothing, but makes the server send a request to a typed URL, with the stored password when the origin is unchanged). A +/// virtual repository shows and edits its members (add, remove, move up or down), its deploy repository, and previews where a package version would +/// come from (); those edits are saved at once, +/// refused with 503 while the gate is closed. A local Maven repository edits its policy. +/// +/// A refusal shows the screen again (, the reason in ). No answer carries a +/// password: the upstream's stored password is never read back (only HasPassword) and the one typed is cleared from the model. +/// +/// +public sealed class AdminRepositoryEditUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef ListScreen = ScreenCatalog.AdminRepositories; + private static readonly ScreenRef EditScreen = ScreenCatalog.AdminRepositoryEdit; + + private readonly IRepositoryAdministration _administration; + private readonly IRepositoryService _repositories; + private readonly IRemoteRepositoryAdministration _remotes; + private readonly IVirtualRepositoryAdministration _virtuals; + private readonly IMavenRepositoryAdministration _maven; + private readonly IAccessEvaluator _access; + private readonly FormatRegistry _formats; + private readonly RepositoryFeedUrl _feeds; + + /// Creates the use case. + public AdminRepositoryEditUseCase( + UserManager users, + PasswordConfirmation confirmation, + IRepositoryAdministration administration, + IRepositoryService repositories, + IRemoteRepositoryAdministration remotes, + IVirtualRepositoryAdministration virtuals, + IMavenRepositoryAdministration maven, + IAccessEvaluator access, + FormatRegistry formats, + RepositoryFeedUrl feeds, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _administration = administration ?? throw new ArgumentNullException(nameof(administration)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _remotes = remotes ?? throw new ArgumentNullException(nameof(remotes)); + _virtuals = virtuals ?? throw new ArgumentNullException(nameof(virtuals)); + _maven = maven ?? throw new ArgumentNullException(nameof(maven)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _formats = formats ?? throw new ArgumentNullException(nameof(formats)); + _feeds = feeds ?? throw new ArgumentNullException(nameof(feeds)); + } + + /// Shows the repository; not found when there is none. + /// The signed-in administrator. + /// The repository's name. + /// The address to come back to after signing in again. + /// Cancels the work. + public async Task> GetAsync(ClaimsPrincipal caller, string? name, string? returnPage, CancellationToken cancellationToken) + { + var model = Start(name, null, returnPage); + if (!await LoadAsync(model, caller, cancellationToken)) return ScreenResult.NotFound(); + + model.AnonymousRead = model.Repository!.AnonymousRead; + if (model.RemoteDetail != null) model.Remote = RemoteFormModel.From(model.RemoteDetail); + + return Done(model); + } + + /// Saves the repository: reads AnonymousRead and, for a remote one, Remote (a blank password keeps the stored one) and Password. + public async Task> SaveAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(name, request, returnPage); + var summary = await _administration.FindAsync(model.Name, cancellationToken); + if (summary == null) return ScreenResult.NotFound(); + + if (summary.Kind == RepositoryKind.Remote) + { + if (!await ConfirmedAsync(caller, request?.Password)) return await RefuseAsync(model, caller, NotConfirmed, cancellationToken); + + try + { + await _remotes.UpdateAsync(model.Name!, model.Remote.ToSettings(), model.Remote.ClearPassword, cancellationToken, caller.Identity?.Name); + } + catch (Exception e) when (e is ArgumentException or InvalidOperationException) + { + return await RefuseAsync(model, caller, e.Message, cancellationToken); + } + } + + await _administration.SetAnonymousReadAsync(model.Name!, model.AnonymousRead, cancellationToken, caller.Identity?.Name); + + return Back(ListScreen, null, $"Repository {model.Name} was saved.", null); + } + + /// + /// Saves the policy of a local Maven repository (Policy, Redeploy, SnapshotBuilds): which versions it accepts, whether a release may + /// be redeployed and how many snapshot builds are kept. Audited; a stricter policy applies to later deploys and deletes nothing. + /// + public async Task> SaveMavenSettingsAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(name, request, returnPage); + MavenRepositorySettings settings; + try + { + settings = MavenRepositorySettings.FromFields(new Dictionary + { + ["policy"] = request?.Policy, + ["redeploy"] = request?.Redeploy, + ["snapshotBuilds"] = request?.SnapshotBuilds, + }); + } + catch (ArgumentException e) + { + return await RefuseAsync(model, caller, e.Message, cancellationToken); + } + + if (!await _maven.SaveSettingsAsync(model.Name!, settings, caller.Identity?.Name, cancellationToken)) + { + return ScreenResult.NotFound(); + } + + return Back(EditScreen, Route(("name", model.Name)), $"The settings of repository {model.Name} were saved.", null); + } + + /// Asks the upstream with the unsaved Remote values (a blank password means the stored one) and saves nothing; asks for the Password. + public async Task> TestAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + var model = Start(name, request, returnPage); + if (!await LoadAsync(model, caller, cancellationToken)) return ScreenResult.NotFound(); + if (model.RemoteDetail == null) return ScreenResult.NotFound(); + + // The probe makes this server send a request to a URL the administrator typed (and the stored password, if the + // origin is unchanged): it asks for the password again, like the changes that hand out credentials. + if (!await ConfirmedAsync(caller, request?.Password)) return await RefuseAsync(model, caller, NotConfirmed, cancellationToken); + + model.AnonymousRead = model.Repository!.AnonymousRead; + var settings = model.Remote.ToSettings(); + if (model.RemoteDetail.IsMirror) + { + settings.Url = model.RemoteDetail.Settings.Url; + settings.Protocol = model.RemoteDetail.Settings.Protocol; + } + + model.TestResult = await _remotes.TestConnectionAsync(model.Name, settings, cancellationToken); + KeepRemoteFields(model); + + return Done(model); + } + + /// Deletes every package the remote repository stored and forgets what it remembered of its upstream; asks for the Password. + public async Task> PurgeAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(name, request, returnPage); + var found = await _remotes.FindAsync(model.Name, cancellationToken); + if (found == null) return ScreenResult.NotFound(); + if (!await ConfirmedAsync(caller, request?.Password)) return await RefuseAsync(model, caller, NotConfirmed, cancellationToken); + + var result = await _remotes.PurgeAsync(model.Name!, cancellationToken, caller.Identity?.Name); + var unit = (await _remotes.FindAsync(model.Name, cancellationToken))?.Repository.Format == RepositoryFormat.Docker ? "manifest(s)" : "package version(s)"; + + return Back( + EditScreen, + Route(("name", model.Name)), + $"The cache of {model.Name} was purged: {result.Packages} {unit} deleted, {result.CachedAnswers} remembered answer(s) dropped.", + null); + } + + /// + /// Deletes one cached package (PackageId; every version, or the PackageVersion given) and forgets what was remembered about it; asks for + /// the Password. + /// + public async Task> PurgePackageAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(name, request, returnPage); + var found = await _remotes.FindAsync(model.Name, cancellationToken); + if (found == null) return ScreenResult.NotFound(); + if (!await ConfirmedAsync(caller, request?.Password)) return await RefuseAsync(model, caller, NotConfirmed, cancellationToken); + + var id = model.PackageId?.Trim(); + if (string.IsNullOrEmpty(id)) + { + return await RefuseAsync(model, caller, "Enter the id of the package to purge.", cancellationToken); + } + + // A Maven version is any version folder name, not always a NuGet version (5.3.20.RELEASE), and a Docker one is a tag or a digest: + // they travel as text. + var isMaven = found.Repository.Format == RepositoryFormat.Maven; + var isDocker = found.Repository.Format == RepositoryFormat.Docker; + NuGet.Versioning.NuGetVersion? version = null; + string? versionText = string.IsNullOrWhiteSpace(model.PackageVersion) ? null : model.PackageVersion.Trim(); + if (!isMaven && !isDocker && versionText != null) + { + if (!NuGet.Versioning.NuGetVersion.TryParse(versionText, out version)) + { + return await RefuseAsync(model, caller, $"'{model.PackageVersion}' is not a valid version.", cancellationToken); + } + + versionText = version.ToNormalizedString(); + } + + PurgeResult result; + try + { + result = isMaven + ? await _remotes.PurgeArtifactAsync(model.Name!, id, versionText, cancellationToken, caller.Identity?.Name) + : isDocker + ? await _remotes.PurgeImageAsync(model.Name!, id, versionText, cancellationToken, caller.Identity?.Name) + : await _remotes.PurgePackageAsync(model.Name!, id, version, cancellationToken, caller.Identity?.Name); + } + catch (ArgumentException e) + { + // A name the repository's format would not accept (an npm name must be lower case...). + return await RefuseAsync(model, caller, e.Message, cancellationToken); + } + + var shown = versionText == null ? string.Empty : " " + versionText; + var message = result.Packages == 0 && result.CachedAnswers == 0 + ? $"Nothing was cached for {id}{shown}." + : $"{id}{shown} was purged: {result.Packages} {(isMaven ? "file(s)" : isDocker ? "manifest(s)" : "package version(s)")} deleted, {result.CachedAnswers} remembered answer(s) dropped."; + + return Back(EditScreen, Route(("name", model.Name)), message, null); + } + + /// Adds the repository Member at the end of the virtual repository's members. + public Task> AddMemberAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + var member = request?.Member; + + return ChangeMembersAsync( + caller, name, request, returnPage, + settings => + { + if (string.IsNullOrEmpty(member)) return "Choose the repository to add."; + if (settings.Members.Contains(member!)) return $"'{member}' is already a member."; + + settings.Members.Add(member!); + + return null; + }, + $"{member} was added.", + cancellationToken); + } + + /// Removes the Member (and the deploy repository too when it was that member). + public Task> RemoveMemberAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + var member = request?.Member; + + return ChangeMembersAsync( + caller, name, request, returnPage, + settings => + { + if (!settings.Members.Remove(member ?? string.Empty)) return $"'{member}' is not a member."; + if (settings.DeployRepository == member) settings.DeployRepository = null; + + return null; + }, + $"{member} was removed.", + cancellationToken); + } + + /// Moves the Member one place earlier (Direction up) or later (otherwise) in the resolution order. + public Task> MoveMemberAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + var member = request?.Member; + var direction = request?.Direction; + + return ChangeMembersAsync( + caller, name, request, returnPage, + settings => + { + var index = settings.Members.IndexOf(member ?? string.Empty); + if (index < 0) return $"'{member}' is not a member."; + + var target = string.Equals(direction, "up", StringComparison.OrdinalIgnoreCase) ? index - 1 : index + 1; + if (target < 0 || target >= settings.Members.Count) return null; + + (settings.Members[index], settings.Members[target]) = (settings.Members[target], settings.Members[index]); + + return null; + }, + $"{member} was moved {(string.Equals(direction, "up", StringComparison.OrdinalIgnoreCase) ? "up" : "down")}.", + cancellationToken); + } + + /// Sets the member that receives uploads (Deploy; blank: the virtual repository takes none). + public Task> SetDeployAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + var deploy = request?.Deploy; + + return ChangeMembersAsync( + caller, name, request, returnPage, + settings => + { + settings.DeployRepository = string.IsNullOrWhiteSpace(deploy) ? null : deploy; + + return null; + }, + string.IsNullOrWhiteSpace(deploy) ? "The virtual repository no longer takes uploads." : $"Uploads now go to {deploy}.", + cancellationToken); + } + + /// Shows where the package version typed (PreviewPackageId, PreviewVersion) would come from, member by member (nothing is fetched or stored). + public async Task> PreviewAsync(ClaimsPrincipal caller, string? name, RepositoryEditRequest? request, string? returnPage, CancellationToken cancellationToken) + { + var model = Start(name, request, returnPage); + if (!await LoadAsync(model, caller, cancellationToken) || model.VirtualDetail == null) return ScreenResult.NotFound(); + + model.AnonymousRead = model.Repository!.AnonymousRead; + var id = model.PreviewPackageId?.Trim(); + if (string.IsNullOrEmpty(id)) + { + return Refused(model, "Enter the id of the package to resolve."); + } + + var repository = model.Repository; + var isMaven = repository.Format == RepositoryFormat.Maven; + var isDocker = repository.Format == RepositoryFormat.Docker; + if (!isMaven && !isDocker && !NuGet.Versioning.NuGetVersion.TryParse(model.PreviewVersion?.Trim(), out _)) + { + return Refused(model, $"'{model.PreviewVersion}' is not a valid version."); + } + + if (repository.Format == RepositoryFormat.Npm) + { + // An npm name is checked by the one rule every npm route and page uses (scoped names; a lookup accepts legacy upper case). + if (!NpmNames.TryParseLookup(id, out id, out var invalidName)) + { + return Refused(model, invalidName); + } + } + + try + { + model.Preview = await _virtuals.PreviewAsync(model.Name!, id, model.PreviewVersion?.Trim() ?? string.Empty, cancellationToken); + } + catch (ArgumentException e) + { + // An artifact that is not group:artifact, or a version that is not a folder name. + return Refused(model, e.Message); + } + + return Done(model); + } + + // ------------------------------------------------------------------ shared + + // The model for a request: the route name and the posted fields. + private static RepositoryEditViewModel Start(string? name, RepositoryEditRequest? request, string? returnPage) + { + var model = new RepositoryEditViewModel { Name = name }; + if (returnPage != null) model.ReturnPage = returnPage; + if (request != null) + { + model.AnonymousRead = request.AnonymousRead; + if (request.Remote != null) model.Remote = request.Remote; + model.PreviewPackageId = request.PreviewPackageId; + model.PreviewVersion = request.PreviewVersion; + model.PackageId = request.PackageId; + model.PackageVersion = request.PackageVersion; + } + + return model; + } + + // Loads the repository, its access summary and, for a remote one, its upstream and cache. False: no such repository. + private async Task LoadAsync(RepositoryEditViewModel model, ClaimsPrincipal caller, CancellationToken cancellationToken) + { + await Confirmation.LoadAsync(model, caller, model.ReturnPage.Length == 0 ? null : model.ReturnPage); + var repository = model.Repository = await _administration.FindAsync(model.Name, cancellationToken); + if (repository == null) return false; + + var module = _formats.Find(repository.Format); + var browse = module + ?.RepositoryLinks(new RepositoryInfo(repository.Key, repository.Name, repository.Format, repository.Kind)) + .FirstOrDefault(l => l.Id == "browse" && l.Controller != null && l.Action != null); + model.BrowseScreen = browse == null ? ScreenCatalog.Index : new ScreenRef(browse.Controller!, browse.Action!); + model.FeedUrl = _feeds.For(repository.Name, module?.FeedPath ?? "v3/index.json"); + + var info = (await _repositories.ListAsync(cancellationToken)).FirstOrDefault(r => r.Name == repository.Name); + if (info != null) + { + model.Access = await _access.DescribeAsync(info, cancellationToken); + } + + if (repository.Kind == RepositoryKind.Remote) + { + model.RemoteDetail = await _remotes.FindAsync(model.Name, cancellationToken); + if (model.RemoteDetail != null) model.Cache = await _remotes.GetCacheAsync(model.Name!, cancellationToken); + } + else if (repository.Kind == RepositoryKind.Virtual) + { + model.VirtualDetail = await _virtuals.FindAsync(model.Name, cancellationToken); + var members = model.VirtualDetail?.Members.Select(m => m.Name).ToHashSet() ?? new HashSet(); + model.MemberCandidates = (await _virtuals.CandidatesAsync(model.Name, cancellationToken)).Where(c => !members.Contains(c.Name)).ToList(); + } + + if (repository.Kind != RepositoryKind.Virtual) + { + model.ReferencedBy = await _virtuals.ReferencedByAsync(repository.Name, cancellationToken); + } + + if (repository.Format == RepositoryFormat.Maven && repository.Kind == RepositoryKind.Local) + { + model.MavenSettings = await _maven.GetSettingsAsync(repository.Name, cancellationToken); + } + + if (repository.IsDefault) + { + model.MirrorRepository = await _remotes.FindAsync(Repository.MirrorName, cancellationToken); + model.MirrorActive = model.MirrorRepository?.IsMirror == true; + } + + return true; + } + + private async Task ConfirmedAsync(ClaimsPrincipal caller, string? password) + { + var current = await CurrentAsync(caller); + + return current != null && await Confirmation.IsConfirmedAsync(current, password); + } + + // Applies 'change' to a copy of the virtual repository's settings and saves them; 'change' returns a reason to refuse. + private async Task> ChangeMembersAsync( + ClaimsPrincipal caller, + string? name, + RepositoryEditRequest? request, + string? returnPage, + Func change, + string done, + CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = Start(name, request, returnPage); + var detail = await _virtuals.FindAsync(model.Name, cancellationToken); + if (detail == null) return ScreenResult.NotFound(); + + var settings = new VirtualRepositorySettings + { + Members = detail.Members.Select(m => m.Name).ToList(), + DeployRepository = detail.DeployRepository, + }; + + var refusal = change(settings); + if (refusal != null) return await RefuseAsync(model, caller, refusal, cancellationToken); + + try + { + await _virtuals.UpdateAsync(model.Name!, settings, cancellationToken, caller.Identity?.Name); + } + catch (ArgumentException e) + { + return await RefuseAsync(model, caller, e.Message, cancellationToken); + } + + return ScreenResult.GoTo(new ScreenNext(EditScreen, Route(("name", model.Name)), done, null, null, "repository-section-virtual")); + } + + // Shows the screen again with a reason, keeping what was typed. + private async Task> RefuseAsync(RepositoryEditViewModel model, ClaimsPrincipal caller, string error, CancellationToken cancellationToken) + { + if (!await LoadAsync(model, caller, cancellationToken)) return ScreenResult.NotFound(); + + if (model.RemoteDetail != null) KeepRemoteFields(model); + + return Refused(model, error); + } + + private static ScreenResult Refused(RepositoryEditViewModel model, string? error) + { + model.Error = error; + model.Remote.Password = null; + + return ScreenResult.Invalid(model, error ?? "The change was refused."); + } + + private static ScreenResult Done(RepositoryEditViewModel model) + { + model.Remote.Password = null; // never sent back + + return ScreenResult.Ok(model); + } + + // The display-only fields of the upstream form, which a posted form does not carry; the typed password is never shown again. + private static void KeepRemoteFields(RepositoryEditViewModel model) + { + model.Remote.HasPassword = model.RemoteDetail!.HasPassword; + model.Remote.EndpointFromMirror = model.RemoteDetail.IsMirror; + model.Remote.Format = model.RemoteDetail.Repository.Format; + model.Remote.Password = null; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminSettingsUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminSettingsUseCase.cs new file mode 100644 index 000000000..9d844c37e --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminSettingsUseCase.cs @@ -0,0 +1,356 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Primitives; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// Edits every registered setting. Values are written to the overrides file; see . One form per +/// section, so one section's errors never block another. +/// +public sealed class AdminSettingsUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef Screen = ScreenCatalog.AdminSettings; + + // The section of the Settings screen that carries the "Sign-in providers" panel. + private const string ProvidersSection = "Accounts"; + + private readonly SettingsService _settings; + private readonly DatabaseCopyService _copier; + private readonly IConfiguration _configuration; + private readonly ITelemetryDiagnostics? _telemetry; + private readonly SignInProviderSettings _providers; + + /// Creates the use case. + public AdminSettingsUseCase( + UserManager users, + PasswordConfirmation confirmation, + SettingsService settings, + DatabaseCopyService copier, + IConfiguration configuration, + MaintenanceGate? gate = null, + ITelemetryDiagnostics? telemetry = null) + : this(users, confirmation, settings, copier, configuration, gate, telemetry, new SignInProviderSettings(settings, configuration, OpenIdConnectProviderSet.Empty)) + { + } + + /// Creates the use case. + public AdminSettingsUseCase( + UserManager users, + PasswordConfirmation confirmation, + SettingsService settings, + DatabaseCopyService copier, + IConfiguration configuration, + MaintenanceGate? gate, + ITelemetryDiagnostics? telemetry, + SignInProviderSettings providers) + : base(users, confirmation, gate) + { + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _copier = copier ?? throw new ArgumentNullException(nameof(copier)); + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + _telemetry = telemetry; + _providers = providers ?? throw new ArgumentNullException(nameof(providers)); + } + + /// Shows the settings. is the id of the section to show (no JavaScript needed). + public async Task> GetAsync(ClaimsPrincipal caller, string? section) + { + if (!_settings.IsAvailable) return ScreenResult.NotFound(); + + var model = new AdminSettingsViewModel(); + await LoadAsync(model, caller); + Select(model, section); + + return ScreenResult.Ok(model); + } + + /// The progress of the database copy, polled by the page. Administrators only (the caller's gate); holds no connection string. + public ScreenResult GetCopyStatus() + => _settings.IsAvailable + ? ScreenResult.Ok(DatabaseCopyStatusView.Of(_copier.Status)) + : ScreenResult.NotFound(); + + /// + /// Saves the settings of one section after the administrator confirms. Refused with HTTP 503 while the + /// is closed. A Database section that changes to another relational database with "Copy all + /// data" ticked is queued as a copy () instead of saved: the settings are saved by the copy + /// once it is verified. A refusal shows the screen again (). + /// + public async Task> SaveAsync(ClaimsPrincipal caller, SettingsSubmission submission, CancellationToken cancellationToken) + { + if (!_settings.IsAvailable) return ScreenResult.NotFound(); + + // Saving writes a file, not the database, so the SaveChanges gate would not stop it; but a save + // while the database is read-only for maintenance (a copy, or the wait for a restart) could + // change the very settings the job depends on. The job itself saves through SettingsService. + ThrowIfClosed(); + + var section = submission.Section ?? string.Empty; + var user = await CurrentAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(user, submission.Password)) + { + return await FailAsync(caller, section, new[] { "The confirmation is incorrect, so nothing was changed." }); + } + + var states = _settings.GetState() + .Where(s => string.Equals(s.Descriptor.Section, section, StringComparison.OrdinalIgnoreCase)) + .ToList(); + var (changes, parseErrors) = SettingsForm.Parse( + submission.Fields.Select(pair => new KeyValuePair(pair.Key, new StringValues(pair.Value))), + states); + + if (parseErrors.Count == 0 + && string.Equals(section, "Database", StringComparison.OrdinalIgnoreCase) + && submission.Field("copyData").Any(v => string.Equals(v, "true", StringComparison.OrdinalIgnoreCase)) + && PlanCopy(changes, user.UserName) is { } copy) + { + if (!_copier.TryQueue(copy, out var refusal)) return await FailAsync(caller, section, new[] { refusal! }); + + return ToSection(section, "Copying the data to the new database. The settings are saved when the copy is verified."); + } + + var result = parseErrors.Count == 0 + ? await _settings.SaveAsync(changes, user.UserName, cancellationToken) + : SettingsSaveResult.Failed(parseErrors); + if (!result.Succeeded) return await FailAsync(caller, section, result.Errors); + + return ToSection(section, changes.Count == 0 ? "Nothing changed." : $"Saved {changes.Count} setting(s)."); + } + + /// + /// Adds or changes a named OpenID Connect provider (the "Sign-in providers" panel of the Accounts section). Confirmed with the password, refused with + /// HTTP 503 while the is closed. A blank secret keeps the saved one; the provider is registered after a restart. + /// + public async Task> SaveSignInProviderAsync(ClaimsPrincipal caller, SignInProviderForm? form, CancellationToken cancellationToken) + { + if (!_settings.IsAvailable) return ScreenResult.NotFound(); + + ThrowIfClosed(); + + var user = await CurrentAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + if (form == null || !await Confirmation.IsConfirmedAsync(user, form.Password)) + { + return await FailAsync(caller, ProvidersSection, new[] { NotConfirmed }); + } + + var result = await _providers.SaveAsync(form, user.UserName, cancellationToken); + if (!result.Succeeded) return await FailAsync(caller, ProvidersSection, result.Errors); + + return ToSection(ProvidersSection, $"Saved the provider {form.Id?.Trim()}. Restart BaGet to apply it."); + } + + /// Removes a named provider saved on this screen (the same confirmation, gate and restart as ). + public async Task> RemoveSignInProviderAsync(ClaimsPrincipal caller, RemoveSignInProviderForm? form, CancellationToken cancellationToken) + { + if (!_settings.IsAvailable) return ScreenResult.NotFound(); + + ThrowIfClosed(); + + var user = await CurrentAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + if (form == null || !await Confirmation.IsConfirmedAsync(user, form.Password)) + { + return await FailAsync(caller, ProvidersSection, new[] { NotConfirmed }); + } + + var result = await _providers.RemoveAsync(form.Id, user.UserName, cancellationToken); + if (!result.Succeeded) return await FailAsync(caller, ProvidersSection, result.Errors); + + return ToSection(ProvidersSection, $"Removed the provider {form.Id?.Trim()}. Restart BaGet to apply it."); + } + + /// + /// Sets the lowest level logged for one source (a namespace prefix); applies live. Confirmed with the password like a save, + /// refused with HTTP 503 while the is closed. + /// + public Task> SetLogLevelAsync(ClaimsPrincipal caller, string? source, string? level, string? password, CancellationToken cancellationToken) + => ChangeLogLevelAsync(caller, source?.Trim(), level ?? string.Empty, password, "set", cancellationToken); + + /// Removes a per-source level saved on this page (one a configuration file sets is only given another level). + public Task> RemoveLogLevelAsync(ClaimsPrincipal caller, string? source, string? password, CancellationToken cancellationToken) + => ChangeLogLevelAsync(caller, source?.Trim(), null, password, "removed", cancellationToken); + + private async Task> ChangeLogLevelAsync( + ClaimsPrincipal caller, + string? source, + string? level, + string? password, + string verb, + CancellationToken cancellationToken) + { + if (!_settings.IsAvailable) return ScreenResult.NotFound(); + + ThrowIfClosed(); + + var user = await CurrentAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(user, password)) + { + return await FailAsync(caller, "Serilog", new[] { "The confirmation is incorrect, so nothing was changed." }); + } + + var result = await _settings.SetLogLevelOverrideAsync(source, level, user.UserName, cancellationToken); + if (!result.Succeeded) return await FailAsync(caller, "Serilog", result.Errors); + + return ToSection( + "Serilog", + level == null + ? $"The level of {source} was {verb}." + : $"The level of {source} was {verb} to {LogLevelOverrides.NormalizeLevel(level)}."); + } + + /// + /// Sends one test span to the Telemetry section's posted, unsaved endpoint, protocol and headers and shows the + /// outcome; nothing is saved. Confirmed like a save (a test sends the headers, which may hold a credential, to an address the + /// administrator chose). A blank headers field keeps the saved headers unless "Clear" is ticked. Not refused while the + /// is closed: it writes nothing. + /// + public async Task> TestTelemetryAsync(ClaimsPrincipal caller, SettingsSubmission submission, CancellationToken cancellationToken) + { + if (!_settings.IsAvailable || _telemetry == null) return ScreenResult.NotFound(); + + var user = await CurrentAsync(caller); + if (user == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(user, submission.Password)) + { + return await FailAsync(caller, "Telemetry", new[] { "The confirmation is incorrect, so nothing was tested." }); + } + + string? Posted(string key) => submission.Has(SettingsForm.ValuePrefix + key) ? submission.Field(SettingsForm.ValuePrefix + key).ToString().Trim() : null; + + var headers = submission.Has(SettingsForm.ClearPrefix + "Telemetry:Otlp:Headers") + ? string.Empty + : Posted("Telemetry:Otlp:Headers") is { Length: > 0 } typed ? typed : null; + + var model = new AdminSettingsViewModel + { + TelemetryTest = await _telemetry.TestAsync( + Posted("Telemetry:Otlp:Endpoint"), + Posted("Telemetry:Otlp:Protocol"), + headers, + cancellationToken), + }; + await LoadAsync(model, caller); + Select(model, null, "Telemetry", locked: true); + + return ScreenResult.Ok(model); + } + + private static void Select(AdminSettingsViewModel model, string? requested, string? failedSection = null, bool locked = false) + { + string? Find(string? value) => value == null ? null : model.Ids.FirstOrDefault(i => string.Equals(i, value, StringComparison.OrdinalIgnoreCase)); + + var fromKey = failedSection != null && model.TryGetId(failedSection, out var failed) + ? failed + : failedSection != null ? Find(failedSection) : null; + + model.SelectionLocked = locked && fromKey != null; + model.SelectedId = fromKey ?? Find(requested) ?? (model.Sections.Count > 0 ? model.SectionId(model.Sections[0].Key) : string.Empty); + } + + /// Back to the screen showing : ?section=id (the server renders it) and #id (the browser keeps it). + private static ScreenResult ToSection(string section, string message) + { + var id = AdminSettingsViewModel.BuildId(section); + + return ScreenResult.GoTo(new ScreenNext(Screen, Route(("section", id)), message, Fragment: id)); + } + + /// + /// The copy a Database section asks for, or null when it is an ordinary save: neither the type nor the + /// connection string is set to a new value, either database is not relational (AzureTable), or it is the + /// database already running. + /// + private DatabaseCopyRequest? PlanCopy(IReadOnlyDictionary changes, string? actor) + { + string? Changed(string key, out bool reset) + { + reset = false; + foreach (var change in changes) + { + if (!string.Equals(change.Key.Key, key, StringComparison.OrdinalIgnoreCase)) continue; + + reset = change.Value == null; + return change.Value as string; + } + + return null; + } + + var type = Changed("Database:Type", out var typeReset); + var connection = Changed("Database:ConnectionString", out var connectionReset); + if (typeReset || connectionReset) return null; + if (type == null && connection == null) return null; + + type ??= _configuration["Database:Type"]; + connection ??= _configuration["Database:ConnectionString"]; + var mySqlVersion = Changed("Database:MySqlServerVersion", out _) ?? _configuration["Database:MySqlServerVersion"]; + + if (string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(connection)) return null; + if (!_copier.IsRelational(_copier.CurrentRelationalType) || !_copier.IsRelational(type)) return null; + if (_copier.IsCurrentDatabase(type, connection)) return null; + + return new DatabaseCopyRequest(type, connection, mySqlVersion, changes, actor); + } + + private async Task> FailAsync(ClaimsPrincipal caller, string section, IReadOnlyList errors) + { + var model = new AdminSettingsViewModel { Errors = errors, ErrorSection = section }; + await LoadAsync(model, caller); + Select(model, null, section, locked: true); + + return ScreenResult.Invalid( + model, + new Dictionary { [string.Empty] = errors.ToArray() }); + } + + private async Task LoadAsync(AdminSettingsViewModel model, ClaimsPrincipal caller) + { + var states = _settings.GetState(); + model.LoadError = _settings.OverridesError; + model.OverridesPath = _settings.OverridesPath; + + model.Sections = states + .GroupBy(s => s.Descriptor.Section ?? string.Empty, StringComparer.OrdinalIgnoreCase) + .OrderBy(g => g.Key.Length == 0 ? 0 : 1) + .ThenBy(g => g.Key, StringComparer.OrdinalIgnoreCase) + .ToList(); + var ids = new Dictionary(StringComparer.Ordinal); + var used = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var group in model.Sections) + { + var id = AdminSettingsViewModel.BuildId(group.Key); + var candidate = id; + for (var n = 2; !used.Add(candidate); n++) candidate = id + "-" + n; + ids[group.Key] = candidate; + } + model.SetIds(ids); + model.LogLevels = _settings.GetLogLevelOverrides(); + model.TelemetrySignals = _telemetry?.GetStatus(); + model.SignInProviders = _providers.List(); + model.PendingRestart = states.Where(s => s.PendingRestart).Select(s => s.Descriptor.Key).Concat(_providers.PendingRestartKeys()).ToList(); + model.CanCopyDatabase = _copier.CurrentRelationalType != null; + model.CopyTargetTypes = _copier.RelationalTypes; + model.CopyStatus = _copier.Status; + + await Confirmation.LoadAsync(model, caller); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminUseCaseBase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminUseCaseBase.cs new file mode 100644 index 000000000..56e044e99 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminUseCaseBase.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// What the use cases of the administration screens share: the signed-in user, the administrator's password confirmation, the read-only gate and +/// the "go back to" answer. A use case never sees the request: its inputs are the caller (), a form DTO and a cancellation token. +/// +public abstract class AdminUseCaseBase +{ + /// The refusal shown when the administrator's password (or recent sign-in) is not right. + protected const string NotConfirmed = "The confirmation is incorrect, so nothing was changed."; + + /// Creates the base. + protected AdminUseCaseBase(UserManager users, PasswordConfirmation confirmation, MaintenanceGate? gate) + { + Users = users ?? throw new ArgumentNullException(nameof(users)); + Confirmation = confirmation ?? throw new ArgumentNullException(nameof(confirmation)); + Gate = gate; + } + + /// Users, passwords, tokens. + protected UserManager Users { get; } + + /// The password confirmation. + protected PasswordConfirmation Confirmation { get; } + + /// The read-only gate, or null where there is none. + protected MaintenanceGate? Gate { get; } + + /// Refuses (503, ) a write while the read-only gate is closed. + protected void ThrowIfClosed() => Gate?.ThrowIfClosed(); + + /// The signed-in user, or null (the global API key has no user). + protected Task CurrentAsync(ClaimsPrincipal caller) => Users.GetUserAsync(caller)!; + + /// Route values for a ; a null value is left out of the link. + protected static IReadOnlyDictionary Route(params (string Name, object? Value)[] values) + { + var route = new Dictionary(values.Length); + foreach (var (name, value) in values) route[name] = value; + + return route; + } + + /// The action is over: go to and show the message or the error there (the flash message). + protected static ScreenResult Back(ScreenRef screen, IReadOnlyDictionary? route, string? message, string? error) + => ScreenResult.GoTo(new ScreenNext(screen, route, message, error)); +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminUserDeletionUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminUserDeletionUseCase.cs new file mode 100644 index 000000000..598ba79d3 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminUserDeletionUseCase.cs @@ -0,0 +1,145 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Models.Users; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// An administrator deleting another account: what goes, what happens to the organizations and to the package IDs only that user +/// owned (leave them without owners, or delete them with all their versions), then a password confirmation. Never the +/// administrator's own account, and never the last administrator. +/// +public sealed class AdminUserDeletionUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef UsersScreen = ScreenCatalog.AdminUsers; + + private readonly AccountDeletionService _deletion; + private readonly IOptionsSnapshot _options; + + /// Creates the use case. + public AdminUserDeletionUseCase( + UserManager users, + PasswordConfirmation confirmation, + AccountDeletionService deletion, + IOptionsSnapshot options, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _deletion = deletion ?? throw new ArgumentNullException(nameof(deletion)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + private bool IsReadOnlyMode => _options.Value.IsReadOnlyMode; + + /// Shows what the deletion does. + public async Task> GetAsync(ClaimsPrincipal caller, string? name, CancellationToken cancellationToken) + { + var (user, refusal) = await FindTargetAsync(caller, name); + if (refusal != null) return refusal; + + var model = new DeleteUserViewModel { Name = name }; + await LoadAsync(model, user!, caller, cancellationToken); + + return ScreenResult.Ok(model); + } + + /// + /// Deletes the user after the administrator's password, then returns to the users. is "keep" (default) or "delete": + /// what to do with the IDs only this user owns. A refusal shows the screen again (). + /// + public async Task> DeleteAsync( + ClaimsPrincipal caller, + string? name, + string? soleOwned, + string? password, + CancellationToken cancellationToken) + { + ThrowIfClosed(); + var (user, refusal) = await FindTargetAsync(caller, name); + if (refusal != null) return refusal; + + var model = new DeleteUserViewModel { Name = name }; + if (soleOwned != null) model.SoleOwned = soleOwned; + + var current = await CurrentAsync(caller); + var deletePackages = string.Equals(model.SoleOwned, "delete", StringComparison.OrdinalIgnoreCase); + + // The same refusal as the package page's hard delete: read-only mode freezes package removal. + if (deletePackages && IsReadOnlyMode) + { + return await ShowAsync(model, DeleteUserViewModel.ReadOnlyMessage, user!, caller, cancellationToken); + } + + if (!await Confirmation.IsConfirmedAsync(current, password)) + { + return await ShowAsync(model, "The confirmation is incorrect, so the account was not deleted.", user!, caller, cancellationToken); + } + + var userName = user!.UserName; + var outcome = await _deletion.DeleteByAdministratorAsync(user, deletePackages, current?.UserName, cancellationToken); + + if (!outcome.Result.Succeeded) + { + return await ShowAsync(model, AccountSupportText.Describe(outcome.Result), user, caller, cancellationToken); + } + + string? error = null; + if (outcome.Failures.Count > 0) + { + error = "Could not delete: " + string.Join(", ", outcome.Failures) + ". They have no owners and are listed under Packages without owners."; + } + + return Back(UsersScreen, null, Summarize(userName, outcome), error); + } + + private async Task> ShowAsync(DeleteUserViewModel model, string error, BaGetUser user, ClaimsPrincipal caller, CancellationToken cancellationToken) + { + model.Error = error; + await LoadAsync(model, user, caller, cancellationToken); + + return ScreenResult.Invalid(model, error); + } + + private static string Summarize(string? name, AdminDeletionResult outcome) + { + var text = $"{name} was deleted."; + if (outcome.DeletedPackageIds.Count > 0) text += $" Packages deleted: {string.Join(", ", outcome.DeletedPackageIds)}."; + if (outcome.KeptWithoutOwners.Count > 0) text += $" Packages left without owners: {string.Join(", ", outcome.KeptWithoutOwners)}."; + + return text; + } + + // The user, or what to answer instead: not found for no such user, back to the list for oneself. + private async Task<(BaGetUser? User, ScreenResult? Refusal)> FindTargetAsync(ClaimsPrincipal caller, string? name) + { + var current = await CurrentAsync(caller); + if (current == null) return (null, ScreenResult.SignIn()); + + var user = string.IsNullOrEmpty(name) ? null : await Users.FindByNameAsync(name); + if (user == null) return (null, ScreenResult.NotFound()); + + if (user.Id == current.Id) + { + return (null, Back(UsersScreen, null, null, "Delete your own account from your account settings.")); + } + + return (user, null); + } + + private async Task LoadAsync(DeleteUserViewModel model, BaGetUser user, ClaimsPrincipal caller, CancellationToken cancellationToken) + { + model.Preview = await _deletion.PreviewAdministratorDeletionAsync(user, cancellationToken); + model.LastAdministrator = (await _deletion.GetBlockersAsync(user, cancellationToken)).LastAdministrator; + model.IsReadOnlyMode = IsReadOnlyMode; + + await Confirmation.LoadAsync(model, caller); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminUserDetailUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminUserDetailUseCase.cs new file mode 100644 index 000000000..4d3e80fae --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminUserDetailUseCase.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.Models.Users; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// One account as an administrator sees it: the details, its API keys (revocable), its organizations and a link to its packages, +/// and the access model's view of it (groups, project roles, effective permissions per repository). Revoking a key, approving the +/// account and changing group membership ask for the administrator's password and are refused with 503 while the +/// is closed. +/// +public sealed class AdminUserDetailUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef Screen = ScreenCatalog.AdminUserDetail; + + private readonly IContext _context; + private readonly ApiKeyService _apiKeys; + private readonly PackageOwnershipService _ownership; + private readonly AccountApprovalService _approvals; + private readonly IAccessAdministration _access; + private readonly IAccessEvaluator _evaluator; + private readonly IRepositoryService _repositories; + private readonly ILogger _logger; + + /// Creates the use case. + public AdminUserDetailUseCase( + UserManager users, + PasswordConfirmation confirmation, + IContext context, + ApiKeyService apiKeys, + PackageOwnershipService ownership, + AccountApprovalService approvals, + IAccessAdministration access, + IAccessEvaluator evaluator, + IRepositoryService repositories, + ILogger logger, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _apiKeys = apiKeys ?? throw new ArgumentNullException(nameof(apiKeys)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _approvals = approvals ?? throw new ArgumentNullException(nameof(approvals)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// Shows the account; not found for an unknown user. is the package ID to evaluate the permissions for. + public async Task> GetAsync(ClaimsPrincipal caller, string? name, string? package, CancellationToken cancellationToken) + { + var model = new UserDetailViewModel { Name = name, Package = package }; + + return await LoadAsync(model, caller, cancellationToken) + ? ScreenResult.Ok(model) + : ScreenResult.NotFound(); + } + + /// Enables the account when it waits for approval, like the Users screen's Approve (password, gate). + public async Task> ApproveAsync(ClaimsPrincipal caller, string? name, string? password, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var user = await FindAsync(name); + if (user == null) return ScreenResult.NotFound(); + + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + string? message = null, error = null; + if (!await Confirmation.IsConfirmedAsync(current, password)) + { + error = NotConfirmed; + } + else + { + switch (await _approvals.ApproveAsync(user.UserName, current.UserName, cancellationToken)) + { + case AccountApprovalResult.Approved: + message = $"{user.UserName} was approved and can sign in."; + break; + case AccountApprovalResult.NotPending: + message = $"{user.UserName} was not waiting for approval."; + break; + default: + error = $"{user.UserName} was changed or removed meanwhile, so nothing was approved."; + break; + } + } + + return Back(user, message, error); + } + + /// Revokes one of the account's API keys. + public async Task> RevokeKeyAsync(ClaimsPrincipal caller, string? name, int key, string? password, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var user = await FindAsync(name); + if (user == null) return ScreenResult.NotFound(); + + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + string? message = null, error = null; + if (!await Confirmation.IsConfirmedAsync(current, password)) + { + error = NotConfirmed; + } + else if (await _apiKeys.RevokeAsync(user.Id, key, cancellationToken)) + { + _logger.LogWarning("{Admin} revoked API key {Key} of {User}", current.UserName, key, user.UserName); + message = "The API key was revoked."; + } + else + { + error = $"{user.UserName} has no such API key."; + } + + return Back(user, message, error); + } + + /// Adds the account to a group. + public Task> AddGroupAsync(ClaimsPrincipal caller, string? name, string? group, string? password, CancellationToken cancellationToken) + => ChangeGroupAsync(caller, name, group, password, add: true, cancellationToken); + + /// Removes the account from a group. + public Task> RemoveGroupAsync(ClaimsPrincipal caller, string? name, string? group, string? password, CancellationToken cancellationToken) + => ChangeGroupAsync(caller, name, group, password, add: false, cancellationToken); + + private static ScreenResult Back(BaGetUser user, string? message, string? error) + => Back(Screen, Route(("name", user.UserName)), message, error); + + private async Task FindAsync(string? name) + => string.IsNullOrEmpty(name) ? null : await Users.FindByNameAsync(name); + + private async Task> ChangeGroupAsync( + ClaimsPrincipal caller, + string? name, + string? group, + string? password, + bool add, + CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var user = await FindAsync(name); + if (user == null || _context is NullContext) return ScreenResult.NotFound(); + + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + string? message = null, error = null; + if (!await Confirmation.IsConfirmedAsync(current, password)) + { + error = NotConfirmed; + } + else + { + try + { + if (add) + { + await _access.AddGroupMemberAsync(group ?? string.Empty, user.Id, current.UserName, cancellationToken); + message = $"{user.UserName} was added to {group}."; + } + else + { + await _access.RemoveGroupMemberAsync(group ?? string.Empty, user.Id, current.UserName, cancellationToken); + message = $"{user.UserName} was removed from {group}."; + } + } + catch (AccessModelException e) + { + error = e.Message; + } + } + + return Back(user, message, error); + } + + private async Task LoadAsync(UserDetailViewModel model, ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var account = await FindAsync(model.Name); + if (account == null) return false; + + model.Account = new UserAccountInfo(account.UserName, account.Email, account.Created, account.IsAdministrator, account.PendingApproval); + + await LoadAccessAsync(model, account, cancellationToken); + + var keys = await _apiKeys.ListAsync(account.Id, cancellationToken); + var repositories = await _apiKeys.RepositoryNamesAsync(keys, cancellationToken); + model.Keys = keys + .Select(key => new UserKeyRow( + key.Key, + key.Description, + key.Scopes ?? Array.Empty(), + key.PackageGlobPattern, + key.Created, + key.Expires, + ApiKeyService.DescribeRepositories(repositories.GetValueOrDefault(key.Key)))) + .ToList(); + model.Organizations = await _ownership.GetOrganizationsAsync(account.Id, cancellationToken) ?? (IReadOnlyList)Array.Empty(); + model.OwnedPackageIds = await _ownership.CountOwnedPackageIdsAsync(account.UserName, cancellationToken); + + await Confirmation.LoadAsync(model, caller); + + return true; + } + + // The access model's view of the account: groups, project roles and the effective permissions per repository. + private async Task LoadAccessAsync(UserDetailViewModel model, BaGetUser account, CancellationToken cancellationToken) + { + model.ModelAvailable = _context is not NullContext; + if (!model.ModelAvailable) return; + + var package = string.IsNullOrWhiteSpace(model.Package) ? null : model.Package.Trim(); + + model.Groups = await _access.GroupsOfUserAsync(account.Id, cancellationToken); + model.ProjectRoles = await _access.ProjectRolesOfUserAsync(account.Id, cancellationToken); + + // What the account would be allowed through a session: its administrator flag is the only override. + var principal = new BaGetPrincipal(account.Id, account.UserName, isSuperuser: false, ApiKeyScopes.All, "*", account.IsAdministrator); + var rows = new List(); + foreach (var repository in await _repositories.ListAsync(cancellationToken)) + { + rows.Add(new RepositoryAccessRow(repository, await _evaluator.ExplainAsync(principal, repository, package, cancellationToken))); + } + + model.Access = rows + .OrderBy(r => r.Repository.IsDefault ? 0 : 1) + .ThenBy(r => r.Repository.Name, StringComparer.Ordinal) + .ToList(); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/AdminUsersUseCase.cs b/src/BaGet.Identity.Application/UseCases/Admin/AdminUsersUseCase.cs new file mode 100644 index 000000000..ff478b1d0 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/AdminUsersUseCase.cs @@ -0,0 +1,352 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Email; +using BaGet.Identity.Application.Models.Users; +using BaGet.Identity.Application.Services.Accounts; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// The Users screen: lists the accounts and lets an administrator approve, promote or demote them, create an account, reset a +/// password (a generated one shown once, or a link mailed to the user). Every action asks for the administrator's password again, +/// and none is offered or accepted for the administrator's own account (that stays on /account/settings). +/// +public sealed class AdminUsersUseCase : AdminUseCaseBase +{ + private static readonly ScreenRef Screen = ScreenCatalog.AdminUsers; + + private readonly IContext _context; + private readonly AvatarService _avatars; + private readonly AccountApprovalService _approvals; + private readonly AccountRecoveryService _recovery; + private readonly AdminUserCreationService _creation; + private readonly AdministratorService _administrators; + private readonly IOptions _email; + private readonly IScreenLinks _links; + private readonly IServiceProvider _services; + private readonly ILogger _logger; + + /// Creates the use case. + public AdminUsersUseCase( + UserManager users, + PasswordConfirmation confirmation, + IContext context, + AvatarService avatars, + AccountApprovalService approvals, + AccountRecoveryService recovery, + AdminUserCreationService creation, + AdministratorService administrators, + IOptions email, + IScreenLinks links, + IServiceProvider services, + ILogger logger, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _avatars = avatars ?? throw new ArgumentNullException(nameof(avatars)); + _approvals = approvals ?? throw new ArgumentNullException(nameof(approvals)); + _recovery = recovery ?? throw new ArgumentNullException(nameof(recovery)); + _creation = creation ?? throw new ArgumentNullException(nameof(creation)); + _administrators = administrators ?? throw new ArgumentNullException(nameof(administrators)); + _email = email ?? throw new ArgumentNullException(nameof(email)); + _links = links ?? throw new ArgumentNullException(nameof(links)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private bool EmailConfigured => _email.Value.IsConfigured; + + /// Lists the users. + public async Task> GetAsync(ClaimsPrincipal caller, string? q, int pageNumber, CancellationToken cancellationToken) + { + var model = new UsersViewModel { Q = q, PageNumber = pageNumber }; + await LoadAsync(model, caller, cancellationToken); + + return ScreenResult.Ok(model); + } + + /// Enables a self-registered account that waits for approval. Asks the password; 503 while the gate is closed. + public async Task> ApproveAsync(ClaimsPrincipal caller, UserChange change, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + string? message = null, error = null; + if (!await Confirmation.IsConfirmedAsync(current, change.Password)) + { + error = NotConfirmed; + } + else + { + var userName = change.UserName!; + switch (await _approvals.ApproveAsync(userName, current.UserName, cancellationToken)) + { + case AccountApprovalResult.Approved: + message = $"{userName} was approved and can sign in."; + break; + case AccountApprovalResult.NotPending: + message = $"{userName} was not waiting for approval."; + break; + case AccountApprovalResult.Conflict: + error = $"{userName} was changed or removed meanwhile, so nothing was approved. Reload the list."; + break; + default: + error = "There is no user with that name."; + break; + } + } + + return BackToUsers(change.Q, change.PageNumber, message, error); + } + + /// Makes a user an administrator. + public Task> PromoteAsync(ClaimsPrincipal caller, UserChange change, CancellationToken cancellationToken) + => ChangeAsync(caller, change, promote: true, cancellationToken); + + /// Removes a user's administrator flag. + public Task> DemoteAsync(ClaimsPrincipal caller, UserChange change, CancellationToken cancellationToken) + => ChangeAsync(caller, change, promote: false, cancellationToken); + + /// + /// Replaces the user's password with a generated one and shows it once. The answer is the screen itself (Ok with + /// ) rather than a redirect, so the password never goes through a flash message or a cookie; the + /// caller must make the response uncacheable. + /// + public async Task> ResetPasswordAsync(ClaimsPrincipal caller, UserChange change, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + var refusal = await RefuseAsync(current, change.UserName, change.Password); + if (refusal != null) return BackToUsers(change.Q, change.PageNumber, null, refusal); + + if (string.IsNullOrWhiteSpace(change.UserName)) return BackToUsers(change.Q, change.PageNumber, null, "There is no user with that name."); + + var generated = await _recovery.ResetPasswordAsync(change.UserName!, cancellationToken, change.ResetEmail); + if (generated == null) return BackToUsers(change.Q, change.PageNumber, null, "There is no user with that name."); + + _logger.LogWarning("{Admin} reset the password of {User}", current.UserName, change.UserName); + + var model = new UsersViewModel + { + Q = change.Q, + PageNumber = change.PageNumber, + GeneratedPassword = generated, + GeneratedFor = change.UserName, + }; + await LoadAsync(model, caller, cancellationToken); + + return ScreenResult.Ok(model); + } + + /// Mails the user a password reset link. Only while SMTP is configured, and only to a user with an address. + public async Task> SendResetLinkAsync(ClaimsPrincipal caller, UserChange change, CancellationToken cancellationToken) + { + if (!EmailConfigured) return ScreenResult.NotFound(); + + ThrowIfClosed(); + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + var refusal = await RefuseAsync(current, change.UserName, change.Password); + if (refusal != null) return BackToUsers(change.Q, change.PageNumber, null, refusal); + + string? message = null, error = null; + var user = string.IsNullOrWhiteSpace(change.UserName) ? null : await Users.FindByNameAsync(change.UserName); + if (user == null) + { + error = "There is no user with that name."; + } + else if (string.IsNullOrEmpty(user.Email)) + { + error = $"{user.UserName} has no email address, so no link can be sent."; + } + else + { + // No rate limiter: an administrator acts, and no one can use this to probe for accounts. + var template = _links.AbsoluteLink(ScreenCatalog.AccountResetPassword, PasswordResetLinkSender.Template); + if (PasswordResetLinkSender.TryEnqueue(_services, user.Id, template)) + { + _logger.LogWarning("{Admin} sent a password reset link to {User}", current.UserName, user.UserName); + message = $"Reset link sent to {UsersViewModel.MaskEmail(user.Email)}."; + } + else + { + error = "The mail queue is full. Try again in a moment."; + } + } + + return BackToUsers(change.Q, change.PageNumber, message, error); + } + + /// + /// Creates an account. The password is typed, generated (shown once on this response, like a reset) or, with + /// , unknown to everyone while the user is mailed a link to choose their own. Asks for the + /// administrator's password; refused with 503 while the is closed. + /// + public async Task> CreateAsync(ClaimsPrincipal caller, UserCreation creation, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(current, creation.Password)) + { + return BackToUsers(creation.Q, creation.PageNumber, null, NotConfirmed); + } + + if (creation.Invite && (!EmailConfigured || string.IsNullOrWhiteSpace(creation.NewEmail))) + { + return BackToUsers( + creation.Q, + creation.PageNumber, + null, + EmailConfigured + ? "An invitation is mailed to the user, so an email address is required." + : "Email is not configured, so no invitation can be sent. Give a password or generate one."); + } + + var mode = creation.Invite + ? NewUserPasswordMode.Invited + : string.IsNullOrEmpty(creation.NewPassword) ? NewUserPasswordMode.Generated : NewUserPasswordMode.Given; + var created = await _creation.CreateAsync(creation.NewUserName, creation.NewEmail, mode, creation.NewPassword, cancellationToken); + if (!created.Succeeded) return BackToUsers(creation.Q, creation.PageNumber, null, created.Error); + + _logger.LogWarning("{Admin} created the user {User}", current.UserName, created.User!.UserName); + + if (mode == NewUserPasswordMode.Generated) + { + var model = new UsersViewModel + { + Q = creation.Q, + PageNumber = creation.PageNumber, + GeneratedPassword = created.GeneratedPassword, + GeneratedFor = created.User.UserName, + GeneratedForNewUser = true, + }; + await LoadAsync(model, caller, cancellationToken); + + return ScreenResult.Ok(model); + } + + string message; + if (mode == NewUserPasswordMode.Invited) + { + var template = _links.AbsoluteLink(ScreenCatalog.AccountResetPassword, PasswordResetLinkSender.Template); + message = PasswordResetLinkSender.TryEnqueue(_services, created.User.Id, template) + ? $"{created.User.UserName} was created. An invitation was sent to {UsersViewModel.MaskEmail(created.User.Email)}." + : $"{created.User.UserName} was created, but the mail queue is full, so no invitation was sent. Use Reset password, Email a reset link."; + } + else + { + message = $"{created.User.UserName} was created."; + } + + return BackToUsers(creation.Q, creation.PageNumber, message, null); + } + + // Why a reset may not go ahead, or null. + private async Task RefuseAsync(BaGetUser current, string? userName, string? password) + { + if (string.Equals(current.UserName, userName, StringComparison.OrdinalIgnoreCase)) + { + return "Reset your own password from your account settings."; + } + + return await Confirmation.IsConfirmedAsync(current, password) ? null : NotConfirmed; + } + + private static ScreenResult BackToUsers(string? q, int pageNumber, string? message, string? error) + => Back(Screen, Route(("q", q), ("p", pageNumber > 1 ? pageNumber : (int?)null)), message, error); + + private async Task> ChangeAsync(ClaimsPrincipal caller, UserChange change, bool promote, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + string? message = null, error = null; + if (!await Confirmation.IsConfirmedAsync(current, change.Password)) + { + error = NotConfirmed; + } + else + { + var userName = change.UserName!; + var result = promote + ? await _administrators.PromoteAsync(userName, current.UserName, cancellationToken) + : await _administrators.DemoteAsync(userName, current.UserName, cancellationToken); + + switch (result) + { + case AdministratorChange.Changed: + message = promote ? $"{userName} is now an administrator." : $"{userName} is no longer an administrator."; + break; + case AdministratorChange.Unchanged: + message = promote ? $"{userName} is already an administrator." : $"{userName} is not an administrator."; + break; + case AdministratorChange.UserNotFound: + error = "There is no user with that name."; + break; + case AdministratorChange.LastAdministrator: + error = "The last administrator cannot be demoted. Promote another user first."; + break; + } + } + + return BackToUsers(change.Q, change.PageNumber, message, error); + } + + private async Task LoadAsync(UsersViewModel model, ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var query = _context.Users.AsNoTracking().AsQueryable(); + if (!string.IsNullOrWhiteSpace(model.Q)) + { + var term = model.Q.Trim().ToLowerInvariant(); + #pragma warning disable CS8602 + query = query.Where(u => u.UserName.ToLower().Contains(term)); + #pragma warning restore CS8602 + } + + var total = await query.CountAsync(cancellationToken); + model.PageCount = Math.Max(1, (total + UsersViewModel.PageSize - 1) / UsersViewModel.PageSize); + model.PageNumber = Math.Min(Math.Max(1, model.PageNumber), model.PageCount); + + var page = await query + .OrderBy(u => u.UserName) + .Skip((model.PageNumber - 1) * UsersViewModel.PageSize) + .Take(UsersViewModel.PageSize) + .Select(u => new { u.UserName, u.Email, u.Created, u.IsAdministrator, u.PendingApproval }) + .ToListAsync(cancellationToken); + + var avatars = await _avatars.GetUrlsAsync(page.Select(u => u.UserName).ToList(), 24, cancellationToken); + + #pragma warning disable CS8620 + model.Users = page + .Select(u => new UserRow(u.UserName, u.Email, u.Created, u.IsAdministrator, avatars.GetValueOrDefault(u.UserName), u.PendingApproval)) + .ToList(); + #pragma warning restore CS8620 + + model.PendingCount = await _approvals.CountPendingAsync(cancellationToken); + model.CanEmailResetLink = EmailConfigured; + model.CanInvite = EmailConfigured; + + model.CurrentUserName = (await CurrentAsync(caller))?.UserName; + await Confirmation.LoadAsync(model, caller); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/OrganizationChangeOutcome.cs b/src/BaGet.Identity.Application/UseCases/Admin/OrganizationChangeOutcome.cs new file mode 100644 index 000000000..cc29991f1 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/OrganizationChangeOutcome.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.UseCases.Admin; + +/// What an organization change decided: the (possibly new) name of the organization and the message or error to show. +internal sealed class OrganizationChangeOutcome +{ + public string? Name { get; set; } + + public string? Message { get; set; } + + public string? Error { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/RemoveOrganizationMemberForm.cs b/src/BaGet.Identity.Application/UseCases/Admin/RemoveOrganizationMemberForm.cs new file mode 100644 index 000000000..da27fe876 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/RemoveOrganizationMemberForm.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.UseCases.Admin; + +/// What the "remove a member" (or "leave") form posts. +public sealed class RemoveOrganizationMemberForm +{ + /// The organization. + public string? Organization { get; set; } + + /// The member to remove. + public string? UserName { get; set; } +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/SettingsSubmission.cs b/src/BaGet.Identity.Application/UseCases/Admin/SettingsSubmission.cs new file mode 100644 index 000000000..322a65af7 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/SettingsSubmission.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using Microsoft.Extensions.Primitives; + +namespace BaGet.Identity.Application.UseCases.Admin; + +/// +/// The fields of a submitted Settings form, per setting key (v:<key> the value, reset:<key>, clear:<key>; a checkbox posts +/// true next to a hidden false, a list is one entry per line) and the section they belong to. The same shape whether it comes from the +/// page's form or from a JSON body. +/// +/// The section being saved (the empty section holds the top-level keys). +/// The administrator's password, asked again. +/// The posted fields; a field may repeat. +public sealed record SettingsSubmission(string? Section, string? Password, IReadOnlyDictionary Fields) +{ + /// The field with , as the form collection would hand it out. + internal StringValues Field(string name) => Fields.TryGetValue(name, out var values) ? new StringValues(values) : StringValues.Empty; + + internal bool Has(string name) => Fields.ContainsKey(name); +} diff --git a/src/BaGet.Identity.Application/UseCases/Admin/UserChange.cs b/src/BaGet.Identity.Application/UseCases/Admin/UserChange.cs new file mode 100644 index 000000000..128e3153a --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/UserChange.cs @@ -0,0 +1,9 @@ +namespace BaGet.Identity.Application.UseCases.Admin; + +/// A change to one account from the Users screen, with the list's filter and page to come back to. +/// The account the change applies to. +/// The administrator's password, asked again. +/// The list's user-name filter. +/// The list's page. +/// For a password reset: the address to mail the new password to, if the administrator typed one. +public sealed record UserChange(string? UserName, string? Password, string? Q = null, int PageNumber = 1, string? ResetEmail = null); diff --git a/src/BaGet.Identity.Application/UseCases/Admin/UserCreation.cs b/src/BaGet.Identity.Application/UseCases/Admin/UserCreation.cs new file mode 100644 index 000000000..a354db0bb --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Admin/UserCreation.cs @@ -0,0 +1,11 @@ +namespace BaGet.Identity.Application.UseCases.Admin; + +/// A new account from the Users screen. +/// The new account's name. +/// Its address, or null. +/// The password typed; empty means generate one (unless ). +/// Mail the user a link to choose their own password. +/// The administrator's password, asked again. +/// The list's user-name filter. +/// The list's page. +public sealed record UserCreation(string? NewUserName, string? NewEmail, string? NewPassword, bool Invite, string? Password, string? Q = null, int PageNumber = 1); diff --git a/src/BaGet.Identity.Application/UseCases/Packages/AdminPackageRows.cs b/src/BaGet.Identity.Application/UseCases/Packages/AdminPackageRows.cs new file mode 100644 index 000000000..5b1ef2a5c --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/AdminPackageRows.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using BaGet.Identity.Application.Models.Packages; + +namespace BaGet.Identity.Application.UseCases.Packages; + +internal static class AdminPackageRows +{ + /// + /// Summarises and attaches each one's owners: one query for the versions, one for the owners. + /// Works in the repository is scoped to, whose name rows carry. + /// + internal static async Task> BuildAsync( + IContext context, + IReadOnlyList? ids, + CancellationToken cancellationToken, + string repositoryName = Repository.DefaultName) + { + #pragma warning disable CS8602 + if (ids.Count == 0) return Array.Empty(); + #pragma warning restore CS8602 + + var summaries = PackagesModel.Summarise( + ids, + await PackagesModel.ListVersionsAsync(context, ids, cancellationToken)); + + var lowered = ids.Select(id => id.ToLowerInvariant()).ToList(); + #pragma warning disable CS8602, CS8604 + var owners = await context.PackageOwners + .AsNoTracking() + .Where(o => lowered.Contains(o.PackageId.ToLower())) + .Select(o => new { o.PackageId, o.OwnerName }) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + #pragma warning disable CS8621, CS8714 + var byId = owners + .GroupBy(o => o.PackageId, StringComparer.OrdinalIgnoreCase) + .ToDictionary( + g => g.Key, + g => (IReadOnlyList)g.Select(o => o.OwnerName).OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList(), + StringComparer.OrdinalIgnoreCase); + #pragma warning restore CS8621, CS8714 + + return summaries + .Select(p => new AdminPackageRow(p, byId.TryGetValue(p.Id, out var names) ? names : Array.Empty(), repositoryName)) + .ToList(); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/AdminPackagesUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/AdminPackagesUseCase.cs new file mode 100644 index 000000000..f259cf028 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/AdminPackagesUseCase.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// The two package listings of the administrator: the package IDs that have no owner in any repository (those that predate +/// accounts, and those left behind when their only owner's account was deleted; only administrators and the global API key may +/// change them), and the IDs one user owns. +/// +public sealed class AdminPackagesUseCase +{ + private readonly IContext _context; + private readonly IRepositoryService _repositories; + private readonly IServiceScopeFactory _scopes; + private readonly PackageOwnershipService _ownership; + private readonly UserManager _users; + + /// Creates the use case. + public AdminPackagesUseCase( + IContext context, + IRepositoryService repositories, + IServiceScopeFactory scopes, + PackageOwnershipService ownership, + UserManager users) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + } + + /// Lists the ownerless IDs of every repository, being one-based. + public async Task> GetOwnerlessAsync(int pageNumber, CancellationToken cancellationToken) + { + var model = new AdminPackagesViewModel { PageNumber = pageNumber }; + + // Ownership is per repository, so an ID is ownerless where nobody in that repository owns it. + #pragma warning disable CS8602, CS8604 + var ownerless = _context.Packages + .IgnoreQueryFilters() + .AsNoTracking() + .Where(p => !_context.PackageOwners.IgnoreQueryFilters() + .Any(o => o.RepositoryKey == p.RepositoryKey && o.PackageId.ToLower() == p.Id.ToLower())) + .Select(p => new { p.RepositoryKey, Id = p.Id.ToLower() }) + .Distinct(); + #pragma warning restore CS8602, CS8604 + + var total = await ownerless.CountAsync(cancellationToken); + model.PageCount = Math.Max(1, (total + AdminPackagesViewModel.PageSize - 1) / AdminPackagesViewModel.PageSize); + model.PageNumber = Math.Min(Math.Max(1, model.PageNumber), model.PageCount); + + var page = await ownerless + .OrderBy(o => o.Id) + .ThenBy(o => o.RepositoryKey) + .Skip((model.PageNumber - 1) * AdminPackagesViewModel.PageSize) + .Take(AdminPackagesViewModel.PageSize) + .ToListAsync(cancellationToken); + + var repositories = (await _repositories.ListAsync(cancellationToken)).ToDictionary(r => r.Key); + + // Each repository's rows are read in a scope pinned to it, which supplies its versions and owners. + var rows = new List(); + foreach (var group in page.GroupBy(o => o.RepositoryKey)) + { + if (!repositories.TryGetValue(group.Key, out var repository)) continue; + + using var scope = _scopes.CreateRepositoryScope(repository); + rows.AddRange(await AdminPackageRows.BuildAsync( + scope.ServiceProvider.GetRequiredService(), + group.Select(o => o.Id).ToList(), + cancellationToken, + repository.Name)); + } + + model.Packages = rows + .OrderBy(r => r.Package.Id, StringComparer.OrdinalIgnoreCase) + .ThenBy(r => r.RepositoryName, StringComparer.Ordinal) + .ToList(); + + return ScreenResult.Ok(model); + } + + /// Lists the user's packages; not found for an unknown user. + public async Task> GetUserAsync(string? name, CancellationToken cancellationToken) + { + var user = await _users.FindByNameAsync(name ?? string.Empty); + if (user == null) return ScreenResult.NotFound(); + + var ids = await _ownership.GetOwnedPackageIdsAsync(user.Id, user.UserName, cancellationToken); + + return ScreenResult.Ok(new UserPackagesViewModel + { + Name = user.UserName, + Packages = await AdminPackageRows.BuildAsync(_context, ids, cancellationToken), + }); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/ContactOwnersUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/ContactOwnersUseCase.cs new file mode 100644 index 000000000..4b4870881 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/ContactOwnersUseCase.cs @@ -0,0 +1,222 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Security.Claims; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.RateLimiting; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// Lets a signed-in user write to the owners of a package without learning their addresses. The message goes to every owning user and to the +/// administrators of every owning organization, one email each, with the sender in Reply-To. The screen needs accounts and mail (the caller's +/// gate); the sender needs a confirmed address, and is limited to one message per package per . +/// +public sealed class ContactOwnersUseCase +{ + private readonly PackageScreenServices _services; + private readonly IContext _context; + private readonly ContactRateLimiter _limiter; + private readonly IEmailMessageSender _mail; + private readonly ILogger _logger; + + /// Creates the use case. + public ContactOwnersUseCase( + PackageScreenServices services, + IContext context, + ContactRateLimiter limiter, + IEmailMessageSender mail, + ILogger logger) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _limiter = limiter ?? throw new ArgumentNullException(nameof(limiter)); + _mail = mail ?? throw new ArgumentNullException(nameof(mail)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// The GET handler: the form, 404 when the package has no owner. + public async Task> GetAsync(ClaimsPrincipal caller, string? id, CancellationToken cancellationToken) + { + var model = new ContactOwnersViewModel(); + + return await LoadAsync(caller, id, model, cancellationToken).ConfigureAwait(false) == null + ? ScreenResult.NotFound() + : ScreenResult.Ok(model); + } + + /// The POST handler: validates, finds the recipients, rate limits and sends. + /// The signed-in user. + /// The package ID from the address. + /// The message to send. + /// Whether the sender also gets a copy. + /// The cancellation token. + public async Task> SendAsync(ClaimsPrincipal caller, string? id, string? message, bool copyToSelf, CancellationToken cancellationToken) + { + var model = new ContactOwnersViewModel { Message = message, CopyToSelf = copyToSelf }; + + var owners = await LoadAsync(caller, id, model, cancellationToken).ConfigureAwait(false); + if (owners == null) return ScreenResult.NotFound(); + + var sender = await _services.Users.GetUserAsync(caller).ConfigureAwait(false); + if (sender == null) return ScreenResult.SignIn(); + + if (!model.SenderHasEmail) + { + model.Error = "Add an email address to your account and confirm it first, so the owners can reply."; + return ScreenResult.Ok(model); + } + + var errors = ScreenValidation.Validate(model); + if (errors.Count > 0) return ScreenResult.Invalid(model, errors); + + var recipients = await FindRecipientsAsync(owners, cancellationToken).ConfigureAwait(false); + if (recipients.Count == 0) + { + model.Error = "None of the owners can be reached by email."; + return ScreenResult.Ok(model); + } + + if (!_limiter.TryAcquire(sender.Id, model.PackageId)) + { + model.Error = "You can send one message per package every " + + (int)ContactRateLimiter.Window.TotalMinutes + + " minutes. Please try again later."; + return ScreenResult.Ok(model); + } + + var subject = $"Message about your package {model.PackageId}"; + var body = BuildBody(sender, model.PackageId, model.Message!.Trim(), copy: false); + var delivered = 0; + + foreach (var recipient in recipients) + { + try + { + #pragma warning disable CS8602 + await _mail.SendAsync(recipient, sender.Email.Trim(), sender.UserName, subject, body, cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8602 + delivered++; + } + catch (Exception e) + { + _logger.LogError(e, "Could not send a contact-owners message for {PackageId}.", model.PackageId); + } + } + + if (delivered == 0) + { + _limiter.Release(sender.Id, model.PackageId); + model.Error = "The message could not be sent. Please try again later."; + return ScreenResult.Ok(model); + } + + if (model.CopyToSelf) + { + try + { + #pragma warning disable CS8602 + await _mail.SendAsync( + sender.Email.Trim(), + replyTo: null, + replyToName: null, + subject: $"Copy of your message about {model.PackageId}", + textBody: BuildBody(sender, model.PackageId, model.Message!.Trim(), copy: true), + cancellationToken: cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8602 + } + catch (Exception e) + { + _logger.LogError(e, "Could not send the sender's copy of a contact-owners message for {PackageId}.", model.PackageId); + } + } + + model.Sent = true; + return ScreenResult.Ok(model); + } + + private async Task?> LoadAsync(ClaimsPrincipal caller, string? id, ContactOwnersViewModel model, CancellationToken cancellationToken) + { + var owners = await _services.Ownership.GetOwnersAsync(id, cancellationToken).ConfigureAwait(false); + if (owners.Count == 0) return null; + + model.PackageId = owners[0].PackageId; + + var user = await _services.Users.GetUserAsync(caller).ConfigureAwait(false); + model.SenderHasEmail = user != null && user.EmailConfirmed && IsDeliverable(user.Email); + + return owners; + } + + /// The confirmed addresses of the user owners and of the administrators of the owning organizations, each once. + private async Task> FindRecipientsAsync(IReadOnlyList owners, CancellationToken cancellationToken) + { + #pragma warning disable CS8602 + var names = owners.Select(o => o.OwnerName.ToLowerInvariant()).ToList(); + #pragma warning restore CS8602 + + #pragma warning disable CS8602 + var userIds = await _services.Users.Users + .AsNoTracking() + .Where(u => names.Contains(u.UserName.ToLower())) + .Select(u => u.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8602 + + #pragma warning disable CS8602, CS8604 + var adminIds = await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.IsAdmin && m.Organization != null && names.Contains(m.Organization.Name.ToLower())) + .Select(m => m.UserId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8602, CS8604 + + var ids = userIds.Concat(adminIds).Distinct().ToList(); + var emails = await _services.Users.Users + .AsNoTracking() + .Where(u => ids.Contains(u.Id) && u.EmailConfirmed) + .Select(u => u.Email) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + #pragma warning disable CS8602 + return emails + .Where(IsDeliverable) + .Select(e => e.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + #pragma warning restore CS8602 + } + + private static bool IsDeliverable(string? email) + => !string.IsNullOrWhiteSpace(email) && new EmailAddressAttribute().IsValid(email.Trim()); + + private static string BuildBody(BaGetUser sender, string? packageId, string message, bool copy) + { + var text = new StringBuilder(); + if (copy) + { + text.Append("This is a copy of the message you sent to the owners of ").Append(packageId).Append(".\n\n"); + } + else + { + text.Append(sender.UserName).Append(" sent you this message about the package ").Append(packageId) + .Append(". Reply to this email to answer them.\n\n"); + } + + text.Append("----\n").Append(message.Replace("\r\n", "\n").Replace('\r', '\n')).Append("\n----\n"); + if (!copy) + { + text.Append("\nYou received this because you own ").Append(packageId).Append(". Your address was not shown to the sender.\n"); + } + + return text.ToString(); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/DockerManageUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/DockerManageUseCase.cs new file mode 100644 index 000000000..af36a63e3 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/DockerManageUseCase.cs @@ -0,0 +1,226 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using BaGet.Identity.Application.Models.Packages; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// The delete tools of a Docker image: delete a tag, a manifest (with its tags), remove the layers no manifest uses, or delete the whole +/// image. Every change goes through after the same check the registry applies to a DELETE +/// (: the Delete action on the image, for the signed-in user's session principal, never a typed key), so the screen +/// can do what the same user's API key could through the registry routes and no more. Opening it needs Delete; every change also asks for the +/// password again, since it cannot be undone. Works in the request's repository. Scoped: runs once per request (see +/// ). +/// +public sealed class DockerManageUseCase +{ + /// What every write handler answers on a read-only server. + public const string ReadOnlyMessage = PackageScreenServices.ReadOnlyMessage; + + private readonly PackageScreenServices _services; + private readonly IOciRegistry _registry; + private readonly IOciAccess _access; + private readonly ILogger _logger; + + private bool _entered; + private string? _enteredImage; + private bool _enteredWrite; + private ScreenResult? _refusal; + + /// Creates the use case. + public DockerManageUseCase(PackageScreenServices services, IOciRegistry registry, IOciAccess access, ILogger logger) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// The check that runs before every handler: a valid image name, a local Docker repository, the Delete action on the image, the + /// maintenance gate and read-only mode for a write. Returns the answer that ends the request, or null to run the handler. + /// + /// The signed-in user. + /// The image name from the address (it may contain slashes). + /// Whether the request is a POST. + /// The cancellation token. + public async Task?> EnterAsync(ClaimsPrincipal caller, string? image, bool isWrite, CancellationToken cancellationToken) + { + if (_entered && _enteredImage == image && _enteredWrite == isWrite) return _refusal; + + _refusal = await CheckAsync(caller, image, isWrite, cancellationToken).ConfigureAwait(false); + _entered = true; + _enteredImage = image; + _enteredWrite = isWrite; + + return _refusal; + } + + private async Task?> CheckAsync(ClaimsPrincipal caller, string? image, bool isWrite, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image)) + { + return ScreenResult.NotFound(); + } + + // The tools exist where images are pushed: only a local Docker repository (a page of another format is 404, as the + // repository check says; the controller's own check can run before it). + var current = _services.Repository.Current; + if (current.Kind != RepositoryKind.Local || current.Format != RepositoryFormat.Docker) + { + return ScreenResult.NotFound(); + } + + // The rule of a DELETE on the registry: the Delete action on the image, for this user. + var principal = await _services.CallerAsync(caller).ConfigureAwait(false); + if (principal == null || !await _access.IsAllowedAsync(principal, current, image!, OciActions.Delete, cancellationToken).ConfigureAwait(false)) + { + return await _services.CanSeeAsync(caller, image, cancellationToken).ConfigureAwait(false) + ? ScreenResult.Forbidden() + : ScreenResult.NotFound(); + } + + if (isWrite) + { + // A write: refused while a database copy has the gate closed, and in read-only mode, for every handler at once. + _services.Services.GetService()?.ThrowIfClosed(); + + if (_services.IsReadOnlyMode) + { + var screen = await LoadAsync(caller, image, cancellationToken).ConfigureAwait(false); + screen.Message = ReadOnlyMessage; + screen.Failed = true; + + return ScreenResult.Ok(screen); + } + } + + return null; + } + + /// The GET handler: loads the image, 404 when it does not exist. + public async Task> GetAsync(ClaimsPrincipal caller, string? image, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, image, false, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var screen = await LoadAsync(caller, image, cancellationToken).ConfigureAwait(false); + + return screen.Info == null ? ScreenResult.NotFound() : ScreenResult.Ok(screen); + } + + private async Task LoadAsync(ClaimsPrincipal caller, string? image, CancellationToken cancellationToken) + { + var confirmation = await _services.ConfirmationAsync(caller, cancellationToken).ConfigureAwait(false); + + return new DockerManageViewModel + { + HasPassword = confirmation.HasPassword, + Reauthenticated = confirmation.Reauthenticated, + CanReauthenticate = confirmation.CanReauthenticate, + Image = image, + Info = await _registry.GetImageAsync(image!, cancellationToken).ConfigureAwait(false), + }; + } + + private async Task> DoneAsync(ClaimsPrincipal caller, string? image, string message, bool failed, CancellationToken cancellationToken) + { + var screen = await LoadAsync(caller, image, cancellationToken).ConfigureAwait(false); + screen.Message = message; + screen.Failed = failed; + + return ScreenResult.Ok(screen); + } + + /// Deletes a tag (the manifest it points at stays), after the password is confirmed. + public async Task> DeleteTagAsync(ClaimsPrincipal caller, string? image, string? tag, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, image, true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, image, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + if (!OciNames.IsValidTag(tag)) return await DoneAsync(caller, image, "Choose a tag.", failed: true, cancellationToken).ConfigureAwait(false); + + var deleted = await _registry.DeleteTagAsync(image!, tag!, cancellationToken).ConfigureAwait(false); + if (deleted) _logger.LogWarning("{User} deleted tag {Tag} of Docker image {Image}", caller.Identity?.Name, tag, image); + + return await DoneAsync(caller, image, deleted ? $"Tag {tag} is deleted." : "There is no such tag.", !deleted, cancellationToken).ConfigureAwait(false); + } + + /// Deletes a manifest with the tags that point at it, after the password is confirmed. + public async Task> DeleteManifestAsync(ClaimsPrincipal caller, string? image, string? digest, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, image, true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, image, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + if (!OciNames.IsValidDigest(digest)) return await DoneAsync(caller, image, "Choose a manifest.", failed: true, cancellationToken).ConfigureAwait(false); + + var deleted = await _registry.DeleteManifestAsync(image!, digest!, cancellationToken).ConfigureAwait(false); + if (deleted) _logger.LogWarning("{User} deleted manifest {Digest} of Docker image {Image}", caller.Identity?.Name, digest, image); + + return await DoneAsync(caller, image, deleted ? "The manifest and its tags are deleted." : "There is no such manifest.", !deleted, cancellationToken).ConfigureAwait(false); + } + + /// Removes the layers no manifest uses (older than the grace period), after the password is confirmed. + public async Task> PruneAsync(ClaimsPrincipal caller, string? image, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, image, true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, image, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + var result = await _registry.PruneAsync(image!, cancellationToken).ConfigureAwait(false); + if (result.Blobs > 0) _logger.LogWarning("{User} pruned {Count} unused layers of Docker image {Image}", caller.Identity?.Name, result.Blobs, image); + + return await DoneAsync( + caller, + image, + result.Blobs == 0 + ? "There was no unused layer old enough to remove." + : $"Removed {result.Blobs} unused layer{(result.Blobs == 1 ? string.Empty : "s")} ({result.Bytes:N0} bytes).", + failed: false, + cancellationToken).ConfigureAwait(false); + } + + /// Deletes the image with every manifest, tag and layer only it holds, after the password is confirmed. + public async Task> DeleteImageAsync(ClaimsPrincipal caller, string? image, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, image, true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, image, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + if (!await _registry.DeleteImageAsync(image!, cancellationToken).ConfigureAwait(false)) + { + return await DoneAsync(caller, image, "There is no such image.", failed: true, cancellationToken).ConfigureAwait(false); + } + + _logger.LogWarning("{User} deleted Docker image {Image}", caller.Identity?.Name, image); + + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.DockerImages)); + } + + /// Null when the signed-in user confirmed with their password, otherwise the screen to show. + private async Task?> RefuseUnconfirmedAsync(ClaimsPrincipal caller, string? image, string? password, CancellationToken cancellationToken) + { + var current = await _services.Users.GetUserAsync(caller).ConfigureAwait(false); + if (current == null) return ScreenResult.SignIn(); + + return await _services.IsConfirmedAsync(current, password, cancellationToken).ConfigureAwait(false) + ? null + : await DoneAsync(caller, image, "The confirmation is incorrect, so nothing was deleted.", failed: true, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/MavenManageUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/MavenManageUseCase.cs new file mode 100644 index 000000000..7ad02f615 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/MavenManageUseCase.cs @@ -0,0 +1,296 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// The owners' screen for a Maven artifact: its owners, versions and the files of the chosen one, with deletion of a file, a version or the +/// whole artifact, and the clean-up of old snapshot builds. Every change goes through as the signed-in user +/// (the session's principal, never a typed key), so the screen can do what the same user's API key could through the repository routes and no +/// more: the access model and ownership apply identically. Opening it takes ownership (directly or through an organization) or +/// administration; deleting also asks for the password again, since it cannot be undone. Works in the request's repository. Scoped: +/// runs once per request (see ). +/// +public sealed class MavenManageUseCase +{ + /// What every write handler answers on a read-only server. + public const string ReadOnlyMessage = PackageScreenServices.ReadOnlyMessage; + + private readonly PackageScreenServices _services; + private readonly IMavenRepository _maven; + private readonly ILogger _logger; + + private bool _entered; + private string? _enteredKey; + private bool _enteredWrite; + private ScreenResult? _refusal; + private string _group = string.Empty; + private string _artifact = string.Empty; + private string? _version; + private bool _isAdministrator; + private bool _actingAsAdministrator; + + /// Creates the use case. + public MavenManageUseCase(PackageScreenServices services, IMavenRepository maven, ILogger logger) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _maven = maven ?? throw new ArgumentNullException(nameof(maven)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private string Name => MavenNames.ArtifactName(_group, _artifact); + + /// + /// The check that runs before every handler: valid coordinates, a local Maven repository, ownership or administration, the maintenance + /// gate and read-only mode for a write. Returns the answer that ends the request, or null to run the handler. + /// + /// The signed-in user. + /// The group id from the address. + /// The artifact id from the address. + /// The version whose files are listed (version of the form or query), or null. + /// The handler about to run (for the administrator audit line). + /// Whether the request is a POST. + /// The cancellation token. + public async Task?> EnterAsync(ClaimsPrincipal caller, string? group, string? artifact, string? version, string? handler, bool isWrite, CancellationToken cancellationToken) + { + var key = group + "\n" + artifact + "\n" + version; + if (_entered && _enteredKey == key && _enteredWrite == isWrite) return _refusal; + + _refusal = await CheckAsync(caller, group, artifact, version, handler, isWrite, cancellationToken).ConfigureAwait(false); + _entered = true; + _enteredKey = key; + _enteredWrite = isWrite; + + return _refusal; + } + + private async Task?> CheckAsync(ClaimsPrincipal caller, string? group, string? artifact, string? version, string? handler, bool isWrite, CancellationToken cancellationToken) + { + if (!MavenNames.IsValidGroupId(group) || !MavenNames.IsValidArtifactId(artifact) || (version != null && !MavenNames.IsValidVersion(version))) + { + return ScreenResult.NotFound(); + } + + _group = group!; + _artifact = artifact!; + _version = version; + + // Owners and the owner tools exist where artifacts are deployed: only a local Maven repository (a page of another format is + // 404, as the repository check says; the controller's own check can run before it). + var current = _services.Repository.Current; + if (current.Kind != RepositoryKind.Local || current.Format != RepositoryFormat.Maven) + { + return ScreenResult.NotFound(); + } + + var isOwner = await _services.Ownership.IsOwnerAsync(_services.Users.GetUserId(caller), caller.Identity?.Name, Name, cancellationToken).ConfigureAwait(false); + _isAdministrator = await _services.Administrators.IsAdministratorAsync(caller, cancellationToken).ConfigureAwait(false); + if (!isOwner && !_isAdministrator) + { + return await _services.CanSeeAsync(caller, Name, cancellationToken).ConfigureAwait(false) + ? ScreenResult.Forbidden() + : ScreenResult.NotFound(); + } + + _actingAsAdministrator = _isAdministrator && !isOwner; + + if (isWrite) + { + // A write: refused while a database copy has the gate closed, and in read-only mode, for every handler at once. + _services.Services.GetService()?.ThrowIfClosed(); + + if (_services.IsReadOnlyMode) + { + var screen = await LoadAsync(caller, cancellationToken).ConfigureAwait(false); + screen.Message = ReadOnlyMessage; + screen.Failed = true; + + return ScreenResult.Ok(screen); + } + + if (_actingAsAdministrator) + { + _logger.LogWarning("Administrator {Admin} ran {Handler} on Maven artifact {Artifact}", caller.Identity?.Name, handler, Name); + } + } + + return null; + } + + /// The GET handler: loads the artifact, 404 when it does not exist. + public async Task> GetAsync(ClaimsPrincipal caller, string? group, string? artifact, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, group, artifact, version, null, false, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var screen = await LoadAsync(caller, cancellationToken).ConfigureAwait(false); + + return screen.Info == null ? ScreenResult.NotFound() : ScreenResult.Ok(screen); + } + + private async Task LoadAsync(ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var confirmation = await _services.ConfirmationAsync(caller, cancellationToken).ConfigureAwait(false); + var info = await _maven.GetArtifactAsync(_group, _artifact, cancellationToken).ConfigureAwait(false); + + return new MavenManageViewModel + { + IsAdministrator = _isAdministrator, + ActingAsAdministrator = _actingAsAdministrator, + HasPassword = confirmation.HasPassword, + Reauthenticated = confirmation.Reauthenticated, + CanReauthenticate = confirmation.CanReauthenticate, + Group = _group, + Artifact = _artifact, + Version = _version, + Info = info, + Selected = info != null && _version != null && info.Versions.Any(v => v.Version == _version) + ? await _maven.GetVersionAsync(_group, _artifact, _version, cancellationToken).ConfigureAwait(false) + : null, + Owners = await _services.Ownership.GetOwnersAsync(Name, cancellationToken).ConfigureAwait(false), + }; + } + + private async Task> DoneAsync(ClaimsPrincipal caller, string message, bool failed, CancellationToken cancellationToken) + { + var screen = await LoadAsync(caller, cancellationToken).ConfigureAwait(false); + screen.Message = message; + screen.Failed = failed; + + return ScreenResult.Ok(screen); + } + + private Task> DoneAsync(ClaimsPrincipal caller, MavenResult result, string success, CancellationToken cancellationToken) + => DoneAsync(caller, result.Succeeded ? success : result.Message ?? "Not done.", !result.Succeeded, cancellationToken); + + /// Adds an owner. + public async Task> AddOwnerAsync(ClaimsPrincipal caller, string? group, string? artifact, string? version, string? ownerName, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, group, artifact, version, "AddOwner", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var result = string.IsNullOrWhiteSpace(ownerName) + ? OwnerChangeResult.UnknownAccount + : await _services.Ownership.AddOwnerAsync(Name, ownerName.Trim(), cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, result == OwnerChangeResult.Success ? $"{ownerName} is now an owner." : PackageScreenServices.Describe(result, "artifact"), result != OwnerChangeResult.Success, cancellationToken).ConfigureAwait(false); + } + + /// Removes an owner. + public async Task> RemoveOwnerAsync(ClaimsPrincipal caller, string? group, string? artifact, string? version, string? ownerName, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, group, artifact, version, "RemoveOwner", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + #pragma warning disable CS8604 + var result = await _services.Ownership.RemoveOwnerAsync(Name, ownerName, cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8604 + + return await DoneAsync(caller, result == OwnerChangeResult.Success ? $"{ownerName} is no longer an owner." : PackageScreenServices.Describe(result, "artifact"), result != OwnerChangeResult.Success, cancellationToken).ConfigureAwait(false); + } + + /// Deletes one file of the chosen version (and its checksums with it), after the password is confirmed. + public async Task> DeleteFileAsync(ClaimsPrincipal caller, string? group, string? artifact, string? version, string? fileName, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, group, artifact, version, "DeleteFile", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + if (_version == null) return await DoneAsync(caller, "Choose a version first.", failed: true, cancellationToken).ConfigureAwait(false); + + var result = await _maven.DeleteFileAsync(await _services.CallerAsync(caller).ConfigureAwait(false), new MavenCoordinate(_group, _artifact, _version), fileName ?? string.Empty, cancellationToken).ConfigureAwait(false); + if (result.Succeeded) _logger.LogWarning("{User} deleted {File} of {Artifact} {Version}", caller.Identity?.Name, fileName, Name, _version); + + return await AfterDeleteAsync(caller, result, $"{fileName} is deleted.", cancellationToken).ConfigureAwait(false); + } + + /// Deletes one version with its files, after the password is confirmed. + public async Task> DeleteVersionAsync(ClaimsPrincipal caller, string? group, string? artifact, string? selectedVersion, string? version, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, group, artifact, selectedVersion, "DeleteVersion", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + if (!MavenNames.IsValidVersion(version)) return await DoneAsync(caller, "Choose a version.", failed: true, cancellationToken).ConfigureAwait(false); + + var result = await _maven.DeleteVersionAsync(await _services.CallerAsync(caller).ConfigureAwait(false), new MavenCoordinate(_group, _artifact, version), cancellationToken).ConfigureAwait(false); + if (result.Succeeded) _logger.LogWarning("{User} deleted {Artifact} {Version}", caller.Identity?.Name, Name, version); + if (_version == version) _version = null; + + return await AfterDeleteAsync(caller, result, $"{Name} {version} is deleted.", cancellationToken).ConfigureAwait(false); + } + + /// Deletes every version of the artifact, after the password is confirmed. + public async Task> DeleteArtifactAsync(ClaimsPrincipal caller, string? group, string? artifact, string? version, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, group, artifact, version, "DeleteArtifact", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + var result = await _maven.DeleteArtifactAsync(await _services.CallerAsync(caller).ConfigureAwait(false), _group, _artifact, cancellationToken).ConfigureAwait(false); + if (!result.Succeeded) return await DoneAsync(caller, result, string.Empty, cancellationToken).ConfigureAwait(false); + + _logger.LogWarning("{User} deleted Maven artifact {Artifact}", caller.Identity?.Name, Name); + + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.MavenArtifacts)); + } + + /// Deletes the builds of a snapshot version older than the newest . + public async Task> CleanupAsync(ClaimsPrincipal caller, string? group, string? artifact, string? selectedVersion, string? version, string? keep, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, group, artifact, selectedVersion, "Cleanup", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + if (!MavenNames.IsValidVersion(version)) return await DoneAsync(caller, "Choose a snapshot version.", failed: true, cancellationToken).ConfigureAwait(false); + if (!int.TryParse(keep, NumberStyles.None, CultureInfo.InvariantCulture, out var count) || count < 1) + { + return await DoneAsync(caller, "Enter how many builds to keep (at least 1).", failed: true, cancellationToken).ConfigureAwait(false); + } + + var result = await _maven.CleanupSnapshotsAsync(await _services.CallerAsync(caller).ConfigureAwait(false), new MavenCoordinate(_group, _artifact, version), count, cancellationToken).ConfigureAwait(false); + if (result.Succeeded) _logger.LogWarning("{User} cleaned up the snapshot builds of {Artifact} {Version}, keeping {Keep}", caller.Identity?.Name, Name, version, count); + + return await DoneAsync(caller, result, result.Message ?? "Done.", cancellationToken).ConfigureAwait(false); + } + + // The last file takes the version, the last version the artifact: nothing left to manage. + private async Task> AfterDeleteAsync(ClaimsPrincipal caller, MavenResult result, string success, CancellationToken cancellationToken) + { + if (result.Succeeded && await _maven.GetArtifactAsync(_group, _artifact, cancellationToken).ConfigureAwait(false) == null) + { + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.MavenArtifacts)); + } + + return await DoneAsync(caller, result, success, cancellationToken).ConfigureAwait(false); + } + + /// Null when the signed-in user confirmed with their password, otherwise the screen to show. + private async Task?> RefuseUnconfirmedAsync(ClaimsPrincipal caller, string? password, CancellationToken cancellationToken) + { + var current = await _services.Users.GetUserAsync(caller).ConfigureAwait(false); + if (current == null) return ScreenResult.SignIn(); + + return await _services.IsConfirmedAsync(current, password, cancellationToken).ConfigureAwait(false) + ? null + : await DoneAsync(caller, "The confirmation is incorrect, so nothing was deleted.", failed: true, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/NpmManageUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/NpmManageUseCase.cs new file mode 100644 index 000000000..71b669964 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/NpmManageUseCase.cs @@ -0,0 +1,294 @@ +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// The owners' screen for an npm package: its owners, dist-tags, per-version deprecation and unpublishing. Every change goes through +/// as the signed-in user (the session's principal, never a typed key), so the screen can do what the same user's API +/// key could through the registry routes and no more: the access model, ownership, and the unpublish window apply identically. Opening it +/// takes ownership (directly or through an organization) or administration; unpublishing also asks for the password again, since it cannot be +/// undone. Works in the request's repository. Scoped: runs once per request (see ). +/// +public sealed class NpmManageUseCase +{ + /// What every write handler answers on a read-only server. + public const string ReadOnlyMessage = PackageScreenServices.ReadOnlyMessage; + + private readonly PackageScreenServices _services; + private readonly INpmRegistry _registry; + private readonly IUrlGenerator _urls; + private readonly IOptionsSnapshot _npm; + private readonly ILogger _logger; + + private bool _entered; + private string? _enteredId; + private bool _enteredWrite; + private ScreenResult? _refusal; + private string _name = string.Empty; + private bool _isAdministrator; + private bool _actingAsAdministrator; + + /// Creates the use case. + public NpmManageUseCase( + PackageScreenServices services, + INpmRegistry registry, + IUrlGenerator urls, + IOptionsSnapshot npm, + ILogger logger) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + _urls = urls ?? throw new ArgumentNullException(nameof(urls)); + _npm = npm ?? throw new ArgumentNullException(nameof(npm)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// The check that runs before every handler: a valid name, a local repository, ownership or administration, the maintenance gate and + /// read-only mode for a write. Returns the answer that ends the request, or null to run the handler. + /// + /// The signed-in user. + /// The package name from the address. + /// The handler about to run (for the administrator audit line). + /// Whether the request is a POST. + /// The cancellation token. + public async Task?> EnterAsync(ClaimsPrincipal caller, string? id, string? handler, bool isWrite, CancellationToken cancellationToken) + { + if (_entered && _enteredId == id && _enteredWrite == isWrite) return _refusal; + + _refusal = await CheckAsync(caller, id, handler, isWrite, cancellationToken).ConfigureAwait(false); + _entered = true; + _enteredId = id; + _enteredWrite = isWrite; + + return _refusal; + } + + private async Task?> CheckAsync(ClaimsPrincipal caller, string? id, string? handler, bool isWrite, CancellationToken cancellationToken) + { + if (!NpmNames.TryParse(id, out var name, out _)) + { + return ScreenResult.NotFound(); + } + + _name = name; + + // Owners and the owner tools exist where packages are published: a remote repository only caches an upstream's (every + // change is refused there) and a virtual one holds none, so neither has this screen (the repository check says the same; + // the controller's own check can run before it, so the rule is kept here too). + if (_services.Repository.Current.Kind != RepositoryKind.Local) + { + return ScreenResult.NotFound(); + } + + var isOwner = await _services.Ownership.IsOwnerAsync(_services.Users.GetUserId(caller), caller.Identity?.Name, _name, cancellationToken).ConfigureAwait(false); + _isAdministrator = await _services.Administrators.IsAdministratorAsync(caller, cancellationToken).ConfigureAwait(false); + if (!isOwner && !_isAdministrator) + { + return await _services.CanSeeAsync(caller, _name, cancellationToken).ConfigureAwait(false) + ? ScreenResult.Forbidden() + : ScreenResult.NotFound(); + } + + _actingAsAdministrator = _isAdministrator && !isOwner; + + if (isWrite) + { + // A write: refused while a database copy has the gate closed, and in read-only mode, for every handler at once. + _services.Services.GetService()?.ThrowIfClosed(); + + if (_services.IsReadOnlyMode) + { + var screen = await LoadAsync(caller, cancellationToken).ConfigureAwait(false); + screen.Message = ReadOnlyMessage; + screen.Failed = true; + + return ScreenResult.Ok(screen); + } + + if (_actingAsAdministrator) + { + _logger.LogWarning("Administrator {Admin} ran {Handler} on npm package {Package}", caller.Identity?.Name, handler, _name); + } + } + + return null; + } + + /// The GET handler: loads the package, 404 when it does not exist. + public async Task> GetAsync(ClaimsPrincipal caller, string? id, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, null, false, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var screen = await LoadAsync(caller, cancellationToken).ConfigureAwait(false); + + return screen.Package == null ? ScreenResult.NotFound() : ScreenResult.Ok(screen); + } + + private async Task LoadAsync(ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var confirmation = await _services.ConfirmationAsync(caller, cancellationToken).ConfigureAwait(false); + + return new NpmManageViewModel + { + IsAdministrator = _isAdministrator, + ActingAsAdministrator = _actingAsAdministrator, + HasPassword = confirmation.HasPassword, + Reauthenticated = confirmation.Reauthenticated, + CanReauthenticate = confirmation.CanReauthenticate, + RegistryUrl = _urls.GetNpmRegistryUrl(), + UnpublishWindow = _npm.Value.UnpublishWindow, + Id = _name, + Package = await _registry.GetPackageAsync(_name, cancellationToken).ConfigureAwait(false), + Owners = await _services.Ownership.GetOwnersAsync(_name, cancellationToken).ConfigureAwait(false), + }; + } + + private async Task> DoneAsync(ClaimsPrincipal caller, string message, bool failed, CancellationToken cancellationToken) + { + var screen = await LoadAsync(caller, cancellationToken).ConfigureAwait(false); + screen.Message = message; + screen.Failed = failed; + + return ScreenResult.Ok(screen); + } + + private Task> DoneAsync(ClaimsPrincipal caller, NpmResult result, string success, CancellationToken cancellationToken) + => DoneAsync(caller, result.Succeeded ? success : result.Message ?? "Not done.", !result.Succeeded, cancellationToken); + + /// Adds an owner. + public async Task> AddOwnerAsync(ClaimsPrincipal caller, string? id, string? ownerName, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "AddOwner", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var result = string.IsNullOrWhiteSpace(ownerName) + ? OwnerChangeResult.UnknownAccount + : await _services.Ownership.AddOwnerAsync(_name, ownerName.Trim(), cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, result == OwnerChangeResult.Success ? $"{ownerName} is now an owner." : PackageScreenServices.Describe(result, "package"), result != OwnerChangeResult.Success, cancellationToken).ConfigureAwait(false); + } + + /// Removes an owner. + public async Task> RemoveOwnerAsync(ClaimsPrincipal caller, string? id, string? ownerName, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "RemoveOwner", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + #pragma warning disable CS8604 + var result = await _services.Ownership.RemoveOwnerAsync(_name, ownerName, cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8604 + + return await DoneAsync(caller, result == OwnerChangeResult.Success ? $"{ownerName} is no longer an owner." : PackageScreenServices.Describe(result, "package"), result != OwnerChangeResult.Success, cancellationToken).ConfigureAwait(false); + } + + /// Points a dist-tag at a version. + public async Task> SetTagAsync(ClaimsPrincipal caller, string? id, string? tag, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "SetTag", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var result = await _registry.SetDistTagAsync(await _services.CallerAsync(caller).ConfigureAwait(false), _name, tag?.Trim() ?? string.Empty, version ?? string.Empty, cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, result, $"{tag} now points at {version}.", cancellationToken).ConfigureAwait(false); + } + + /// Removes a dist-tag. + public async Task> RemoveTagAsync(ClaimsPrincipal caller, string? id, string? tag, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "RemoveTag", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var result = await _registry.RemoveDistTagAsync(await _services.CallerAsync(caller).ConfigureAwait(false), _name, tag ?? string.Empty, cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, result, $"The tag {tag} is removed.", cancellationToken).ConfigureAwait(false); + } + + /// Deprecates a version. + public async Task> DeprecateAsync(ClaimsPrincipal caller, string? id, string? version, string? message, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Deprecate", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + if (string.IsNullOrWhiteSpace(message)) + { + return await DoneAsync(caller, "Write the deprecation message.", failed: true, cancellationToken).ConfigureAwait(false); + } + + var result = await _registry.DeprecateAsync(await _services.CallerAsync(caller).ConfigureAwait(false), _name, new Dictionary { [version ?? string.Empty] = message.Trim() }, cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, result, $"{_name}@{version} is deprecated.", cancellationToken).ConfigureAwait(false); + } + + /// Removes a version's deprecation. + public async Task> UndeprecateAsync(ClaimsPrincipal caller, string? id, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Undeprecate", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var result = await _registry.DeprecateAsync(await _services.CallerAsync(caller).ConfigureAwait(false), _name, new Dictionary { [version ?? string.Empty] = null }, cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, result, $"{_name}@{version} is no longer deprecated.", cancellationToken).ConfigureAwait(false); + } + + /// Unpublishes one version and deletes its tarball, after the password is confirmed. + public async Task> UnpublishAsync(ClaimsPrincipal caller, string? id, string? version, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Unpublish", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + var result = await _registry.UnpublishVersionsAsync(await _services.CallerAsync(caller).ConfigureAwait(false), _name, new[] { version ?? string.Empty }, newTags: null, cancellationToken).ConfigureAwait(false); + if (result.Succeeded) _logger.LogWarning("{User} unpublished {Package}@{Version}", caller.Identity?.Name, _name, version); + + // The last version takes the package with it: nothing left to manage. + if (result.Succeeded && await _registry.GetPackageAsync(_name, cancellationToken).ConfigureAwait(false) == null) + { + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.NpmPackages)); + } + + return await DoneAsync(caller, result, $"{_name}@{version} is unpublished. Its tarball is deleted.", cancellationToken).ConfigureAwait(false); + } + + /// Unpublishes every version of the package, after the password is confirmed. + public async Task> UnpublishAllAsync(ClaimsPrincipal caller, string? id, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "UnpublishAll", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var unconfirmed = await RefuseUnconfirmedAsync(caller, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + var result = await _registry.UnpublishPackageAsync(await _services.CallerAsync(caller).ConfigureAwait(false), _name, cancellationToken).ConfigureAwait(false); + if (!result.Succeeded) return await DoneAsync(caller, result, string.Empty, cancellationToken).ConfigureAwait(false); + + _logger.LogWarning("{User} unpublished npm package {Package}", caller.Identity?.Name, _name); + + return ScreenResult.GoTo(new ScreenNext(ScreenCatalog.NpmPackages)); + } + + /// Null when the signed-in user confirmed with their password, otherwise the screen to show. + private async Task?> RefuseUnconfirmedAsync(ClaimsPrincipal caller, string? password, CancellationToken cancellationToken) + { + var current = await _services.Users.GetUserAsync(caller).ConfigureAwait(false); + if (current == null) return ScreenResult.SignIn(); + + return await _services.IsConfirmedAsync(current, password, cancellationToken).ConfigureAwait(false) + ? null + : await DoneAsync(caller, "The confirmation is incorrect, so nothing was unpublished.", failed: true, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/PackageManageUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/PackageManageUseCase.cs new file mode 100644 index 000000000..d32382032 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/PackageManageUseCase.cs @@ -0,0 +1,654 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using NuGet.Versioning; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// The owners' screen for a package ID (/packages/{id}/manage): its owners, its versions' listing and deprecation, vulnerabilities and +/// indexed symbols (PDBs), and the abuse reports against it. An administrator may open it for any ID, ownerless ones included, and alone may +/// set the ID's verified (reserved) flag and delete permanently whatever says, after +/// confirming their password. Everything works in the request's repository. Scoped: runs once per request (the view +/// controller asks first, so the check keeps its place before the repository filter; the operations ask again and get the same answer). +/// +public sealed class PackageManageUseCase +{ + /// + /// What every write handler answers on a read-only server. The API refuses each of these operations with a 401, so the screen must + /// refuse all of them too rather than only the one it was last asked about. + /// + public const string ReadOnlyMessage = PackageScreenServices.ReadOnlyMessage; + + private readonly PackageScreenServices _services; + private readonly IPackageDatabase _packages; + private readonly PackageChangeNotifier _notifier; + private readonly IContext _context; + private readonly IPackageDeletionService _deletions; + private readonly ISymbolRegistry _symbols; + private readonly SystemTime _time; + private readonly ILogger _logger; + + private bool _entered; + private string? _enteredId; + private bool _enteredWrite; + private ScreenResult? _refusal; + private bool _isAdministrator; + private bool _actingAsAdministrator; + + /// Creates the use case. + public PackageManageUseCase( + PackageScreenServices services, + IPackageDatabase packages, + PackageChangeNotifier notifier, + IContext context, + IPackageDeletionService deletions, + ISymbolRegistry symbols, + SystemTime time, + ILogger logger) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _deletions = deletions ?? throw new ArgumentNullException(nameof(deletions)); + _symbols = symbols ?? throw new ArgumentNullException(nameof(symbols)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// The check that runs before every handler: only an owner, directly or through an organization, or an administrator, may manage the + /// package; a write is refused on a read-only server. Returns the answer that ends the request, or null to run the handler. + /// + /// The signed-in user. + /// The package ID from the address. + /// The handler about to run (for the administrator audit line). + /// Whether the request is a POST. + /// The cancellation token. + public async Task?> EnterAsync(ClaimsPrincipal caller, string? id, string? handler, bool isWrite, CancellationToken cancellationToken) + { + if (_entered && _enteredId == id && _enteredWrite == isWrite) return _refusal; + + _refusal = await CheckAsync(caller, id, handler, isWrite, cancellationToken).ConfigureAwait(false); + _entered = true; + _enteredId = id; + _enteredWrite = isWrite; + + return _refusal; + } + + private async Task?> CheckAsync(ClaimsPrincipal caller, string? id, string? handler, bool isWrite, CancellationToken cancellationToken) + { + var isOwner = await _services.Ownership.IsOwnerAsync(_services.Users.GetUserId(caller), caller.Identity?.Name, id, cancellationToken).ConfigureAwait(false); + _isAdministrator = await _services.Administrators.IsAdministratorAsync(caller, cancellationToken).ConfigureAwait(false); + // An owner also needs a management permission in this repository (a seeded target gives every signed-in user + // all of them, so nothing changes until an administrator narrows it); an administrator holds every action. Each + // handler then asks for the action the protocol asks for the same change (RequireAsync). + if (isOwner && !_isAdministrator + && !await ManagePermission.HeldAnyAsync(_services.Services, caller, id, cancellationToken).ConfigureAwait(false)) + { + isOwner = false; + } + + if (!isOwner && !_isAdministrator) + { + // A caller who may not even read the package gets the answer of a missing one (404), not a 403 that tells the repository exists. + return _services.Repository.Current.Kind == RepositoryKind.Virtual + || !await _services.CanSeeAsync(caller, id, cancellationToken).ConfigureAwait(false) + ? ScreenResult.NotFound() + : ScreenResult.Forbidden(); + } + + _actingAsAdministrator = _isAdministrator && !isOwner; + // Every handler on this screen but the GET writes to the database, and most of + // them notify the catalog as well. Refused here, once, rather than in each + // handler: unlisting, relisting, deprecating and changing owners are the same + // operations the push and metadata endpoints short-circuit in read-only mode, + // and a screen that refused only one of them would contradict itself. + if (_services.IsReadOnlyMode && isWrite) + { + return ScreenResult.Ok(await LoadAsync(caller, id, ReadOnlyMessage, cancellationToken).ConfigureAwait(false)); + } + + if (_actingAsAdministrator && isWrite) + { + // The audit trail: an administrator changing what is not theirs. + _logger.LogWarning("Administrator {Admin} ran {Handler} on {PackageId}", caller.Identity?.Name, handler, id); + } + + return null; + } + + /// + /// Null when the user may do what the handler does: an administrator, or an owner holding the access model action the protocol + /// endpoints require for the same change (Delete to unlist, relist and delete, Annotate to deprecate and edit vulnerabilities, + /// Manage for owners); otherwise the answer that ends the request. + /// + private async Task?> RequireAsync(ClaimsPrincipal caller, string? id, AccessAction action, CancellationToken cancellationToken) + { + if (_isAdministrator || await ManagePermission.HeldAsync(_services.Services, caller, id, action, cancellationToken).ConfigureAwait(false)) return null; + + return ScreenResult.Forbidden(); + } + + /// The GET handler: loads the screen, 404 when the ID has neither versions nor owners. + public async Task> GetAsync(ClaimsPrincipal caller, string? id, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, null, false, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var screen = await LoadAsync(caller, id, null, cancellationToken).ConfigureAwait(false); + + return screen.Versions.Count == 0 && screen.Owners.Count == 0 + ? ScreenResult.NotFound() + : ScreenResult.Ok(screen); + } + + /// Adds an owner. + public async Task> AddOwnerAsync(ClaimsPrincipal caller, string? id, string? ownerName, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "AddOwner", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Manage, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var result = string.IsNullOrWhiteSpace(ownerName) + ? OwnerChangeResult.UnknownAccount + : await _services.Ownership.AddOwnerAsync(id, ownerName.Trim(), cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, id, result == OwnerChangeResult.Success ? $"{ownerName} is now an owner." : Describe(result), cancellationToken).ConfigureAwait(false); + } + + /// Removes an owner. + public async Task> RemoveOwnerAsync(ClaimsPrincipal caller, string? id, string? ownerName, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "RemoveOwner", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Manage, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + #pragma warning disable CS8604 + var result = await _services.Ownership.RemoveOwnerAsync(id, ownerName, cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8604 + + return await DoneAsync(caller, id, result == OwnerChangeResult.Success ? $"{ownerName} is no longer an owner." : Describe(result), cancellationToken).ConfigureAwait(false); + } + + /// Unlists a version. + public async Task> UnlistAsync(ClaimsPrincipal caller, string? id, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Unlist", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Delete, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + return await ChangeVersionAsync(caller, id, version, v => _packages.UnlistPackageAsync(id!, v, cancellationToken), "unlisted", cancellationToken).ConfigureAwait(false); + } + + /// Relists a version. + public async Task> RelistAsync(ClaimsPrincipal caller, string? id, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Relist", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Delete, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + return await ChangeVersionAsync(caller, id, version, v => _packages.RelistPackageAsync(id!, v, cancellationToken), "relisted", cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletion as the server is configured to perform it: hides the version, + /// removes its rows and its files. The screen labels the button from the behaviour, so it + /// never promises a deletion that only unlists. + /// + public async Task> DeleteAsync(ClaimsPrincipal caller, string? id, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Delete", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Delete, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + // Read-only mode is refused for every handler at once, in EnterAsync, as the push endpoint's DELETE refuses before anything is touched. + if (!NuGetVersion.TryParse(version, out var parsed)) return ScreenResult.NotFound(); + + // False means the database held no such version - not that nothing happened: a hard delete removes the files either way. + var found = await _deletions.TryDeletePackageAsync(id!, parsed, cancellationToken).ConfigureAwait(false); + var normalized = parsed.ToNormalizedString(); + + // PackageDeletionService notifies the catalog itself, so nothing is notified here. + if (_services.Options.PackageDeletionBehavior == PackageDeletionBehavior.HardDelete) + { + return await DoneAsync( + caller, + id, + found + ? $"{id} {normalized} is deleted. Its rows and its files are gone, and consumers " + + "can no longer restore it. Any indexed PDBs are still served, and an external " + + "search index keeps the version until it is reindexed." + : $"{id} {normalized} was not in the database. Any files left in storage for it were removed.", + cancellationToken).ConfigureAwait(false); + } + + return await DoneAsync( + caller, + id, + found + ? $"{id} {normalized} is unlisted. Deleting is configured to unlist on this server, so " + + "anyone who knows the exact version can still restore it." + : $"There is no {id} {normalized} to unlist.", + cancellationToken).ConfigureAwait(false); + } + + /// + /// Removes one version's rows and files whatever the server's deletion behaviour is. Administrators only, and only after they confirm + /// their password: it cannot be undone. + /// + public async Task> HardDeleteAsync(ClaimsPrincipal caller, string? id, string? version, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "HardDelete", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + if (!_isAdministrator) return ScreenResult.Forbidden(); + if (!NuGetVersion.TryParse(version, out var parsed)) return ScreenResult.NotFound(); + + var unconfirmed = await RefuseUnconfirmedAsync(caller, id, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + var found = await _deletions.TryHardDeletePackageAsync(id!, parsed, cancellationToken).ConfigureAwait(false); + var normalized = parsed.ToNormalizedString(); + + _logger.LogWarning("Administrator {Admin} permanently deleted {PackageId} {PackageVersion}", caller.Identity?.Name, id, normalized); + + return await DoneAsync( + caller, + id, + found + ? $"{id} {normalized} is deleted permanently. Its rows and its files are gone, and consumers " + + "can no longer restore it. Any indexed PDBs are still served, and an external " + + "search index keeps the version until it is reindexed." + : $"{id} {normalized} was not in the database. Any files left in storage for it were removed.", + cancellationToken).ConfigureAwait(false); + } + + /// + /// Removes every version of the ID, then its owners, so the ID is free to claim again. Administrators only, and only after they confirm + /// their password. + /// + public async Task> HardDeleteAllAsync(ClaimsPrincipal caller, string? id, string? password, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "HardDeleteAll", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + if (!_isAdministrator) return ScreenResult.Forbidden(); + + var unconfirmed = await RefuseUnconfirmedAsync(caller, id, password, cancellationToken).ConfigureAwait(false); + if (unconfirmed != null) return unconfirmed; + + var versions = await _packages.FindAsync(id!, includeUnlisted: true, cancellationToken).ConfigureAwait(false); + foreach (var package in versions) + { + await _deletions.TryHardDeletePackageAsync(id!, package.Version, cancellationToken).ConfigureAwait(false); + } + + var lowerId = id!.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + _context.PackageOwners.RemoveRange(await _context.PackageOwners + .Where(o => o.PackageId.ToLower() == lowerId) + .ToListAsync(cancellationToken).ConfigureAwait(false)); + #pragma warning restore CS8602, CS8604 + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + _logger.LogWarning( + "Administrator {Admin} permanently deleted every version of {PackageId} ({Count}) and removed its owners", + caller.Identity?.Name, + id, + versions.Count); + + return await DoneAsync( + caller, + id, + $"Every version of {id} ({versions.Count}) is deleted permanently, and the ID has no owners.", + cancellationToken).ConfigureAwait(false); + } + + /// Null when the signed in user confirmed with their password, otherwise the screen to show. + private async Task?> RefuseUnconfirmedAsync(ClaimsPrincipal caller, string? id, string? password, CancellationToken cancellationToken) + { + var current = await _services.Users.GetUserAsync(caller).ConfigureAwait(false); + if (current == null) return ScreenResult.SignIn(); + + return await _services.IsConfirmedAsync(current, password, cancellationToken).ConfigureAwait(false) + ? null + : await DoneAsync(caller, id, "The confirmation is incorrect, so nothing was deleted.", cancellationToken).ConfigureAwait(false); + } + + /// Deprecates a version. + public async Task> DeprecateAsync( + ClaimsPrincipal caller, + string? id, + string? version, + List? reasons, + string? message, + string? alternatePackageId, + string? alternateVersionRange, + CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Deprecate", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Annotate, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + reasons = reasons?.Where(r => PackageDeprecation.KnownReasons.Contains(r, StringComparer.Ordinal)).Distinct().ToList(); + if (reasons == null || reasons.Count == 0) + { + return await DoneAsync(caller, id, "Choose at least one deprecation reason.", cancellationToken).ConfigureAwait(false); + } + + // The same rules as the metadata API (PackageMetadataAdminController.Validate). + var alternateId = string.IsNullOrWhiteSpace(alternatePackageId) ? null : alternatePackageId.Trim(); + var alternateRange = string.IsNullOrWhiteSpace(alternateVersionRange) ? null : alternateVersionRange.Trim(); + if (alternateId == null && alternateRange != null) + { + return await DoneAsync(caller, id, "An alternate version range needs an alternate package ID.", cancellationToken).ConfigureAwait(false); + } + + if (alternateRange != null && alternateRange != "*" && !VersionRange.TryParse(alternateRange, out _)) + { + return await DoneAsync(caller, id, $"'{alternateRange}' is not a version range.", cancellationToken).ConfigureAwait(false); + } + + var deprecation = new PackageDeprecation + { + Reasons = reasons.ToArray(), + Message = string.IsNullOrWhiteSpace(message) ? null : message.Trim(), + AlternatePackageId = alternateId, + AlternateVersionRange = alternateRange, + }; + + return await ChangeVersionAsync(caller, id, version, v => _packages.SetDeprecationAsync(id!, v, deprecation, cancellationToken), "deprecated", cancellationToken).ConfigureAwait(false); + } + + /// Removes a version's deprecation. + public async Task> UndeprecateAsync(ClaimsPrincipal caller, string? id, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "Undeprecate", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Annotate, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + return await ChangeVersionAsync(caller, id, version, v => _packages.RemoveDeprecationAsync(id!, v, cancellationToken), "no longer deprecated", cancellationToken).ConfigureAwait(false); + } + + /// Adds one vulnerability to a version, through the rules the metadata API applies (). + public async Task> AddVulnerabilityAsync( + ClaimsPrincipal caller, + string? id, + string? version, + string? advisoryUrl, + int severity, + string? versionRange, + CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "AddVulnerability", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Annotate, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var added = new PackageVulnerability + { + AdvisoryUrl = advisoryUrl?.Trim(), + Severity = severity, + VersionRange = string.IsNullOrWhiteSpace(versionRange) ? null : versionRange.Trim(), + }; + + return await ChangeVulnerabilitiesAsync(caller, id, version, current => current.Append(added).ToList(), "updated (vulnerability added)", cancellationToken).ConfigureAwait(false); + } + + /// Removes one vulnerability, identified by its key, from a version. + public async Task> RemoveVulnerabilityAsync(ClaimsPrincipal caller, string? id, string? version, int key, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "RemoveVulnerability", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Annotate, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + return await ChangeVulnerabilitiesAsync(caller, id, version, current => current.Where(v => v.Key != key).ToList(), "updated (vulnerability removed)", cancellationToken).ConfigureAwait(false); + } + + private async Task> ChangeVulnerabilitiesAsync( + ClaimsPrincipal caller, + string? id, + string? version, + Func, IReadOnlyList> change, + string done, + CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var parsed)) return ScreenResult.NotFound(); + + var package = await _packages.FindOrNullAsync(id!, parsed, includeUnlisted: true, cancellationToken).ConfigureAwait(false); + if (package == null) return ScreenResult.NotFound(); + + // Fresh copies: the stored rows are replaced as a whole, so the list must not reuse tracked entities. Entries the vulnerability + // scanner wrote (Source set) are not the administrator's to edit and are kept by the store, so they are left out of the list. + var updated = change((package.Vulnerabilities ?? new List()).Where(v => v.Source == null).ToList()) + .Select(v => new PackageVulnerability + { + Key = v.Key, + AdvisoryUrl = v.AdvisoryUrl, + Severity = v.Severity, + VersionRange = v.VersionRange, + }) + .ToList(); + + var error = PackageVulnerabilityRules.Validate(updated); + if (error != null) return await DoneAsync(caller, id, error, cancellationToken).ConfigureAwait(false); + + foreach (var vulnerability in updated) vulnerability.Key = 0; + + return await ChangeVersionAsync( + caller, + id, + version, + v => _packages.SetVulnerabilitiesAsync(id!, v, updated, cancellationToken), + done, + cancellationToken).ConfigureAwait(false); + } + + /// Marks or unmarks the ID as verified (reserved for its owners). Administrators only: owners cannot grant the flag to themselves. + public async Task> SetVerifiedAsync(ClaimsPrincipal caller, string? id, bool verified, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "SetVerified", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + if (!_isAdministrator) return ScreenResult.Forbidden(); + + var changed = await _services.Ownership.SetVerifiedAsync(id!, verified, cancellationToken).ConfigureAwait(false); + if (!changed) return ScreenResult.NotFound(); + + _logger.LogWarning("Administrator {Admin} {Action} {PackageId}", caller.Identity?.Name, verified ? "verified" : "unverified", id); + + return await DoneAsync(caller, id, verified ? $"{id} is verified." : $"{id} is no longer verified.", cancellationToken).ConfigureAwait(false); + } + + /// Deletes the PDBs recorded for a version. They stop being served; PDBs indexed before they were recorded cannot be deleted from here. + public async Task> DeleteSymbolsAsync(ClaimsPrincipal caller, string? id, string? version, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "DeleteSymbols", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Delete, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + if (!NuGetVersion.TryParse(version, out var parsed)) return ScreenResult.NotFound(); + + var removed = await _symbols.DeleteAsync(id!, parsed, cancellationToken).ConfigureAwait(false); + + return await DoneAsync( + caller, + id, + removed == 0 + ? $"{id} {parsed.ToNormalizedString()} has no recorded symbols to delete." + : $"Deleted {removed} symbol file(s) of {id} {parsed.ToNormalizedString()}.", + cancellationToken).ConfigureAwait(false); + } + + /// Resolves an abuse report. + public async Task> ResolveReportAsync(ClaimsPrincipal caller, string? id, int key, CancellationToken cancellationToken) + { + var refusal = await EnterAsync(caller, id, "ResolveReport", true, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + refusal = await RequireAsync(caller, id, AccessAction.Manage, cancellationToken).ConfigureAwait(false); + if (refusal != null) return refusal; + + var lowerId = id!.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var report = await _context.AbuseReports.FirstOrDefaultAsync(r => r.Key == key && r.PackageId.ToLower() == lowerId, cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8602, CS8604 + if (report != null && report.Resolved == null) + { + report.Resolved = _time.UtcNow; + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + return await DoneAsync(caller, id, "The report is resolved.", cancellationToken).ConfigureAwait(false); + } + + private async Task> ChangeVersionAsync( + ClaimsPrincipal caller, + string? id, + string? version, + Func> change, + string done, + CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var parsed)) return ScreenResult.NotFound(); + + bool changed; + try + { + changed = await change(parsed).ConfigureAwait(false); + } + catch (NotSupportedException e) + { + return await DoneAsync(caller, id, e.Message, cancellationToken).ConfigureAwait(false); + } + + if (!changed) return ScreenResult.NotFound(); + + await _notifier.PackageChangedAsync(id!, parsed, cancellationToken).ConfigureAwait(false); + + return await DoneAsync(caller, id, $"{id} {parsed.ToNormalizedString()} is {done}.", cancellationToken).ConfigureAwait(false); + } + + private async Task> DoneAsync(ClaimsPrincipal caller, string? id, string message, CancellationToken cancellationToken) + => ScreenResult.Ok(await LoadAsync(caller, id, message, cancellationToken).ConfigureAwait(false)); + + private async Task LoadAsync(ClaimsPrincipal caller, string? id, string? message, CancellationToken cancellationToken) + { + var screen = new PackageManageScreen + { + Id = id, + Message = message, + IsAdministrator = _isAdministrator, + ActingAsAdministrator = _actingAsAdministrator, + SymbolsSupported = _symbols.IsSupported, + SeverityNames = PackageVulnerabilityRules.SeverityNames, + CanReauthenticate = false, // set below from the caller's linked providers + DeletionBehavior = _services.Options.PackageDeletionBehavior, + IsReadOnlyMode = _services.IsReadOnlyMode, + }; + + if (_isAdministrator) + { + var confirmation = await _services.ConfirmationAsync(caller, cancellationToken).ConfigureAwait(false); + screen.HasPassword = confirmation.HasPassword; + screen.Reauthenticated = confirmation.Reauthenticated; + screen.CanReauthenticate = confirmation.CanReauthenticate; + } + + screen.Owners = (await _services.Ownership.GetOwnersAsync(id, cancellationToken).ConfigureAwait(false)) + .Select(o => new PackageManageOwner(o.OwnerName, o.IsVerified)) + .ToList(); + + var versions = (await _packages.FindAsync(id!, includeUnlisted: true, cancellationToken).ConfigureAwait(false)) + .OrderByDescending(p => p.Version) + .ToList(); + screen.Versions = versions + .Select(p => new PackageManageVersion( + p.Version.OriginalVersion ?? p.Version.ToNormalizedString(), + p.NormalizedVersionString, + p.Downloads, + p.Listed, + p.Deprecation == null + ? null + : new PackageManageDeprecation(p.Deprecation.Reasons ?? Array.Empty(), p.Deprecation.Message, p.Deprecation.AlternatePackageId, p.Deprecation.AlternateVersionRange), + (p.Vulnerabilities ?? new List()) + .Select(v => new PackageManageVulnerability(v.Key, v.AdvisoryUrl, v.Severity, v.VersionRange, v.Source)) + .ToList())) + .ToList(); + + if (_symbols.IsSupported) + { + var symbols = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (var package in versions) + { + var listed = await _symbols.ListAsync(id!, package.Version, cancellationToken).ConfigureAwait(false); + if (listed.Count > 0) + { + symbols[package.Version.ToNormalizedString()] = listed.Select(s => new PackageManageSymbol(s.FileName, s.Key)).ToList(); + } + } + + screen.Symbols = symbols; + } + + if (!(_context is NullContext)) + { + var lowerId = id!.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + screen.Reports = (await _context.AbuseReports + .AsNoTracking() + .Where(r => r.PackageId.ToLower() == lowerId && r.Resolved == null) + .OrderByDescending(r => r.Key) + .ToListAsync(cancellationToken).ConfigureAwait(false)) + .Select(r => new PackageManageReport(r.Key, r.PackageVersion, r.Reason, r.Details, r.ReporterEmail)) + .ToList(); + screen.HasValidation = await _context.PackageValidations + .AsNoTracking() + .AnyAsync(v => v.PackageId.ToLower() == lowerId, cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8602, CS8604 + } + + return screen; + } + + private static string Describe(OwnerChangeResult result) => result switch + { + OwnerChangeResult.UnknownAccount => "There is no user or organization with that name.", + OwnerChangeResult.AlreadyOwner => "That account is already an owner.", + OwnerChangeResult.NotOwner => "That account is not an owner.", + OwnerChangeResult.LastOwner => "A package must keep at least one owner.", + _ => result.ToString(), + }; +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/PackageScreenServices.cs b/src/BaGet.Identity.Application/UseCases/Packages/PackageScreenServices.cs new file mode 100644 index 000000000..841d021be --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/PackageScreenServices.cs @@ -0,0 +1,147 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// The services every package-management use case (Packages/* screens) shares: the signed-in user's account, the sensitive-action +/// check, the session principal the format services authorize, the read-only switch. Registered scoped with the account services. +/// +public sealed class PackageScreenServices +{ + /// What every write answers on a read-only server. + public const string ReadOnlyMessage = "This server is in read-only mode, so nothing can be changed."; + + private readonly ExternalLogins _logins; + private readonly IOptionsSnapshot _options; + private readonly ISessionPrincipalFactory _sessions; + private readonly IReauthenticationState _reauthentication; + + /// Creates the services. + public PackageScreenServices( + UserManager users, + PackageOwnershipService ownership, + AdministratorService administrators, + IOptions accounts, + IOptionsSnapshot options, + ISessionPrincipalFactory sessions, + IReauthenticationState reauthentication, + IRepositoryContext repository, + IServiceProvider services) + : this(users, ownership, administrators, accounts, options, sessions, reauthentication, repository, services, ExternalLogins.For(users, accounts)) + { + } + + /// Creates the services. + public PackageScreenServices( + UserManager users, + PackageOwnershipService ownership, + AdministratorService administrators, + IOptions accounts, + IOptionsSnapshot options, + ISessionPrincipalFactory sessions, + IReauthenticationState reauthentication, + IRepositoryContext repository, + IServiceProvider services, + ExternalLogins logins) + { + _ = accounts ?? throw new ArgumentNullException(nameof(accounts)); + Users = users ?? throw new ArgumentNullException(nameof(users)); + Ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + Administrators = administrators ?? throw new ArgumentNullException(nameof(administrators)); + _logins = logins ?? throw new ArgumentNullException(nameof(logins)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _sessions = sessions ?? throw new ArgumentNullException(nameof(sessions)); + _reauthentication = reauthentication ?? throw new ArgumentNullException(nameof(reauthentication)); + Repository = repository ?? throw new ArgumentNullException(nameof(repository)); + Services = services ?? throw new ArgumentNullException(nameof(services)); + } + + /// Users, passwords. + public UserManager Users { get; } + + /// Package and organization ownership. + public PackageOwnershipService Ownership { get; } + + /// Server administrators. + public AdministratorService Administrators { get; } + + /// The request's repository. + public IRepositoryContext Repository { get; } + + /// The request's services, for the helpers that take a provider (, , the maintenance gate). + public IServiceProvider Services { get; } + + /// The server's options. + public BaGetOptions Options => _options.Value; + + /// Whether the server refuses writes. + public bool IsReadOnlyMode => _options.Value.IsReadOnlyMode; + + /// Whether an external provider is available to sign in again with. + public bool CanReauthenticate => _logins.Configured.Count > 0; + + // Whether a particular caller can is ConfirmationAsync(...).CanReauthenticate (a configured provider linked to the account). + + /// + /// Whether the caller may see the package's pages in the request's repository (Read on the repository and the package). A refusal of the + /// owner check answers 404 rather than 403 when this is false, so a private repository is not told from a missing one; the global + /// repository filter would say the same, but the controller's own check runs before it. + /// + public async Task CanSeeAsync(ClaimsPrincipal caller, string? packageId, CancellationToken cancellationToken) + { + var access = (IRepositoryAccess?)Services.GetService(typeof(IRepositoryAccess)); + if (access == null) return true; + + var repository = Repository.Current; + return string.IsNullOrEmpty(packageId) + ? await access.CanReadAsync(caller, repository, cancellationToken).ConfigureAwait(false) + : await access.CanReadPackageAsync(caller, repository, packageId!, cancellationToken).ConfigureAwait(false); + } + + /// The session's principal for the format services (null when it cannot be built). + public async Task CallerAsync(ClaimsPrincipal caller) + => await _sessions.CreateAsync(caller).ConfigureAwait(false); + + /// + /// The sensitive-action check: an account with a password types it again; one without (external sign-in only) must have signed in + /// again with its provider a moment ago. + /// + public async Task IsConfirmedAsync(BaGetUser? user, string? password, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + return await Users.HasPasswordAsync(user).ConfigureAwait(false) + ? await Users.CheckPasswordAsync(user, password ?? string.Empty).ConfigureAwait(false) + : await _reauthentication.HasReauthenticatedRecentlyAsync(cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8604 + } + + /// How the caller can confirm a sensitive action. + public async Task ConfirmationAsync(ClaimsPrincipal caller, CancellationToken cancellationToken) + { + var current = await Users.GetUserAsync(caller).ConfigureAwait(false); + var hasPassword = current == null || await Users.HasPasswordAsync(current).ConfigureAwait(false); + var reauthenticated = !hasPassword && await _reauthentication.HasReauthenticatedRecentlyAsync(cancellationToken).ConfigureAwait(false); + + return new ConfirmationState(hasPassword, reauthenticated, await _logins.CanReauthenticateAsync(current).ConfigureAwait(false)); + } + + /// The message of an owner change, shared by the management screens ( is "package", "artifact" …). + public static string Describe(OwnerChangeResult result, string unit) => result switch + { + OwnerChangeResult.UnknownAccount => "There is no such user or organization.", + OwnerChangeResult.AlreadyOwner => $"That account already owns the {unit}.", + OwnerChangeResult.NotOwner => "That account is not an owner.", + OwnerChangeResult.LastOwner => $"{(unit == "package" ? "A" : "An")} {unit} keeps at least one owner.", + _ => result.ToString(), + }; +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/ScanArtifactUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/ScanArtifactUseCase.cs new file mode 100644 index 000000000..5d1156769 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/ScanArtifactUseCase.cs @@ -0,0 +1,120 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Security; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// Scan now for one version: checks the artifact (and its dependencies, or the image's packages) against the vulnerability source +/// again and shows what was found. Linked from the findings section of every format's package page. Gated like the other package operations: +/// signed in, the Manage action on the package (); refused with 503 while the server is read-only (the result is +/// stored). The scan of a container image can take minutes, so it is queued for the background worker and the screen says so; the other +/// formats are scanned before the answer. Works in the request's repository. +/// +public sealed class ScanArtifactUseCase +{ + private readonly PackageScreenServices _services; + private readonly IScanService _scans; + private readonly IAdminAudit _audit; + private readonly ScanQueue _queue; + + /// Creates the use case. + public ScanArtifactUseCase(PackageScreenServices services, IScanService scans, IAdminAudit audit, ScanQueue queue) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _scans = scans ?? throw new ArgumentNullException(nameof(scans)); + _audit = audit ?? throw new ArgumentNullException(nameof(audit)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + } + + /// Shows the form (and the stored result) of the version. + /// The signed-in user. + /// The artifact name (NuGet id, npm name, Maven group:artifact, Docker image). + /// The version (Docker: the manifest digest). + /// Where the link back goes, as the visitor sent it. + /// The address the link back leads to: when it is local, else the home page (the host knows its path base). + /// The cancellation token. + public async Task> GetAsync(ClaimsPrincipal caller, string? name, string? version, string? returnUrl, string backUrl, CancellationToken cancellationToken) + { + if (!await CanScanAsync(caller, name, version, cancellationToken).ConfigureAwait(false)) return ScreenResult.Forbidden(); + + var model = Model(name, version, returnUrl, backUrl); + model.Engine = _scans.GetEngineStatus(); + model.Result = await _scans.FindAsync(name!, version!, cancellationToken).ConfigureAwait(false); + + return ScreenResult.Ok(model); + } + + /// Scans the version now (or queues it, for an image) and shows the outcome. + /// + public async Task> ScanAsync(ClaimsPrincipal caller, string? name, string? version, string? returnUrl, string backUrl, CancellationToken cancellationToken) + { + if (!await CanScanAsync(caller, name, version, cancellationToken).ConfigureAwait(false)) return ScreenResult.Forbidden(); + + var model = Model(name, version, returnUrl, backUrl); + model.Engine = _scans.GetEngineStatus(); + if (!model.Engine.Available) + { + return Refuse(model, 409, model.Engine.Reason ?? "Scanning is not available."); + } + + var repository = _services.Repository.Current; + var user = (await _services.Users.GetUserAsync(caller).ConfigureAwait(false))?.UserName; + _audit.Record(user, "scan.run", $"repository {repository.Name}, {name} {version}"); + + try + { + var scanner = _services.Services.GetFormatService(repository.Format); + if (scanner?.Engine == ScanEngine.Image) + { + if (!await _scans.IsStoredAsync(name!, version!, cancellationToken).ConfigureAwait(false)) return Refuse(model, 404, "That version does not exist in this repository."); + + _queue.Enqueue(repository, name!, version!); + model.Result = await _scans.FindAsync(name!, version!, cancellationToken).ConfigureAwait(false); + model.Message = "The image is queued for a scan with Trivy, which can take a few minutes. Reload this page to see the result."; + + return ScreenResult.Ok(model); + } + + model.Result = await _scans.ScanAsync(name!, version!, cancellationToken).ConfigureAwait(false); + } + catch (ScanUnavailableException e) + { + return Refuse(model, 409, e.Message); + } + + if (model.Result == null) return Refuse(model, 404, "That version does not exist in this repository."); + + model.Result = await _scans.FindAsync(name!, version!, cancellationToken).ConfigureAwait(false); + model.Message = model.Result?.Error != null && model.Result.ScannedAt == null + ? "The scan failed: " + model.Result.Error + : model.Result?.FindingCount > 0 + ? $"Scanned: {model.Result.FindingCount} finding(s), the worst is {ScanSeverities.Name(model.Result.Highest)}." + : "Scanned: no known vulnerabilities."; + model.Failed = model.Result?.Error != null && model.Result.ScannedAt == null; + + return ScreenResult.Ok(model); + } + + private async Task CanScanAsync(ClaimsPrincipal caller, string? name, string? version, CancellationToken cancellationToken) + => !string.IsNullOrEmpty(name) + && !string.IsNullOrEmpty(version) + && await ScanAccess.CanScanAsync(_services.Services, caller, name, cancellationToken).ConfigureAwait(false); + + // The screen is shown again with the reason, under the status the refusal stands for. + private static ScreenResult Refuse(ScanViewModel model, int status, string message) + { + model.Message = message; + model.Failed = true; + + return ScreenResult.Ok(model, status); + } + + private static ScanViewModel Model(string? name, string? version, string? returnUrl, string backUrl) + => new() { Name = name, Version = version, ReturnUrl = returnUrl, BackUrl = backUrl }; +} diff --git a/src/BaGet.Identity.Application/UseCases/Packages/ValidationStatusUseCase.cs b/src/BaGet.Identity.Application/UseCases/Packages/ValidationStatusUseCase.cs new file mode 100644 index 000000000..e4bfed4e9 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Packages/ValidationStatusUseCase.cs @@ -0,0 +1,83 @@ +using System; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.EntityFrameworkCore; +using BaGet.Identity.Application.Models.Operations; + +namespace BaGet.Identity.Application.UseCases.Packages; + +/// +/// Where a pushed package stands in validation: for each version of the ID, its newest submission and the verdict and message of every step. +/// The screen counterpart of GET v3/package/{id}/{version}/validation, gated the same way: a signed-in user who may push or manage the +/// ID (an administrator holds both). Nothing is written. +/// +public sealed class ValidationStatusUseCase +{ + private readonly PackageScreenServices _services; + private readonly IPackageAuthorizationService _authorization; + private readonly IContext _context; + + /// Creates the use case. + public ValidationStatusUseCase(PackageScreenServices services, IPackageAuthorizationService authorization, IContext context) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// Shows the submissions of the ID, forbidden without the permission, 404 when validation never saw it. + public async Task> GetAsync(ClaimsPrincipal caller, string? id, CancellationToken cancellationToken) + { + var principal = await _services.CallerAsync(caller).ConfigureAwait(false); + if (principal == null) return ScreenResult.SignIn(); + + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, id, cancellationToken).ConfigureAwait(false) + && !await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken).ConfigureAwait(false)) + { + return ScreenResult.Forbidden(); + } + + if (_context is NullContext) return ScreenResult.NotFound(); + + var lowerId = (id ?? string.Empty).ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + var steps = await _context.PackageValidations + .AsNoTracking() + .Where(v => v.PackageId.ToLower() == lowerId) + .OrderByDescending(v => v.Key) + .ToListAsync(cancellationToken).ConfigureAwait(false); + #pragma warning restore CS8602, CS8604 + if (steps.Count == 0) return ScreenResult.NotFound(); + + // The newest submission of a version is the one that matters, as in the API. + return ScreenResult.Ok(new ValidationStatusViewModel + { + Id = id, + Submissions = steps + .GroupBy(s => s.PackageVersion, StringComparer.OrdinalIgnoreCase) + .Select(g => + { + var latest = g.First().SubmissionId; + var submission = g.Where(s => s.SubmissionId == latest).OrderBy(s => s.Key).ToList(); + var index = submission.FirstOrDefault(s => s.Type == PackageValidation.IndexType); + + return new ValidationSubmission( + g.Key ?? string.Empty, + latest, + index?.State switch + { + PackageValidationState.Succeeded => "Available", + PackageValidationState.Failed => "Quarantined", + _ => "Validating", + }, + submission); + }) + .OrderByDescending(s => NuGet.Versioning.NuGetVersion.TryParse(s.Version, out var v) ? v : null) + .ToList(), + }); + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Policies/PolicyScreenSupport.cs b/src/BaGet.Identity.Application/UseCases/Policies/PolicyScreenSupport.cs new file mode 100644 index 000000000..240888eff --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Policies/PolicyScreenSupport.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; + +namespace BaGet.Identity.Application.UseCases.Policies; + +/// +/// What the retention, scanning and replication use cases share: the lists their forms choose from and the one-line descriptions of +/// a policy or a replication (also used by the views through RetentionControllerBase.Describe / ReplicationControllerBase.Describe). +/// +internal static class PolicyScreenSupport +{ + /// The repositories a retention policy or hold can name (virtual ones store nothing), by name. + public static async Task> RetentionRepositoriesAsync(IRepositoryService repositories, CancellationToken cancellationToken) + => (await repositories.ListAsync(cancellationToken)) + .Where(r => r.Kind != RepositoryKind.Virtual).OrderBy(r => r.Name, StringComparer.Ordinal).ToList(); + + /// The names of the projects a policy can name. + public static async Task> ProjectNamesAsync(IAccessAdministration access, CancellationToken cancellationToken) + => (await access.ListProjectsAsync(cancellationToken)).Select(p => p.Name).OrderBy(n => n, StringComparer.Ordinal).ToList(); + + /// The local repositories a replication can name (remote and virtual ones are not replicated), by name. + public static async Task> ReplicationRepositoriesAsync(IRepositoryService repositories, CancellationToken cancellationToken) + => (await repositories.ListAsync(cancellationToken)) + .Where(r => r.Kind == RepositoryKind.Local).OrderBy(r => r.Name, StringComparer.Ordinal).ToList(); + + /// The schedule and triggers of a configuration in a few words. + public static string DescribeReplication(ReplicationConfig c) + { + var parts = new List { c.Direction == ReplicationDirection.Push ? "push" : "pull" }; + if (c.OnDeploy) parts.Add("on deploy"); + parts.Add(c.ScheduleMinutes is int minutes ? "every " + minutes + " min" : "manual"); + if (c.PropagateDeletes) parts.Add("deletes follow"); + parts.Add(c.Conflict == ReplicationConflict.SourceWins ? "source wins" : "target wins"); + + return string.Join(", ", parts); + } + + /// The rules of a policy in one line, for the lists. + public static string DescribeRetention(RetentionPolicy p) + { + var rules = new List(); + if (p.KeepLast is int keep) rules.Add($"keep the newest {keep}"); + if (p.OlderThanDays is int age) rules.Add($"older than {age} d"); + if (p.UnusedDays is int unused) rules.Add($"unused for {unused} d"); + if (p.CacheLimitBytes is long cache) rules.Add($"cache over {RetentionReport.FormatBytes(cache)}"); + if (p.UntaggedAfterDays is int untagged) rules.Add($"untagged for {untagged} d"); + if (p.CollectGarbage) rules.Add("garbage collection"); + var text = rules.Count == 0 ? "no rule" : string.Join(", ", rules); + if (p.PrereleaseOnly) text += " (prerelease only)"; + + return text; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Policies/PolicyUseCaseBase.cs b/src/BaGet.Identity.Application/UseCases/Policies/PolicyUseCaseBase.cs new file mode 100644 index 000000000..fb0e59651 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Policies/PolicyUseCaseBase.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Application.UseCases.Policies; + +/// +/// What the use cases of the retention, scanning and replication screens share: one change that asks the administrator's password, +/// turns an into the refusal shown on the screen the action comes back to, and says where to go afterwards. +/// +public abstract class PolicyUseCaseBase : AdminUseCaseBase +{ + /// Creates the base. + protected PolicyUseCaseBase(UserManager users, PasswordConfirmation confirmation, MaintenanceGate? gate) + : base(users, confirmation, gate) + { + } + + /// The user name recorded in the audit log. + protected static string? ActorOf(ClaimsPrincipal caller) => caller.Identity?.Name; + + /// + /// Runs one change: refused with 503 while the server is read-only, asks for the password when (the answer is the + /// refusal on ), turns an into the refusal shown there, else shows the message + /// returns. + /// + protected async Task> ActAsync( + ClaimsPrincipal caller, + string? password, + bool confirm, + Func> change, + ScreenRef screen, + IReadOnlyDictionary? route) + { + ThrowIfClosed(); + + if (confirm) + { + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(current, password)) return Back(screen, route, null, NotConfirmed); + } + + try + { + return Back(screen, route, await change(), null); + } + catch (AccessModelException e) + { + return Back(screen, route, null, e.Message); + } + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Policies/ReplicationUseCase.cs b/src/BaGet.Identity.Application/UseCases/Policies/ReplicationUseCase.cs new file mode 100644 index 000000000..23c5468b3 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Policies/ReplicationUseCase.cs @@ -0,0 +1,222 @@ +using System; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Policies; + +namespace BaGet.Identity.Application.UseCases.Policies; + +/// +/// The replication screens: the replications and the form that creates one, and one replication (save, test the connection, run, resume, stop, +/// delete, its log). Everything but stopping asks for the administrator's password. Every write is refused while the server is read-only. +/// The peer's API key is write only: no model carries it, whatever the request sent (), and it is never +/// part of a configuration's view. +/// +public sealed class ReplicationUseCase : PolicyUseCaseBase +{ + private static readonly ScreenRef ReplicationsScreen = ScreenCatalog.AdminReplication; + private static readonly ScreenRef ConfigScreen = ScreenCatalog.AdminReplicationConfig; + + private readonly IReplicationAdministration _replication; + private readonly ReplicationJobs _jobs; + private readonly IRepositoryService _repositories; + private readonly IReplicationInventory _inventory; + + /// Creates the use case. + public ReplicationUseCase( + UserManager users, + PasswordConfirmation confirmation, + IReplicationAdministration replication, + ReplicationJobs jobs, + IRepositoryService repositories, + IReplicationInventory inventory, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _replication = replication ?? throw new ArgumentNullException(nameof(replication)); + _jobs = jobs ?? throw new ArgumentNullException(nameof(jobs)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _inventory = inventory ?? throw new ArgumentNullException(nameof(inventory)); + } + + // ------------------------------------------------------------------ replications + + /// Lists the replications. is the address to come back to after signing in again. + public async Task> GetReplicationsAsync(ClaimsPrincipal caller, string? returnPage, CancellationToken cancellationToken) + => ScreenResult.Ok(await ShowReplicationsAsync(new ReplicationViewModel(), caller, returnPage, cancellationToken)); + + /// Creates a replication and opens it. + public async Task> CreateAsync(ClaimsPrincipal caller, ReplicationBody? body, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var form = body?.Form ?? new ReplicationForm(); + var model = new ReplicationViewModel { Form = form.WithoutSecret() }; + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(current, body?.Password)) + { + model.Error = NotConfirmed; + + return ScreenResult.Invalid(await ShowReplicationsAsync(model, caller, returnPage, cancellationToken), NotConfirmed); + } + + try + { + var config = await _replication.SaveAsync(form.ToInput(0), ActorOf(caller), cancellationToken); + + return Back(ConfigScreen, Route(("key", config.Key)), $"Replication {config.Name} was created.", null); + } + catch (AccessModelException e) + { + model.Error = e.Message; + + return ScreenResult.Invalid(await ShowReplicationsAsync(model, caller, returnPage, cancellationToken), e.Message); + } + } + + private async Task ShowReplicationsAsync(ReplicationViewModel model, ClaimsPrincipal caller, string? returnPage, CancellationToken cancellationToken) + { + model.Replications = await _replication.ListAsync(cancellationToken); + model.Repositories = await PolicyScreenSupport.ReplicationRepositoriesAsync(_repositories, cancellationToken); + await Confirmation.LoadAsync(model, caller, returnPage); + + return model; + } + + // ------------------------------------------------------------------ one replication + + /// Shows the configuration. + public async Task> GetConfigAsync(ClaimsPrincipal caller, int key, string? returnPage, CancellationToken cancellationToken) + { + var model = new ReplicationConfigViewModel { Key = key }; + if (!await LoadConfigAsync(model, cancellationToken)) return ScreenResult.NotFound(); + + model.Form = ReplicationForm.From(model.View!); + await Confirmation.LoadAsync(model, caller, returnPage); + + return ScreenResult.Ok(model); + } + + /// Saves the settings. + public Task> SaveAsync(ClaimsPrincipal caller, int key, ReplicationBody? body, CancellationToken cancellationToken) + => ActAsync(caller, body?.Password, confirm: true, async () => + { + var config = await _replication.SaveAsync((body?.Form ?? new ReplicationForm()).ToInput(key), ActorOf(caller), cancellationToken); + + return $"Replication {config.Name} was saved."; + }, ConfigScreen, Route(("key", key))); + + /// Tests the connection with the typed settings; saves nothing. + public async Task> TestAsync( + ClaimsPrincipal caller, int key, ReplicationBody? body, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var form = body?.Form ?? new ReplicationForm(); + var model = new ReplicationConfigViewModel { Key = key, Form = form.WithoutSecret() }; + if (!await LoadConfigAsync(model, cancellationToken)) return ScreenResult.NotFound(); + + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(current, body?.Password)) + { + const string refusal = "The confirmation is incorrect, so nothing was tested."; + model.Error = refusal; + await Confirmation.LoadAsync(model, caller, returnPage); + + return ScreenResult.Invalid(model, refusal); + } + + model.Test = await _replication.TestAsync(form.ToInput(key), cancellationToken); + await Confirmation.LoadAsync(model, caller, returnPage); + + return ScreenResult.Ok(model); + } + + /// Starts a run. + public async Task> RunAsync(ClaimsPrincipal caller, int key, string? password, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var view = await _replication.GetAsync(key, cancellationToken); + if (view == null) return ScreenResult.NotFound(); + + return await ActAsync(caller, password, confirm: true, () => Start(caller, key, view.Config, "manual", null), ConfigScreen, Route(("key", key))); + } + + /// Starts a run that continues the last interrupted or failed one. + public async Task> ResumeAsync(ClaimsPrincipal caller, int key, string? password, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var view = await _replication.GetAsync(key, cancellationToken); + if (view == null) return ScreenResult.NotFound(); + + var runs = await _replication.ListRunsAsync(key, 1, cancellationToken); + var last = runs.FirstOrDefault(); + var resume = last != null && last.Status is ReplicationRunStatus.Failed or ReplicationRunStatus.Interrupted ? last.Key : (int?)null; + + return await ActAsync(caller, password, confirm: true, () => Start(caller, key, view.Config, "resume", resume), ConfigScreen, Route(("key", key))); + } + + private Task Start(ClaimsPrincipal caller, int key, ReplicationConfig config, string trigger, int? resumedFrom) + { + if (!config.Enabled) throw new ReplicationException($"The replication '{config.Name}' is disabled: enable it first."); + if (!_jobs.TryStart(key, trigger, ActorOf(caller), resumedFrom, out var refusal)) throw new ReplicationException(refusal ?? "The run was not started."); + + return Task.FromResult("The replication started; the log below shows its progress."); + } + + /// Asks the running replication to stop; it ends as interrupted and can be resumed. + public async Task> StopAsync(int key, CancellationToken cancellationToken) + { + ThrowIfClosed(); + if (await _replication.GetAsync(key, cancellationToken) == null) return ScreenResult.NotFound(); + + return _jobs.Cancel(key) + ? Back(ConfigScreen, Route(("key", key)), "The replication was asked to stop; it ends as interrupted.", null) + : Back(ConfigScreen, Route(("key", key)), null, "No run of this replication is going on this server."); + } + + /// Deletes the configuration with its log. + public async Task> DeleteAsync(ClaimsPrincipal caller, int key, string? password, CancellationToken cancellationToken) + { + ThrowIfClosed(); + if (await _replication.GetAsync(key, cancellationToken) == null) return ScreenResult.NotFound(); + + return await ActAsync(caller, password, confirm: true, async () => + { + await _replication.DeleteAsync(key, ActorOf(caller), cancellationToken); + + return "The replication was deleted. What it copied stays where it is."; + }, ReplicationsScreen, null); + } + + private async Task LoadConfigAsync(ReplicationConfigViewModel model, CancellationToken cancellationToken) + { + model.View = await _replication.GetAsync(model.Key, cancellationToken); + if (model.View == null) return false; + + model.Runs = await _replication.ListRunsAsync(model.Key, 25, cancellationToken); + model.Job = _jobs.Get(model.Key); + model.Repositories = await PolicyScreenSupport.ReplicationRepositoriesAsync(_repositories, cancellationToken); + if (model.View.Repository != null) + { + try + { + model.LocalItems = (await _inventory.GetAsync(model.View.Repository, summary: true, cancellationToken))?.Count; + } + catch (Exception e) when (e is not OperationCanceledException) + { + model.LocalItems = null; + } + } + + return true; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Policies/RetentionUseCase.cs b/src/BaGet.Identity.Application/UseCases/Policies/RetentionUseCase.cs new file mode 100644 index 000000000..6fdb217b8 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Policies/RetentionUseCase.cs @@ -0,0 +1,231 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using BaGet.Identity.Application.Models.Policies; + +namespace BaGet.Identity.Application.UseCases.Policies; + +/// +/// The retention screens: the policies and the form that creates one, one policy (save, dry run, run now, delete) and the legal holds. +/// Creating, saving, running and deleting a policy and lifting a hold ask for the administrator's password; a dry run and placing a hold +/// do not. A refusal of the administration () is shown on the screen the action comes back to. Every +/// write is refused while the server is read-only. +/// +public sealed class RetentionUseCase : PolicyUseCaseBase +{ + private static readonly ScreenRef PoliciesScreen = ScreenCatalog.AdminRetention; + private static readonly ScreenRef PolicyScreen = ScreenCatalog.AdminRetentionPolicy; + private static readonly ScreenRef HoldsScreen = ScreenCatalog.AdminRetentionHolds; + + private readonly IRetentionAdministration _retention; + private readonly RetentionJobs _jobs; + private readonly IRepositoryService _repositories; + private readonly IAccessAdministration _access; + + /// Creates the use case. + public RetentionUseCase( + UserManager users, + PasswordConfirmation confirmation, + IRetentionAdministration retention, + RetentionJobs jobs, + IRepositoryService repositories, + IAccessAdministration access, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _retention = retention ?? throw new ArgumentNullException(nameof(retention)); + _jobs = jobs ?? throw new ArgumentNullException(nameof(jobs)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + } + + // ------------------------------------------------------------------ policies + + /// Lists the policies. is the address to come back to after signing in again. + public async Task> GetPoliciesAsync(ClaimsPrincipal caller, string? returnPage, CancellationToken cancellationToken) + { + var model = new RetentionViewModel(); + + return ScreenResult.Ok(await ShowPoliciesAsync(model, caller, returnPage, cancellationToken)); + } + + /// Creates a policy and opens it. + public async Task> CreateAsync(ClaimsPrincipal caller, RetentionPolicyBody? body, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = new RetentionViewModel { Form = body?.Form ?? new RetentionPolicyForm() }; + var current = await CurrentAsync(caller); + if (current == null) return ScreenResult.SignIn(); + + if (!await Confirmation.IsConfirmedAsync(current, body?.Password)) + { + model.Error = NotConfirmed; + + return ScreenResult.Invalid(await ShowPoliciesAsync(model, caller, returnPage, cancellationToken), NotConfirmed); + } + + try + { + var policy = await _retention.SavePolicyAsync(model.Form.ToInput(0), ActorOf(caller), cancellationToken); + + return Back(PolicyScreen, Route(("key", policy.Key)), $"Policy {policy.Name} was created.", null); + } + catch (AccessModelException e) + { + model.Error = e.Message; + + return ScreenResult.Invalid(await ShowPoliciesAsync(model, caller, returnPage, cancellationToken), e.Message); + } + } + + private async Task ShowPoliciesAsync(RetentionViewModel model, ClaimsPrincipal caller, string? returnPage, CancellationToken cancellationToken) + { + model.Policies = await _retention.ListPoliciesAsync(cancellationToken); + model.Repositories = await PolicyScreenSupport.RetentionRepositoriesAsync(_repositories, cancellationToken); + model.ProjectNames = await PolicyScreenSupport.ProjectNamesAsync(_access, cancellationToken); + await Confirmation.LoadAsync(model, caller, returnPage); + + return model; + } + + // ------------------------------------------------------------------ one policy + + /// Shows the policy. + public async Task> GetPolicyAsync(ClaimsPrincipal caller, int key, string? returnPage, CancellationToken cancellationToken) + { + var model = new RetentionPolicyViewModel { Key = key }; + if (!await LoadPolicyAsync(model, cancellationToken)) return ScreenResult.NotFound(); + + model.Form = RetentionPolicyForm.From(model.View!); + await Confirmation.LoadAsync(model, caller, returnPage); + + return ScreenResult.Ok(model); + } + + /// Saves the rules. + public Task> SaveAsync(ClaimsPrincipal caller, int key, RetentionPolicyBody? body, CancellationToken cancellationToken) + => ActAsync(caller, body?.Password, confirm: true, async () => + { + var policy = await _retention.SavePolicyAsync((body?.Form ?? new RetentionPolicyForm()).ToInput(key), ActorOf(caller), cancellationToken); + + return $"Policy {policy.Name} was saved."; + }, PolicyScreen, Route(("key", key))); + + /// Starts a dry run: the report of what a run would delete. + public async Task> DryRunAsync(ClaimsPrincipal caller, int key, CancellationToken cancellationToken) + { + ThrowIfClosed(); + if (await _retention.GetPolicyAsync(key, cancellationToken) == null) return ScreenResult.NotFound(); + + return _jobs.TryStart(key, dryRun: true, ActorOf(caller), out var refusal) + ? Back(PolicyScreen, Route(("key", key)), "The dry run started; nothing is deleted.", null) + : Back(PolicyScreen, Route(("key", key)), null, refusal); + } + + /// Starts a run that deletes. + public async Task> RunAsync(ClaimsPrincipal caller, int key, string? password, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var view = await _retention.GetPolicyAsync(key, cancellationToken); + if (view == null) return ScreenResult.NotFound(); + + return await ActAsync(caller, password, confirm: true, () => + { + if (!view.Policy.Enabled) throw new RetentionException("The policy is disabled: enable it first (a dry run works either way)."); + if (!_jobs.TryStart(key, dryRun: false, ActorOf(caller), out var refusal)) throw new RetentionException(refusal ?? "The run was not started."); + + return Task.FromResult($"{view.Policy.Name} started; versions it selects are deleted."); + }, PolicyScreen, Route(("key", key))); + } + + /// Deletes the policy (what it deleted stays deleted). + public async Task> DeleteAsync(ClaimsPrincipal caller, int key, string? password, CancellationToken cancellationToken) + { + ThrowIfClosed(); + if (await _retention.GetPolicyAsync(key, cancellationToken) == null) return ScreenResult.NotFound(); + + return await ActAsync(caller, password, confirm: true, async () => + { + await _retention.DeletePolicyAsync(key, ActorOf(caller), cancellationToken); + + return "The policy was deleted."; + }, PoliciesScreen, null); + } + + private async Task LoadPolicyAsync(RetentionPolicyViewModel model, CancellationToken cancellationToken) + { + model.View = await _retention.GetPolicyAsync(model.Key, cancellationToken); + if (model.View == null) return false; + + model.Status = _jobs.Get(model.Key); + model.Repositories = await PolicyScreenSupport.RetentionRepositoriesAsync(_repositories, cancellationToken); + model.ProjectNames = await PolicyScreenSupport.ProjectNamesAsync(_access, cancellationToken); + + return true; + } + + // ------------------------------------------------------------------ holds + + /// Lists the holds (of only, when given). + public async Task> GetHoldsAsync(ClaimsPrincipal caller, string? repository, string? returnPage, CancellationToken cancellationToken) + { + var model = new RetentionHoldsViewModel { Repository = repository }; + + return ScreenResult.Ok(await ShowHoldsAsync(model, caller, returnPage, cancellationToken)); + } + + /// Places a hold. + public async Task> AddHoldAsync( + ClaimsPrincipal caller, string? repository, RetentionHoldForm? form, string? returnPage, CancellationToken cancellationToken) + { + ThrowIfClosed(); + + var model = new RetentionHoldsViewModel + { + Repository = repository, + HoldRepository = form?.HoldRepository, + HoldName = form?.HoldName, + HoldVersion = form?.HoldVersion, + Reason = form?.Reason, + }; + + try + { + var hold = await _retention.AddHoldAsync( + model.HoldRepository ?? string.Empty, model.HoldName ?? string.Empty, model.HoldVersion, model.Reason, ActorOf(caller), cancellationToken); + + return Back( + HoldsScreen, + Route(("repository", repository)), + $"{hold.Name}{(string.IsNullOrEmpty(hold.Version) ? string.Empty : " " + hold.Version)} is on legal hold.", + null); + } + catch (AccessModelException e) + { + model.Error = e.Message; + + return ScreenResult.Invalid(await ShowHoldsAsync(model, caller, returnPage, cancellationToken), e.Message); + } + } + + /// Lifts a hold. + public Task> RemoveHoldAsync(ClaimsPrincipal caller, string? repository, RetentionHoldRemoval? removal, CancellationToken cancellationToken) + => ActAsync(caller, removal?.Password, confirm: true, async () => + { + return await _retention.RemoveHoldAsync(removal?.Key ?? 0, ActorOf(caller), cancellationToken) ? "The hold was lifted." : "That hold no longer exists."; + }, HoldsScreen, Route(("repository", repository))); + + private async Task ShowHoldsAsync(RetentionHoldsViewModel model, ClaimsPrincipal caller, string? returnPage, CancellationToken cancellationToken) + { + model.Holds = await _retention.ListHoldsAsync(model.Repository, cancellationToken); + model.Repositories = await PolicyScreenSupport.RetentionRepositoriesAsync(_repositories, cancellationToken); + await Confirmation.LoadAsync(model, caller, returnPage); + + return model; + } +} diff --git a/src/BaGet.Identity.Application/UseCases/Policies/ScanningUseCase.cs b/src/BaGet.Identity.Application/UseCases/Policies/ScanningUseCase.cs new file mode 100644 index 000000000..cd062f5e8 --- /dev/null +++ b/src/BaGet.Identity.Application/UseCases/Policies/ScanningUseCase.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Application.UseCases.Policies; + +/// +/// The vulnerability scanning screens: the overview of every repository and project, the dashboard of one repository (its findings, its +/// policy, Scan now) and the policy of a project. Saving a policy asks for the administrator's password; starting a scan does not. +/// Every write is refused while the server is read-only. The links to the package screens of the findings are s: the +/// use case knows no routes. +/// +public sealed class ScanningUseCase : PolicyUseCaseBase +{ + private static readonly ScreenRef RepositoryScreen = ScreenCatalog.AdminScanRepository; + private static readonly ScreenRef ProjectScreen = ScreenCatalog.AdminScanProject; + + private readonly IServiceProvider _services; + private readonly IOptionsSnapshot _options; + private readonly ITrivyRunner _trivy; + private readonly IServiceScopeFactory _scopes; + private readonly IRepositoryService _repositories; + private readonly IAccessAdministration _access; + private readonly IScanPolicyService _policies; + private readonly AdminJobService _jobs; + + /// Creates the use case. + public ScanningUseCase( + UserManager users, + PasswordConfirmation confirmation, + IServiceProvider services, + IOptionsSnapshot options, + ITrivyRunner trivy, + IServiceScopeFactory scopes, + IRepositoryService repositories, + IAccessAdministration access, + IScanPolicyService policies, + AdminJobService jobs, + MaintenanceGate? gate = null) + : base(users, confirmation, gate) + { + _services = services ?? throw new ArgumentNullException(nameof(services)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _trivy = trivy ?? throw new ArgumentNullException(nameof(trivy)); + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _policies = policies ?? throw new ArgumentNullException(nameof(policies)); + _jobs = jobs ?? throw new ArgumentNullException(nameof(jobs)); + } + + // ------------------------------------------------------------------ overview + + /// Shows the overview. + public async Task> GetOverviewAsync(CancellationToken cancellationToken) + { + var options = _options.Value; + var model = new ScanningViewModel + { + Options = options, + Settings = new ScanningSettingsView(options.Enabled, options.ScanOnDeploy, options.OsvUrl, options.OsvOfflinePath, options.RescanInterval), + TrivyConfigured = _trivy.IsConfigured(options), + }; + + var rows = new List(); + foreach (var repository in (await _repositories.ListAsync(cancellationToken)).Where(r => r.Kind != RepositoryKind.Virtual)) + { + using var scope = _scopes.CreateRepositoryScope(repository); + var summary = await scope.ServiceProvider.GetRequiredService().SummarizeAsync(cancellationToken); + rows.Add(new ScanningRepositoryRow(repository, summary, await _policies.GetEffectiveAsync(repository.Key, cancellationToken))); + } + + model.Repositories = rows; + + var projects = new List(); + foreach (var project in await _access.ListProjectsAsync(cancellationToken)) + { + projects.Add(new ScanningProjectRow(project, await _policies.GetAsync(ScanPolicyScope.Project, project.Key, cancellationToken) != null)); + } + + model.Projects = projects; + + return ScreenResult.Ok(model); + } + + // ------------------------------------------------------------------ one repository + + /// Shows the dashboard of a repository: its findings from up, (from 1; 0 is the first). + public async Task> GetRepositoryAsync( + ClaimsPrincipal caller, string? name, int minSeverity, int pageNumber, string? returnPage, CancellationToken cancellationToken) + { + var model = new ScanRepositoryViewModel { Name = name, MinSeverity = minSeverity, PageNumber = pageNumber == 0 ? 1 : pageNumber }; + if (!await LoadRepositoryAsync(model, cancellationToken)) return ScreenResult.NotFound(); + + await Confirmation.LoadAsync(model, caller, returnPage); + + return ScreenResult.Ok(model); + } + + /// Saves the repository policy; empty values remove it. + public async Task> SaveRepositoryPolicyAsync( + ClaimsPrincipal caller, string? name, ScanPolicyBody? body, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var repository = await FindRepositoryAsync(name, cancellationToken); + if (repository == null) return ScreenResult.NotFound(); + + return await ActAsync(caller, body?.Password, confirm: true, async () => + { + var values = (body ?? new ScanPolicyBody(null, null, null, false, null)).ToFields().ToValues(); + await _policies.SaveAsync(ScanPolicyScope.Repository, repository.Key, values, ActorOf(caller), cancellationToken); + + return values.IsEmpty ? $"The scanning policy of {repository.Name} was removed." : $"The scanning policy of {repository.Name} was saved."; + }, RepositoryScreen, Route(("name", name))); + } + + /// Starts a scan of every artifact of the repository in the background. + public async Task> ScanAsync(ClaimsPrincipal caller, string? name, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var repository = await FindRepositoryAsync(name, cancellationToken); + if (repository == null) return ScreenResult.NotFound(); + + var route = Route(("name", name)); + var operation = _jobs.Operations.FirstOrDefault(o => o.Name == "vulnerability-scan"); + if (operation == null || !operation.IsAvailable(_services) || !operation.AppliesTo(repository)) + { + return Back( + RepositoryScreen, route, null, "Scanning is not available: it is turned off (Scanning:Enabled) or the repository cannot be scanned."); + } + + return _jobs.TryStart(operation.Name, repository, ActorOf(caller), out var refusal) + ? Back(RepositoryScreen, route, $"A scan of {repository.Name} started. Its status is shown below and on the Operations page.", null) + : Back(RepositoryScreen, route, null, refusal); + } + + private async Task FindRepositoryAsync(string? name, CancellationToken cancellationToken) + { + var repository = await _repositories.FindAsync(name, cancellationToken); + + return repository == null || repository.Kind == RepositoryKind.Virtual ? null : repository; + } + + private async Task LoadRepositoryAsync(ScanRepositoryViewModel model, CancellationToken cancellationToken) + { + model.Repository = await FindRepositoryAsync(model.Name, cancellationToken); + if (model.Repository == null) return false; + + model.Own = await _policies.GetAsync(ScanPolicyScope.Repository, model.Repository.Key, cancellationToken); + model.Effective = await _policies.GetEffectiveAsync(model.Repository.Key, cancellationToken); + model.Job = _jobs.Get("vulnerability-scan", model.Repository.Name); + + using var scope = _scopes.CreateRepositoryScope(model.Repository); + var scans = scope.ServiceProvider.GetRequiredService(); + model.Summary = await scans.SummarizeAsync(cancellationToken); + var page = Math.Max(1, model.PageNumber); + var size = ScanRepositoryViewModel.PageSize; + var results = await scans.ListAsync(Math.Clamp(model.MinSeverity, 0, PackageVulnerabilityRules.MaxSeverity), (page - 1) * size, size + 1, cancellationToken); + model.HasMore = results.Count > size; + model.Findings = results.Take(size).ToList(); + + var links = new Dictionary(); + foreach (var result in model.Findings) + { + if (PackageScreen(model.Repository, result) is { } link) links[result.Key] = link; + } + + model.PackageLinks = links; + + return true; + } + + // The package screen of a version in its format (the repository's package page); null where there is none. + private static ScreenLink? PackageScreen(RepositoryInfo info, ScanResult result) + { + var repo = info.IsDefault ? null : info.Name; + var name = result.Name ?? string.Empty; + var version = result.Version ?? string.Empty; + + switch (info.Format) + { + case RepositoryFormat.NuGet: + return new ScreenLink(ScreenCatalog.Package, Route(("id", name), ("version", version), ("repo", repo))); + case RepositoryFormat.Npm: + return new ScreenLink(ScreenCatalog.NpmPackage, Route(("id", name), ("version", version), ("repo", repo))); + case RepositoryFormat.Maven: + return MavenNames.TryParseArtifactName(name, out var group, out var artifact) + ? new ScreenLink(ScreenCatalog.MavenArtifact, Route(("group", group), ("artifact", artifact), ("version", version), ("repo", repo))) + : null; + case RepositoryFormat.Docker: + return new ScreenLink(ScreenCatalog.DockerImage, Route(("image", name), ("digest", version), ("repo", repo))); + default: + return null; + } + } + + // ------------------------------------------------------------------ one project + + /// Shows the policy of the project. + public async Task> GetProjectAsync(ClaimsPrincipal caller, string? name, string? returnPage, CancellationToken cancellationToken) + { + var model = new ScanProjectViewModel { Name = name }; + model.Project = await _access.GetProjectAsync(name ?? string.Empty, cancellationToken); + if (model.Project == null) return ScreenResult.NotFound(); + + model.Own = await _policies.GetAsync(ScanPolicyScope.Project, model.Project.Project.Key, cancellationToken); + await Confirmation.LoadAsync(model, caller, returnPage); + + return ScreenResult.Ok(model); + } + + /// Saves the project policy; empty values remove it. + public async Task> SaveProjectPolicyAsync( + ClaimsPrincipal caller, string? name, ScanPolicyBody? body, CancellationToken cancellationToken) + { + ThrowIfClosed(); + var project = await _access.GetProjectAsync(name ?? string.Empty, cancellationToken); + if (project == null) return ScreenResult.NotFound(); + + return await ActAsync(caller, body?.Password, confirm: true, async () => + { + var values = (body ?? new ScanPolicyBody(null, null, null, false, null)).ToFields().ToValues(); + await _policies.SaveAsync(ScanPolicyScope.Project, project.Project.Key, values, ActorOf(caller), cancellationToken); + + return values.IsEmpty ? $"The scanning policy of {project.Project.Name} was removed." : $"The scanning policy of {project.Project.Name} was saved."; + }, ProjectScreen, Route(("name", name))); + } +} diff --git a/src/BaGet.Identity.FrontEnd/BaGet.Identity.FrontEnd.csproj b/src/BaGet.Identity.FrontEnd/BaGet.Identity.FrontEnd.csproj new file mode 100644 index 000000000..6176e0fad --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/BaGet.Identity.FrontEnd.csproj @@ -0,0 +1,38 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's account and administration screens: the view controllers and views of the user accounts, package management and administration pages. + BaGet.Identity + true + enable + Extension.$(MSBuildProjectName) + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountController.cs new file mode 100644 index 000000000..4774398fa --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountController.cs @@ -0,0 +1,155 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The sign-in side of the account screens: sign in (password and external provider), the two second-factor steps, sign out, +/// registration, email confirmation, the password reset pair and re-authentication. It replaces the Razor Pages of +/// Pages/Account of the same names: same URLs, same ?handler= forms. The work is done by the JSON twin (through the use +/// cases of BaGet.Identity.Application); this controller binds the form, calls the twin in process and renders the view. The external +/// provider's challenge and callback are browser-only steps: they have no twin and call directly. +/// +public sealed class AccountController : AccountControllerBase +{ + private ExternalSignInUseCase External => HttpContext.RequestServices.GetRequiredService(); + + // ----- /account/login + + /// The sign-in form. + [Route("account/login"), HttpGet, HttpHead, PageHandler] + public async Task Login(string? returnUrl) + => Render(await Api(api => api.Login(returnUrl)), "Login", modelShowsFormErrors: true); + + /// The sign-in form was posted. + [Route("account/login"), HttpPost, PageHandler] + public async Task LoginPost(LoginForm form) + => Render(await Api(api => api.LoginPost(form)), "Login", modelShowsFormErrors: true); + + /// "Sign in with the provider" was posted (browser-only: it sends the visitor to the provider). + [Route("account/login"), HttpPost, PageHandler("External")] + public IActionResult LoginExternal(string? returnUrl) + { + // The posted button names the provider (none: the only one configured). + var challenge = External.StartSignIn(Request.Form["provider"].ToString(), Url.Action(nameof(Login), "Account", new { ReturnUrl = returnUrl, handler = "Callback" })!); + + return challenge == null ? NotFound() : Challenge(challenge.Properties, challenge.Scheme); + } + + /// The provider has signed the user in (browser-only). + [Route("account/login"), HttpGet, PageHandler("Callback")] + public async Task LoginCallback(string? returnUrl, CancellationToken cancellationToken) + => Render(await External.CompleteSignInAsync(returnUrl, cancellationToken), "Login", modelShowsFormErrors: true); + + // ----- /account/loginwith2fa + + /// The authenticator code form. + [Route("account/loginwith2fa"), HttpGet, HttpHead, PageHandler] + public async Task LoginWith2fa(bool rememberMe, string? returnUrl) + => Render(await Api(api => api.LoginWith2fa(rememberMe, returnUrl)), "LoginWith2fa", modelShowsFormErrors: true); + + /// The authenticator code was posted. + [Route("account/loginwith2fa"), HttpPost, PageHandler] + public async Task LoginWith2faPost(TwoFactorLoginForm form) + => Render(await Api(api => api.LoginWith2faPost(form)), "LoginWith2fa", modelShowsFormErrors: true); + + // ----- /account/loginwithrecoverycode + + /// The recovery code form. + [Route("account/loginwithrecoverycode"), HttpGet, HttpHead, PageHandler] + public async Task LoginWithRecoveryCode(string? returnUrl) + => Render(await Api(api => api.LoginWithRecoveryCode(returnUrl)), "LoginWithRecoveryCode", modelShowsFormErrors: true); + + /// The recovery code was posted. + [Route("account/loginwithrecoverycode"), HttpPost, PageHandler] + public async Task LoginWithRecoveryCodePost(RecoveryCodeLoginForm form) + => Render(await Api(api => api.LoginWithRecoveryCodePost(form)), "LoginWithRecoveryCode", modelShowsFormErrors: true); + + // ----- /account/logout + + /// The sign-out button (signing out is a POST, so a link elsewhere cannot do it). + [Route("account/logout"), HttpGet, HttpHead, PageHandler] + public async Task Logout() + => Render(await Api(api => api.Logout()), "Logout", _ => null); + + /// Signs the user out. + [Route("account/logout"), HttpPost, PageHandler] + public async Task LogoutPost() + => Render(await Api(api => api.LogoutPost()), "Logout", _ => null); + + // ----- /account/register + + /// The registration form (404 while Accounts:AllowRegistration is off). + [Route("account/register"), HttpGet, HttpHead, PageHandler] + public async Task Register(string? returnUrl) + => Render(await Api(api => api.Register(returnUrl)), "Register"); + + /// The registration form was posted. + [Route("account/register"), HttpPost, PageHandler] + public async Task RegisterPost(RegisterForm form, CancellationToken cancellationToken) + => Render(await Api(api => api.RegisterPost(form, cancellationToken)), "Register"); + + // ----- /account/confirmemail + + /// The target of the links in confirmation emails. + [Route("account/confirmemail"), HttpGet, HttpHead, PageHandler, RequiresEmail] + public async Task ConfirmEmail(string? userId, string? code, string? email) + => Render(await Api(api => api.ConfirmEmail(userId, code, email)), "ConfirmEmail"); + + // ----- /account/forgotpassword + + /// The "forgot password" form. + [Route("account/forgotpassword"), HttpGet, HttpHead, PageHandler, RequiresEmail] + public async Task ForgotPassword() + => Render(await Api(api => api.ForgotPassword()), "ForgotPassword"); + + /// The "forgot password" form was posted. + [Route("account/forgotpassword"), HttpPost, PageHandler, RequiresEmail] + public async Task ForgotPasswordPost(ForgotPasswordForm form) + => Render(await Api(api => api.ForgotPasswordPost(form)), "ForgotPassword"); + + // ----- /account/resetpassword + + /// The new-password form behind the link of a reset email. + [Route("account/resetpassword"), HttpGet, HttpHead, PageHandler, RequiresEmail] + public async Task ResetPassword(string? userId, string? code) + => Render(await Api(api => api.ResetPassword(userId, code)), "ResetPassword", modelShowsFormErrors: true); + + /// The new password was posted. + [Route("account/resetpassword"), HttpPost, PageHandler, RequiresEmail] + public async Task ResetPasswordPost(ResetPasswordForm form) + => Render(await Api(api => api.ResetPasswordPost(form)), "ResetPassword", modelShowsFormErrors: true); + + // ----- /account/reauthenticate + + /// The "confirm it is you" screen (only the target of the sign-in-again button; the form is elsewhere). + [Route("account/reauthenticate"), HttpGet, HttpHead, PageHandler, RequiresSignIn] + public async Task Reauthenticate(string? returnUrl) + => Render(await Api(api => api.Reauthenticate(returnUrl)), "Reauthenticate", modelShowsFormErrors: true); + + /// "Sign in again" was posted: sends the user to the provider (browser-only). + [Route("account/reauthenticate"), HttpPost, PageHandler, RequiresSignIn] + public async Task ReauthenticatePost(ReauthenticateForm form) + { + var (challenge, screen) = await External.StartReauthenticationAsync( + User, + Url.Action(nameof(Reauthenticate), "Account", new { form.ReturnUrl, handler = "Callback" })!, + form.ReturnUrl, + form.Provider); + + return challenge != null ? Challenge(challenge.Properties, challenge.Scheme) : Render(screen!, "Reauthenticate", modelShowsFormErrors: true); + } + + /// The provider answered (browser-only). + [Route("account/reauthenticate"), HttpGet, PageHandler("Callback"), RequiresSignIn] + public async Task ReauthenticateCallback(string? returnUrl) + => Render(await External.CompleteReauthenticationAsync(User, returnUrl), "Reauthenticate", modelShowsFormErrors: true); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountOrganizationsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountOrganizationsController.cs new file mode 100644 index 000000000..c62dc962e --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountOrganizationsController.cs @@ -0,0 +1,51 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Organizations; +using BaGet.Identity.Application.UseCases.Account; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The signed-in user's organizations: create one, and manage the members of those the user administers. It replaces the Razor +/// Page Account/Organizations: same URL, same ?handler= forms. The work is done by . +/// +public sealed class AccountOrganizationsController : AccountControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + /// The organizations of the user. + [Route("account/organizations"), HttpGet, HttpHead, PageHandler] + public async Task Organizations(CancellationToken cancellationToken) + => Render(await Api(api => api.Organizations(cancellationToken)), "Organizations"); + + /// Create an organization. + [Route("account/organizations"), HttpPost, PageHandler("Create")] + public async Task OrganizationsCreate(string name, CancellationToken cancellationToken) + => Render( + await Api(api => api.OrganizationsCreate(new CreateOrganizationForm { Name = name }, cancellationToken)), + "Organizations"); + + /// Add a member (organization administrators only). + [Route("account/organizations"), HttpPost, PageHandler("AddMember")] + public async Task OrganizationsAddMember(string organization, string userName, bool isAdmin, CancellationToken cancellationToken) + => Render( + await Api(api => api.OrganizationsAddMember( + new AddOrganizationMemberForm { Organization = organization, UserName = userName, IsAdmin = isAdmin }, + cancellationToken)), + "Organizations"); + + /// Remove a member (an administrator removes anyone; any member may leave). + [Route("account/organizations"), HttpPost, PageHandler("RemoveMember")] + public async Task OrganizationsRemoveMember(string organization, string? userName, CancellationToken cancellationToken) + => Render( + await Api(api => api.OrganizationsRemoveMember( + new RemoveOrganizationMemberForm { Organization = organization, UserName = userName }, + cancellationToken)), + "Organizations"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountPackagesController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountPackagesController.cs new file mode 100644 index 000000000..3f65107cb --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountPackagesController.cs @@ -0,0 +1,37 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The signed-in user's own packages and permissions: "My packages", "My access" and the redirect to the user's profile. It +/// replaces the Razor Pages Account/Packages, Account/Access and Account/Profile: same URLs. Every action needs a signed-in user. +/// The work is done by . +/// +public sealed class AccountPackagesController : AccountControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + /// The package IDs the user owns, per repository. + [Route("account/packages"), HttpGet, HttpHead, PageHandler] + public async Task Packages(CancellationToken cancellationToken) + => Render(await Api(api => api.Packages(cancellationToken)), "Packages"); + + /// What the user may do in each repository. + [Route("account/access"), HttpGet, HttpHead, PageHandler] + public async Task Access(string? package, CancellationToken cancellationToken) + => Render(await Api(api => api.Access(package, cancellationToken)), "Access"); + + /// The signed-in user's own profile: forwards to /profiles/{name}. + [Route("account/profile"), HttpGet, HttpHead, PageHandler] + public async Task MyProfile() + => Render(await Api(api => api.MyProfile()), "MyProfile", _ => null); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountSettingsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountSettingsController.cs new file mode 100644 index 000000000..830bc4d21 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AccountSettingsController.cs @@ -0,0 +1,130 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using BaGet.Identity.Application.Models.Account; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.UseCases.Account; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The signed-in user's own settings: account settings (email, password, delete the account), two-factor authentication and API +/// keys. It replaces the Razor Pages Account/Settings, Account/TwoFactor and Account/ApiKeys: same URLs, same ?handler= forms. Every action needs a signed-in +/// user (a visitor is challenged, 404 while accounts are off). The work is done by +/// (the use cases of BaGet.Identity.Application); this controller binds the form, calls it in process and renders the view. +/// +public sealed class AccountSettingsController : AccountControllerBase +{ + /// + protected override bool RequiresSignIn => true; + + // ----- /account/settings + + /// Account settings. + [Route("account/settings"), HttpGet, HttpHead, PageHandler] + public async Task Settings() + => Render(await Api(api => api.Settings()), "Settings", modelShowsFormErrors: true); + + /// Change the password. + [Route("account/settings"), HttpPost, PageHandler("ChangePassword")] + public async Task SettingsChangePassword(string? currentPassword, string newPassword, string confirmPassword) + => Render( + await Api(api => api.SettingsChangePassword( + new ChangePasswordForm { CurrentPassword = currentPassword, NewPassword = newPassword, ConfirmPassword = confirmPassword })), + "Settings", + modelShowsFormErrors: true); + + /// Change the email address (asks the password again). + [Route("account/settings"), HttpPost, PageHandler("ChangeEmail")] + public async Task SettingsChangeEmail(string? newEmail, string? password) + => Render( + await Api(api => api.SettingsChangeEmail(new ChangeEmailForm { NewEmail = newEmail, Password = password })), + "Settings", + modelShowsFormErrors: true); + + /// Delete the account (asks the password again). + [Route("account/settings"), HttpPost, PageHandler("Delete")] + public async Task SettingsDelete(string? password, CancellationToken cancellationToken) + => Render( + await Api(api => api.SettingsDelete(new PasswordConfirmationForm { Password = password }, cancellationToken)), + "Settings", + modelShowsFormErrors: true); + + /// "Link this provider" was posted (browser-only: it sends the user to the provider, after the password check). + [Route("account/settings"), HttpPost, PageHandler("LinkExternal")] + public async Task SettingsLinkExternal(string? provider, string? password) + { + var (challenge, screen) = await HttpContext.RequestServices.GetRequiredService().StartLinkAsync( + User, + provider, + password, + Url.Action(nameof(Settings), "AccountSettings", new { handler = "LinkCallback" })!); + + return challenge != null ? Challenge(challenge.Properties, challenge.Scheme) : Render(screen!, "Settings", modelShowsFormErrors: true); + } + + /// The provider answered a link (browser-only). + [Route("account/settings"), HttpGet, PageHandler("LinkCallback")] + public async Task SettingsLinkCallback() + => Render(await HttpContext.RequestServices.GetRequiredService().CompleteLinkAsync(User), "Settings", modelShowsFormErrors: true); + + /// Unlink an external provider (asks the password again). + [Route("account/settings"), HttpPost, PageHandler("UnlinkExternal")] + public async Task SettingsUnlinkExternal(string? provider, string? password) + => Render( + await Api(api => api.SettingsUnlinkExternal(new UnlinkExternalForm { Provider = provider, Password = password })), + "Settings", + modelShowsFormErrors: true); + + // ----- /account/twofactor + + /// Two-factor authentication. + [Route("account/twofactor"), HttpGet, HttpHead, PageHandler] + public async Task TwoFactor() + => Render(await Api(api => api.TwoFactor()), "TwoFactor", modelShowsFormErrors: true); + + /// Turn two-factor authentication on with a code from the authenticator. + [Route("account/twofactor"), HttpPost, PageHandler("Enable")] + public async Task TwoFactorEnable(string? code) + => Render( + await Api(api => api.TwoFactorEnable(new TwoFactorCodeForm { Code = code })), + "TwoFactor", + modelShowsFormErrors: true); + + /// Turn two-factor authentication off (asks the password again). + [Route("account/twofactor"), HttpPost, PageHandler("Disable")] + public async Task TwoFactorDisable(string? password) + => Render( + await Api(api => api.TwoFactorDisable(new PasswordConfirmationForm { Password = password })), + "TwoFactor", + modelShowsFormErrors: true); + + /// Reset the authenticator (asks the password again). + [Route("account/twofactor"), HttpPost, PageHandler("Reset")] + public async Task TwoFactorReset(string? password) + => Render( + await Api(api => api.TwoFactorReset(new PasswordConfirmationForm { Password = password })), + "TwoFactor", + modelShowsFormErrors: true); + + // ----- /account/apikeys + + /// The user's API keys and the new-key form. + [Route("account/apikeys"), HttpGet, HttpHead, PageHandler] + public async Task ApiKeysIndex(CancellationToken cancellationToken) + => Render(await Api(api => api.ApiKeysIndex(cancellationToken)), "ApiKeys"); + + /// Create a key. + [Route("account/apikeys"), HttpPost, PageHandler("Create")] + public async Task ApiKeysCreate(ApiKeyForm form, CancellationToken cancellationToken) + => Render(await Api(api => api.ApiKeysCreate(form, cancellationToken)), "ApiKeys"); + + /// Revoke a key. + [Route("account/apikeys"), HttpPost, PageHandler("Revoke")] + public async Task ApiKeysRevoke(int key, CancellationToken cancellationToken) + => Render(await Api(api => api.ApiKeysRevoke(key, cancellationToken)), "ApiKeys"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminAuditController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminAuditController.cs new file mode 100644 index 000000000..d03bf3b64 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminAuditController.cs @@ -0,0 +1,23 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Access; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The access audit log (/admin/audit): one entry per change to groups, memberships, permission targets, grants, projects, the +/// repositories' project and anonymous-read switch, newest first, filtered by who made the change, what it was done to and the dates. +/// Read only; server administrators only. It replaces the Razor Page /Admin/Audit (same URL); the work is done by +/// the JSON twin () and this controller only renders its answer. +/// +public sealed class AdminAuditController : AccessControllerBase +{ + /// Lists the entries that match the filter (actor, subject, from, to). + [Route("admin/audit"), HttpGet, HttpHead, PageHandler] + public async Task Index(string? actor, string? subject, string? from, string? to, CancellationToken cancellationToken) + => Render(await Api(api => api.Get(actor, subject, from, to, cancellationToken)), "Index"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminGroupsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminGroupsController.cs new file mode 100644 index 000000000..b036c2a31 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminGroupsController.cs @@ -0,0 +1,64 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The groups screens of the administrator: the list with the new-group form (/admin/groups) and one group (/admin/groups/{name}: +/// rename, members, delete). They replace the Razor Pages /Admin/Groups and /Admin/GroupDetail (same URLs and handlers); the work is done by the JSON twin () and this controller only renders its +/// answers. Server administrators only; membership changes and deletion ask for the password again, and every POST is refused with 503 while the +/// read-only gate is closed (). +/// +public sealed class AdminGroupsController : AccessControllerBase +{ + /// Lists the groups. + [Route("admin/groups"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => ShowList(await Api(api => api.List(cancellationToken))); + + /// Creates a group and opens it. + [Route("admin/groups"), HttpPost, PageHandler] + public async Task Create(string? name, string? description, CancellationToken cancellationToken) + => ShowList(await Api(api => api.Create(new GroupCreation(name, description), cancellationToken))); + + /// Shows one group, with the member search for . + [Route("admin/groups/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Detail(string name, string? q, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Get(name, q, cancellationToken))); + + /// Renames the group. + [Route("admin/groups/{name}"), HttpPost, PageHandler("Rename")] + public async Task Rename(string name, string? newName, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Rename(name, new GroupRename(newName), cancellationToken))); + + /// Adds a user to the group. + [Route("admin/groups/{name}"), HttpPost, PageHandler("AddMember")] + public async Task AddMember(string name, string? userId, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.AddMember(name, new GroupMemberChange(userId, password), cancellationToken))); + + /// Removes a user from the group. + [Route("admin/groups/{name}"), HttpPost, PageHandler("RemoveMember")] + public async Task RemoveMember(string name, string? userId, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.RemoveMember(name, new GroupMemberChange(userId, password), cancellationToken))); + + /// Deletes the group with the grants and project roles that name it. + [Route("admin/groups/{name}"), HttpPost, PageHandler("Delete")] + public async Task Delete(string name, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Delete(name, new PasswordForm(password), cancellationToken))); + + /// A form posted to the group's own URL with no handler: the screen is rendered (the page had no default handler). + [Route("admin/groups/{name}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task DetailPost(string name, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Get(name, null, cancellationToken))); + + private IActionResult ShowList(UiApiResponse response) => RenderFlashed(response, "Index"); + + private IActionResult ShowDetail(UiApiResponse response) => RenderFlashed(response, "Detail"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminOperationsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminOperationsController.cs new file mode 100644 index 000000000..3096f7ba5 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminOperationsController.cs @@ -0,0 +1,95 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Operations; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The administrator's operational screens: maintenance operations (/admin/operations), the validation queue +/// (/admin/validation), abuse reports (/admin/abuse), the cluster status (/admin/cluster), the package formats +/// (/admin/formats) and the notice shown where there is no access model (/admin/access-unavailable). They replace the +/// Razor Pages of the same names (same URLs and handlers); the work is done by the JSON twin +/// () and this controller only renders its answers. Every write is refused with 503 while +/// the read-only gate is closed. +/// +public sealed class AdminOperationsController : AdminControllerBase +{ + // ---------------------------------------------------------------- Operations + + /// Lists the operations and their status. + [Route("admin/operations"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.GetOperations(cancellationToken)), "Index"); + + /// Starts an operation on a repository. + [Route("admin/operations"), HttpPost, PageHandler] + public async Task Start(string? operation, string? repository, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Start(new OperationForm(operation, repository, password), cancellationToken)), "Index"); + + // ---------------------------------------------------------------- Validation + + /// Lists the pending and quarantined submissions. + [Route("admin/validation"), HttpGet, HttpHead, PageHandler] + public async Task Validation(CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.GetValidation(cancellationToken)), "Validation"); + + /// Validates the submission again. + [Route("admin/validation"), HttpPost, PageHandler("Retry")] + public async Task Retry(string? submissionId, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Retry(new SubmissionForm(submissionId, null), cancellationToken)), "Validation"); + + /// Indexes the quarantined package although validation failed. + [Route("admin/validation"), HttpPost, PageHandler("Release")] + public async Task Release(string? submissionId, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Release(new SubmissionForm(submissionId, password), cancellationToken)), "Validation"); + + /// Deletes the quarantined package. + [Route("admin/validation"), HttpPost, PageHandler("Reject")] + public async Task Reject(string? submissionId, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Reject(new SubmissionForm(submissionId, password), cancellationToken)), "Validation"); + + // ---------------------------------------------------------------- Abuse + + /// Lists the abuse reports (the unresolved ones unless all). + [Route("admin/abuse"), HttpGet, HttpHead, PageHandler] + public async Task Abuse(bool all, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.GetAbuse(all, cancellationToken)), "Abuse"); + + /// Marks a report resolved. + [Route("admin/abuse"), HttpPost, PageHandler("Resolve")] + public async Task Resolve(int key, bool all, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Resolve(new AbuseForm(key, all), cancellationToken)), "Abuse"); + + /// Reopens a resolved report. + [Route("admin/abuse"), HttpPost, PageHandler("Reopen")] + public async Task Reopen(int key, bool all, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Reopen(new AbuseForm(key, all), cancellationToken)), "Abuse"); + + // ---------------------------------------------------------------- Cluster, Formats, AccessUnavailable + + /// The cluster status; ?refresh=true runs the health checks again. + [Route("admin/cluster"), HttpGet, HttpHead, PageHandler] + public async Task Cluster(bool refresh, CancellationToken cancellationToken) + => Render(await Api(api => api.GetCluster(refresh, cancellationToken)), "Cluster"); + + /// The package formats this server can host. + [Route("admin/formats"), HttpGet, HttpHead, PageHandler] + public async Task Formats(CancellationToken cancellationToken) + => Render(await Api(api => api.GetFormats(cancellationToken)), "Formats"); + + /// + /// Where the access screens send an administrator when the configured database has no access model (Azure Table): says so and + /// explains what applies instead. The page had no handler method at all, hence no . The page + /// has fixed text, so the view takes no model. + /// + [Route("admin/access-unavailable"), HttpGet, HttpHead] + public async Task AccessUnavailable() + => Render(await Api(api => Task.FromResult(api.GetAccessUnavailable())), "AccessUnavailable", _ => null); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminOrganizationsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminOrganizationsController.cs new file mode 100644 index 000000000..82fd04fc5 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminOrganizationsController.cs @@ -0,0 +1,63 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Organizations; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The administrator's organization screens: the list (/admin/organizations) and one organization +/// (/admin/organizations/{name}: rename, members, delete). They replace the Razor Pages /Admin/Organizations and +/// /Admin/OrganizationDetail (same URLs and handlers); the work is done by the JSON twin +/// () and this controller only renders its answers. Every change asks the administrator's +/// password again and is refused with 503 while the read-only gate is closed. +/// +public sealed class AdminOrganizationsController : AdminControllerBase +{ + /// Lists the organizations. + [Route("admin/organizations"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => Render(await Api(api => api.List(cancellationToken)), "Index"); + + /// Shows one organization. + [Route("admin/organizations/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Detail(string name, CancellationToken cancellationToken) + => Show(await Api(api => api.Get(name, cancellationToken))); + + /// Renames the organization. + [Route("admin/organizations/{name}"), HttpPost, PageHandler("Rename")] + public async Task Rename(string name, string? newName, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.Rename(name, new OrganizationRenameForm(newName, password), cancellationToken))); + + /// Deletes the organization. + [Route("admin/organizations/{name}"), HttpPost, PageHandler("Delete")] + public async Task Delete(string name, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.Delete(name, new PasswordForm(password), cancellationToken))); + + /// Adds a user to the organization. + [Route("admin/organizations/{name}"), HttpPost, PageHandler("AddMember")] + public async Task AddMember(string name, string? userName, bool isAdmin, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.AddMember(name, new OrganizationMemberForm(userName, isAdmin, password), cancellationToken))); + + /// Makes a member an administrator of the organization, or not. + [Route("admin/organizations/{name}"), HttpPost, PageHandler("SetAdmin")] + public async Task SetAdmin(string name, string? userName, bool isAdmin, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.SetAdmin(name, new OrganizationMemberForm(userName, isAdmin, password), cancellationToken))); + + /// Removes a member from the organization. + [Route("admin/organizations/{name}"), HttpPost, PageHandler("RemoveMember")] + public async Task RemoveMember(string name, string? userName, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.RemoveMember(name, new OrganizationMemberForm(userName, false, password), cancellationToken))); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/organizations/{name}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task DetailPost(string name, CancellationToken cancellationToken) + => Show(await Api(api => api.Get(name, cancellationToken))); + + private IActionResult Show(UiApiResponse response) => RenderFlashed(response, "Detail"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminPackagesController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminPackagesController.cs new file mode 100644 index 000000000..5ac931e1a --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminPackagesController.cs @@ -0,0 +1,24 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The package IDs that have no owner, in every repository (/admin/packages, and /r/{repo}/admin/packages like the +/// page): those that predate accounts, and those left behind when their only owner's account was deleted. Only administrators and +/// the global API key may change them, so this is where an administrator finds them. It replaces the Razor Page +/// /Admin/Packages (same URL); the work is done by the JSON twin (). +/// The packages of one user are . +/// +public sealed class AdminPackagesController : AdminControllerBase +{ + /// Lists the ownerless IDs of every repository. + [Route("admin/packages"), HttpGet, HttpHead, PageHandler, RepositoryPage] + public async Task Index([ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => Render(await Api(api => api.List(pageNumber, cancellationToken)), "Index"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminPermissionsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminPermissionsController.cs new file mode 100644 index 000000000..36329dff7 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminPermissionsController.cs @@ -0,0 +1,101 @@ +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Access; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The permission target screens of the administrator: the list with the new-target form (/admin/permissions, server +/// administrators only) and one target (/admin/permissions/{name}: patterns, preview, grants, delete), which also admits the +/// administrators of the target's project for a project target. They replace the Razor Pages /Admin/Permissions and +/// /Admin/PermissionDetail (same URLs and handlers); the work is done by the JSON twin +/// () and this controller only renders its answers. Saving patterns, changing grants and deleting +/// ask for the password again, and every POST is refused with 503 while the read-only gate is closed (). +/// +public sealed class AdminPermissionsController : AccessControllerBase +{ + /// + protected override async Task AuthorizeAsync(CancellationToken cancellationToken) + { + // Only the detail screen is widened to a project's administrators (the target is the name route value). + var isDetail = ControllerContext.ActionDescriptor.AttributeRouteInfo?.Template?.Contains("{name}") == true; + + return isDetail + ? await AccessAuthorization.TargetAsync(AccessAdmin, IsServerAdministrator, CurrentUserId, RouteData.Values["name"]?.ToString(), cancellationToken) + : IsServerAdministrator; + } + + /// Lists the permission targets. + [Route("admin/permissions"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => ShowList(await Api(api => api.List(cancellationToken))); + + /// Creates a target and opens it. + [Route("admin/permissions"), HttpPost, PageHandler] + public async Task Create(string? name, string? repositoryPatterns, string? includePatterns, string? excludePatterns, string? project, string? testPackage, CancellationToken cancellationToken) + => ShowList(await Api( + api => api.Create(new PermissionTargetForm(name, repositoryPatterns, includePatterns, excludePatterns, project, testPackage), cancellationToken))); + + /// Previews the form patterns without saving anything. + [Route("admin/permissions"), HttpPost, PageHandler("Preview")] + public async Task Preview(string? name, string? repositoryPatterns, string? includePatterns, string? excludePatterns, string? project, string? testPackage, CancellationToken cancellationToken) + => ShowList(await Api( + api => api.Preview(new PermissionTargetForm(name, repositoryPatterns, includePatterns, excludePatterns, project, testPackage), cancellationToken))); + + /// Re-creates the built-in groups and targets that are missing (the upgrade defaults). + [Route("admin/permissions"), HttpPost, PageHandler("RestoreBuiltIns")] + public async Task RestoreBuiltIns(string? password, CancellationToken cancellationToken) + => ShowList(await Api(api => api.RestoreBuiltIns(new PasswordForm(password), cancellationToken))); + + /// Shows one target. / pre-fill the grant form. + [Route("admin/permissions/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Detail(string name, string? testPackage, PrincipalType? principalType, string? principalName, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Get(name, testPackage, principalType, principalName, cancellationToken))); + + /// Previews the form patterns (and the test package) without saving anything. + [Route("admin/permissions/{name}"), HttpPost, PageHandler("Preview")] + public async Task DetailPreview(string name, string? repositoryPatterns, string? includePatterns, string? excludePatterns, string? testPackage, PrincipalType? principalType, string? principalName, CancellationToken cancellationToken) + => ShowDetail(await Api( + api => api.PreviewDetail(name, new PermissionTargetForm(null, repositoryPatterns, includePatterns, excludePatterns, null, testPackage, principalType, principalName), cancellationToken))); + + /// Replaces the target patterns. + [Route("admin/permissions/{name}"), HttpPost, PageHandler("Save")] + public async Task Save(string name, string? repositoryPatterns, string? includePatterns, string? excludePatterns, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api( + api => api.Save(name, new PermissionTargetForm(null, repositoryPatterns, includePatterns, excludePatterns, Password: password), cancellationToken))); + + /// Gives a principal the ticked actions through the target, replacing an earlier grant to it. + [Route("admin/permissions/{name}"), HttpPost, PageHandler("SetGrant")] + public async Task SetGrant(string name, PrincipalType? principalType, string? principalName, string[]? actions, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api( + api => api.SetGrant(name, new GrantForm(principalType, principalName, actions, password), cancellationToken))); + + /// Removes a principal grant. + [Route("admin/permissions/{name}"), HttpPost, PageHandler("RemoveGrant")] + public async Task RemoveGrant(string name, PrincipalType type, string? principalId, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api( + api => api.RemoveGrant(name, new PrincipalRemoval(type, principalId, password), cancellationToken))); + + /// Deletes the target and its grants. + [Route("admin/permissions/{name}"), HttpPost, PageHandler("Delete")] + public async Task Delete(string name, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Delete(name, new PasswordForm(password), cancellationToken))); + + /// A form posted to the target's own URL with no handler: the screen is rendered (the page had no default handler). + [Route("admin/permissions/{name}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task DetailPost(string name, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Get(name, null, null, null, cancellationToken))); + + private IActionResult ShowList(UiApiResponse response) => RenderFlashed(response, "Index"); + + private IActionResult ShowDetail(UiApiResponse response) => RenderFlashed(response, "Detail"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminProjectsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminProjectsController.cs new file mode 100644 index 000000000..f836f262b --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminProjectsController.cs @@ -0,0 +1,97 @@ +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Access; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.UseCases.Access; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The project screens: the list with the new-project form (/admin/projects) and one project (/admin/projects/{name}: +/// repositories, members, the project's permission targets, delete). They replace the Razor Pages /Admin/Projects and +/// /Admin/ProjectDetail (same URLs and handlers); the work is done by the JSON twin +/// () and this controller only renders its answers. Server administrators, and the administrators of a +/// project for the projects they administer (the project is the name route value; only server administrators create and delete projects and +/// assign repositories). Member changes and deletions ask for the password again, and every POST is refused with 503 while the read-only gate is +/// closed (). +/// +public sealed class AdminProjectsController : AccessControllerBase +{ + /// + protected override async Task AuthorizeAsync(CancellationToken cancellationToken) + { + var isDetail = ControllerContext.ActionDescriptor.AttributeRouteInfo?.Template?.Contains("{name}") == true; + + return isDetail + ? await AccessAuthorization.ProjectAsync(AccessAdmin, IsServerAdministrator, CurrentUserId, RouteData.Values["name"]?.ToString(), cancellationToken) + : await AccessAuthorization.ProjectsAsync(AccessAdmin, IsServerAdministrator, CurrentUserId, cancellationToken); + } + + /// Lists the projects the signed-in user may open. + [Route("admin/projects"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => ShowList(await Api(api => api.List(cancellationToken))); + + /// Creates a project (administrators only) and opens it. + [Route("admin/projects"), HttpPost, PageHandler] + public async Task Create(string? name, string? displayName, CancellationToken cancellationToken) + => ShowList(await Api(api => api.Create(new ProjectCreation(name, displayName), cancellationToken))); + + /// Shows one project. + [Route("admin/projects/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Detail(string name, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Get(name, cancellationToken))); + + /// Gives a user or group a role in the project, replacing an earlier one. + [Route("admin/projects/{name}"), HttpPost, PageHandler("SetMember")] + public async Task SetMember(string name, PrincipalType type, string? principalName, ProjectRole role, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.SetMember(name, new ProjectMemberForm(type, principalName, role, password), cancellationToken))); + + /// Takes a user or group out of the project. + [Route("admin/projects/{name}"), HttpPost, PageHandler("RemoveMember")] + public async Task RemoveMember(string name, PrincipalType type, string? principalId, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.RemoveMember(name, new PrincipalRemoval(type, principalId, password), cancellationToken))); + + /// Puts a repository in the project (server administrators only); it leaves any project it was in. + [Route("admin/projects/{name}"), HttpPost, PageHandler("AssignRepository")] + public async Task AssignRepository(string name, string? repository, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.AssignRepository(name, new ProjectRepositoryForm(repository, password), cancellationToken))); + + /// Takes a repository out of the project (server administrators only). + [Route("admin/projects/{name}"), HttpPost, PageHandler("UnassignRepository")] + public async Task UnassignRepository(string name, string? repository, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.UnassignRepository(name, new ProjectRepositoryForm(repository, password), cancellationToken))); + + /// Creates a permission target that applies only to the project's repositories. + [Route("admin/projects/{name}"), HttpPost, PageHandler("CreateTarget")] + public async Task CreateTarget(string name, string? targetName, string? repositoryPatterns, string? includePatterns, string? excludePatterns, string? testPackage, CancellationToken cancellationToken) + => ShowDetail(await Api( + api => api.CreateTarget(name, new ProjectTargetForm(targetName, repositoryPatterns, includePatterns, excludePatterns, testPackage), cancellationToken))); + + /// Previews the new target patterns without saving anything. + [Route("admin/projects/{name}"), HttpPost, PageHandler("Preview")] + public async Task Preview(string name, string? targetName, string? repositoryPatterns, string? includePatterns, string? excludePatterns, string? testPackage, CancellationToken cancellationToken) + => ShowDetail(await Api( + api => api.Preview(name, new ProjectTargetForm(targetName, repositoryPatterns, includePatterns, excludePatterns, testPackage), cancellationToken))); + + /// Deletes the project (server administrators only) with its members and targets; repositories stay. + [Route("admin/projects/{name}"), HttpPost, PageHandler("Delete")] + public async Task Delete(string name, string? password, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Delete(name, new PasswordForm(password), cancellationToken))); + + /// A form posted to the project's own URL with no handler: the screen is rendered (the page had no default handler). + [Route("admin/projects/{name}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task DetailPost(string name, CancellationToken cancellationToken) + => ShowDetail(await Api(api => api.Get(name, cancellationToken))); + + private IActionResult ShowList(UiApiResponse response) => RenderFlashed(response, "Index"); + + private IActionResult ShowDetail(UiApiResponse response) => RenderFlashed(response, "Detail"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminReplicationController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminReplicationController.cs new file mode 100644 index 000000000..fe0e97b0a --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminReplicationController.cs @@ -0,0 +1,80 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The replication screens: the replications (/admin/replication) and one replication (/admin/replication/{key}). +/// They replace the Razor Pages of the same names (same URLs and handlers); the work is done by the JSON twin +/// () and this controller only renders its answers. Administrators only (404 for anyone else), every POST +/// is refused with 503 while the read-only gate is closed. The peer API key is write only: it is never filled back into a form. +/// +public sealed class AdminReplicationController : ReplicationControllerBase +{ + // ---------------------------------------------------------------- replications + + /// Lists the replications. + [Route("admin/replication"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => ShowReplications(await Api(api => api.GetReplications(cancellationToken))); + + /// Creates a replication and opens it. + [Route("admin/replication"), HttpPost, PageHandler] + public async Task Create([Bind(Prefix = "Form")] ReplicationForm? form, string? password, CancellationToken cancellationToken) + => ShowReplications(await Api(api => api.Create(new ReplicationBody(form, password), cancellationToken))); + + // ---------------------------------------------------------------- one replication + + /// Shows the replication. + [Route("admin/replication/{key:int}"), HttpGet, HttpHead, PageHandler] + public async Task Config(int key, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.GetConfig(key, cancellationToken))); + + /// Saves the settings. + [Route("admin/replication/{key:int}"), HttpPost, PageHandler("Save")] + public async Task Save(int key, [Bind(Prefix = "Form")] ReplicationForm? form, string? password, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.Save(key, new ReplicationBody(form, password), cancellationToken))); + + /// Tests the connection with the typed settings; saves nothing. + [Route("admin/replication/{key:int}"), HttpPost, PageHandler("Test")] + public async Task Test(int key, [Bind(Prefix = "Form")] ReplicationForm? form, string? password, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.Test(key, new ReplicationBody(form, password), cancellationToken))); + + /// Starts a run. + [Route("admin/replication/{key:int}"), HttpPost, PageHandler("Run")] + public async Task Run(int key, string? password, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.Run(key, new PasswordForm(password), cancellationToken))); + + /// Starts a run that continues the last interrupted or failed one. + [Route("admin/replication/{key:int}"), HttpPost, PageHandler("Resume")] + public async Task Resume(int key, string? password, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.Resume(key, new PasswordForm(password), cancellationToken))); + + /// Asks the running replication to stop; it ends as interrupted and can be resumed. + [Route("admin/replication/{key:int}"), HttpPost, PageHandler("Stop")] + public async Task Stop(int key, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.Stop(key, cancellationToken))); + + /// Deletes the configuration with its log. + [Route("admin/replication/{key:int}"), HttpPost, PageHandler("Delete")] + public async Task Delete(int key, string? password, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.Delete(key, new PasswordForm(password), cancellationToken))); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/replication/{key:int}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task ConfigPost(int key, CancellationToken cancellationToken) + => ShowConfig(await Api(api => api.GetConfig(key, cancellationToken))); + + // ---------------------------------------------------------------- helpers + + private IActionResult ShowReplications(UiApiResponse response) => RenderFlashed(response, "Index"); + + private IActionResult ShowConfig(UiApiResponse response) => RenderFlashed(response, "Config"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminRepositoriesController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminRepositoriesController.cs new file mode 100644 index 000000000..e6194e9e0 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminRepositoriesController.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Repositories; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The administrator's repository screens: the list with the create forms (/admin/repositories), one repository +/// (/admin/repositories/{name}: anonymous read, upstream, cache, members, Maven settings) and its deletion +/// (/admin/repositories/{name}/delete). They replace the Razor Pages /Admin/Repositories, +/// /Admin/RepositoryEdit and /Admin/RepositoryDelete (same URLs, same ?handler= values); the work is done by the JSON twin +/// () and this controller only renders its answers. +/// Administrators only; every write is refused with 503 while the read-only gate is closed, and the changes that hand out +/// credentials or delete data ask for the administrator's password again, as the pages did. +/// +public sealed class AdminRepositoriesController : RepositoryControllerBase +{ + // ---------------------------------------------------------------- Repositories + + /// Lists the repositories (narrowed by format, kind, q) and shows the create forms. + [Route("admin/repositories"), HttpGet, HttpHead, PageHandler] + public async Task Index(string? format, string? kind, string? q, CancellationToken cancellationToken) + => Show(await Api(api => api.GetRepositories(format, kind, q, cancellationToken)), "Index"); + + /// Creates a local NuGet repository. + [Route("admin/repositories"), HttpPost, PageHandler] + public async Task Create(string? name, RemoteFormModel? remote, CancellationToken cancellationToken) + => Show(await Api(api => api.Create(new RepositoryCreateForm { Name = name, Remote = remote ?? new RemoteFormModel() }, cancellationToken)), "Index"); + + /// Creates a local repository of a format other than NuGet from the posted field:* values. + [Route("admin/repositories"), HttpPost, PageHandler("Format")] + public async Task CreateFormat(string? name, RemoteFormModel? remote, string? format, bool anonymousRead = true, CancellationToken cancellationToken = default) + => Show( + await Api(api => api.CreateFormat( + new RepositoryCreateForm { Name = name, Remote = remote ?? new RemoteFormModel(), Format = format, AnonymousRead = anonymousRead, Fields = PostedFields() }, + cancellationToken)), + "Index"); + + /// Creates a virtual repository with no members. + [Route("admin/repositories"), HttpPost, PageHandler("Virtual")] + public async Task CreateVirtual(string? name, RemoteFormModel? remote, string? format = null, bool anonymousRead = true, CancellationToken cancellationToken = default) + => Show( + await Api(api => api.CreateVirtual( + new RepositoryCreateForm { Name = name, Remote = remote ?? new RemoteFormModel(), Format = format, AnonymousRead = anonymousRead }, + cancellationToken)), + "Index"); + + /// Creates a remote repository from the posted upstream settings, after the administrator's password. + [Route("admin/repositories"), HttpPost, PageHandler("Remote")] + public async Task CreateRemote(string? name, RemoteFormModel? remote, string? password, string? anonymousRead, string? format = null, CancellationToken cancellationToken = default) + => Show( + await Api(api => api.CreateRemote( + new RepositoryCreateForm + { + Name = name, + Remote = remote ?? new RemoteFormModel(), + Format = format, + Password = password, + // Absent = the default; anything but "true" is "no". + AnonymousRead = string.IsNullOrEmpty(anonymousRead) ? null : string.Equals(anonymousRead, "true", StringComparison.OrdinalIgnoreCase), + }, + cancellationToken)), + "Index"); + + // The format module's create fields, posted as field:{name}. + private Dictionary PostedFields() + => !Request.HasFormContentType + ? new Dictionary() + : Request.Form.Keys + .Where(k => k.StartsWith("field:", StringComparison.Ordinal)) + .ToDictionary(k => k.Substring("field:".Length), k => (string?)Request.Form[k].ToString(), StringComparer.Ordinal); + + // ---------------------------------------------------------------- RepositoryEdit + + /// Shows one repository. + [Route("admin/repositories/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Edit(string name, CancellationToken cancellationToken) + => Show(await Api(api => api.GetRepository(name, cancellationToken)), "Edit"); + + /// Saves the repository. + [Route("admin/repositories/{name}"), HttpPost, PageHandler] + public async Task Save(string name, RepositoryEditForm? form, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.Save(name, Body(form, password), cancellationToken)), "Edit"); + + /// Saves the policy of a local Maven repository. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("MavenSettings")] + public async Task MavenSettings(string name, RepositoryEditForm? form, string? policy, string? redeploy, string? snapshotBuilds, CancellationToken cancellationToken) + => Show(await Api(api => api.MavenSettings(name, Body(form, null, policy: policy, redeploy: redeploy, snapshotBuilds: snapshotBuilds), cancellationToken)), "Edit"); + + /// Asks a remote repository's upstream with the unsaved values and saves nothing. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("Test")] + public async Task Test(string name, RepositoryEditForm? form, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.Test(name, Body(form, password), cancellationToken)), "Edit"); + + /// Deletes everything a remote repository cached. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("Purge")] + public async Task Purge(string name, RepositoryEditForm? form, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.Purge(name, Body(form, password), cancellationToken)), "Edit"); + + /// Deletes one cached package of a remote repository. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("PurgePackage")] + public async Task PurgePackage(string name, RepositoryEditForm? form, string? password, CancellationToken cancellationToken) + => Show(await Api(api => api.PurgePackage(name, Body(form, password), cancellationToken)), "Edit"); + + /// Adds a member at the end of a virtual repository. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("AddMember")] + public async Task AddMember(string name, RepositoryEditForm? form, string? member, CancellationToken cancellationToken) + => Show(await Api(api => api.AddMember(name, Body(form, null, member: member), cancellationToken)), "Edit"); + + /// Removes a member of a virtual repository. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("RemoveMember")] + public async Task RemoveMember(string name, RepositoryEditForm? form, string? member, CancellationToken cancellationToken) + => Show(await Api(api => api.RemoveMember(name, Body(form, null, member: member), cancellationToken)), "Edit"); + + /// Moves a member of a virtual repository up or down. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("MoveMember")] + public async Task MoveMember(string name, RepositoryEditForm? form, string? member, string? direction, CancellationToken cancellationToken) + => Show(await Api(api => api.MoveMember(name, Body(form, null, member: member, direction: direction), cancellationToken)), "Edit"); + + /// Sets the member of a virtual repository that receives uploads. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("Deploy")] + public async Task Deploy(string name, RepositoryEditForm? form, string? deploy, CancellationToken cancellationToken) + => Show(await Api(api => api.Deploy(name, Body(form, null, deploy: deploy), cancellationToken)), "Edit"); + + /// Shows where a package version would come from in a virtual repository. + [Route("admin/repositories/{name}"), HttpPost, PageHandler("Preview")] + public async Task Preview(string name, RepositoryEditForm? form, CancellationToken cancellationToken) + => Show(await Api(api => api.Preview(name, Body(form, null), cancellationToken)), "Edit"); + + // What the page's forms post, as the twin's body. + private static RepositoryEditRequest Body(RepositoryEditForm? form, string? password, string? member = null, string? direction = null, string? deploy = null, string? policy = null, string? redeploy = null, string? snapshotBuilds = null) + => new() + { + AnonymousRead = form?.AnonymousRead ?? false, + Remote = form?.Remote ?? new RemoteFormModel(), + PreviewPackageId = form?.PreviewPackageId, + PreviewVersion = form?.PreviewVersion, + PackageId = form?.PackageId, + PackageVersion = form?.PackageVersion, + Password = password, + Member = member, + Direction = direction, + Deploy = deploy, + Policy = policy, + Redeploy = redeploy, + SnapshotBuilds = snapshotBuilds, + }; + + // The screens print the reason from their model (Error), so a refusal is not copied into ModelState as well; the message of the last + // redirect is moved into the model. + private IActionResult Show(UiApiResponse response, string view) + where TModel : class, IFlashMessage + => Render(response, view, model => { Flash(model); return model; }, modelShowsFormErrors: true); + + // ---------------------------------------------------------------- RepositoryDelete + + /// Shows what deleting the repository does. + [Route("admin/repositories/{name}/delete"), HttpGet, HttpHead, PageHandler] + public async Task DeleteRepository(string name, CancellationToken cancellationToken) + => Render(await Api(api => api.GetDeletion(name, cancellationToken)), "Delete", modelShowsFormErrors: true); + + /// Deletes the repository, then returns to the list. + [Route("admin/repositories/{name}/delete"), HttpPost, PageHandler] + public async Task DeleteRepositoryConfirmed(string name, CancellationToken cancellationToken) + => Render(await Api(api => api.DeleteRepository(name, cancellationToken)), "Delete", modelShowsFormErrors: true); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminRetentionController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminRetentionController.cs new file mode 100644 index 000000000..06437767d --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminRetentionController.cs @@ -0,0 +1,96 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Application.Models.Shared; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The retention screens: the policies (/admin/retention), one policy (/admin/retention/{key}) and the legal holds +/// (/admin/retention/holds). They replace the Razor Pages of the same names (same URLs and handlers); the work is +/// done by the JSON twin () and this controller only renders its answers. Administrators only (404 for +/// anyone else), every POST is refused with 503 while the read-only gate is closed. +/// +public sealed class AdminRetentionController : RetentionControllerBase +{ + // ---------------------------------------------------------------- policies + + /// Lists the policies. + [Route("admin/retention"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => ShowPolicies(await Api(api => api.GetPolicies(cancellationToken))); + + /// Creates a policy and opens it. + [Route("admin/retention"), HttpPost, PageHandler] + public async Task Create([Bind(Prefix = "Form")] RetentionPolicyForm? form, string? password, CancellationToken cancellationToken) + => ShowPolicies(await Api(api => api.Create(new RetentionPolicyBody(form, password), cancellationToken))); + + // ---------------------------------------------------------------- one policy + + /// Shows the policy. + [Route("admin/retention/{key:int}"), HttpGet, HttpHead, PageHandler] + public async Task Policy(int key, CancellationToken cancellationToken) + => ShowPolicy(await Api(api => api.GetPolicy(key, cancellationToken))); + + /// Saves the rules. + [Route("admin/retention/{key:int}"), HttpPost, PageHandler("Save")] + public async Task Save(int key, [Bind(Prefix = "Form")] RetentionPolicyForm? form, string? password, CancellationToken cancellationToken) + => ShowPolicy(await Api(api => api.Save(key, new RetentionPolicyBody(form, password), cancellationToken))); + + /// Starts a dry run: the report of what a run would delete. + [Route("admin/retention/{key:int}"), HttpPost, PageHandler("DryRun")] + public async Task DryRun(int key, CancellationToken cancellationToken) + => ShowPolicy(await Api(api => api.DryRun(key, cancellationToken))); + + /// Starts a run that deletes. + [Route("admin/retention/{key:int}"), HttpPost, PageHandler("Run")] + public async Task Run(int key, string? password, CancellationToken cancellationToken) + => ShowPolicy(await Api(api => api.Run(key, new PasswordForm(password), cancellationToken))); + + /// Deletes the policy (what it deleted stays deleted). + [Route("admin/retention/{key:int}"), HttpPost, PageHandler("Delete")] + public async Task Delete(int key, string? password, CancellationToken cancellationToken) + => ShowPolicy(await Api(api => api.Delete(key, new PasswordForm(password), cancellationToken))); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/retention/{key:int}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task PolicyPost(int key, CancellationToken cancellationToken) + => ShowPolicy(await Api(api => api.GetPolicy(key, cancellationToken))); + + // ---------------------------------------------------------------- holds + + /// Lists the holds. + [Route("admin/retention/holds"), HttpGet, HttpHead, PageHandler] + public async Task Holds([FromQuery] string? repository, CancellationToken cancellationToken) + => ShowHolds(await Api(api => api.GetHolds(repository, cancellationToken))); + + /// Places a hold. + [Route("admin/retention/holds"), HttpPost, PageHandler("Add")] + public async Task AddHold( + [FromQuery] string? repository, string? holdRepository, string? holdName, string? holdVersion, string? reason, CancellationToken cancellationToken) + => ShowHolds(await Api( + api => api.AddHold(repository, new RetentionHoldForm(holdRepository, holdName, holdVersion, reason), cancellationToken))); + + /// Lifts a hold. + [Route("admin/retention/holds"), HttpPost, PageHandler("Remove")] + public async Task RemoveHold([FromQuery] string? repository, int key, string? password, CancellationToken cancellationToken) + => ShowHolds(await Api(api => api.RemoveHold(repository, new RetentionHoldRemoval(key, password), cancellationToken))); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/retention/holds"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task HoldsPost([FromQuery] string? repository, CancellationToken cancellationToken) + => ShowHolds(await Api(api => api.GetHolds(repository, cancellationToken))); + + // ---------------------------------------------------------------- helpers + + private IActionResult ShowPolicies(UiApiResponse response) => RenderFlashed(response, "Index"); + + private IActionResult ShowPolicy(UiApiResponse response) => RenderFlashed(response, "Policy"); + + private IActionResult ShowHolds(UiApiResponse response) => RenderFlashed(response, "Holds"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminScanningController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminScanningController.cs new file mode 100644 index 000000000..70406c46e --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminScanningController.cs @@ -0,0 +1,89 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Routing; +using BaGet.Identity.Application.Models.Policies; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The vulnerability scanning screens: the overview (/admin/scanning), the dashboard of a repository +/// (/admin/scanning/{name}) and the policy of a project (/admin/scanning/projects/{name}). They replace the Razor +/// Pages of the same names (same URLs and handlers); the work is done by the JSON twin +/// () and this controller only renders its answers. Administrators only (404 for anyone else), every POST +/// is refused with 503 while the read-only gate is closed. +/// +public sealed class AdminScanningController : AccessControllerBase +{ + // ---------------------------------------------------------------- overview + + /// Shows the overview. + [Route("admin/scanning"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => Render(await Api(api => api.GetOverview(cancellationToken)), "Index"); + + // ---------------------------------------------------------------- one repository + + /// Shows the dashboard of a repository. + [Route("admin/scanning/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Repository( + string name, [FromQuery(Name = "min")] int minSeverity, [FromQuery(Name = "p")] int pageNumber, CancellationToken cancellationToken) + => ShowRepository(await Api(api => api.GetRepository(name, minSeverity, pageNumber, cancellationToken))); + + /// Saves the repository policy; empty values remove it. + [Route("admin/scanning/{name}"), HttpPost, PageHandler("Policy")] + public async Task RepositoryPolicy( + string name, string? warn, string? blockDownload, string? blockDeploy, bool blockUnscanned, string? password, CancellationToken cancellationToken) + => ShowRepository(await Api( + api => api.SaveRepositoryPolicy(name, new ScanPolicyBody(warn, blockDownload, blockDeploy, blockUnscanned, password), cancellationToken))); + + /// Starts a scan of every artifact of the repository in the background. + [Route("admin/scanning/{name}"), HttpPost, PageHandler("Scan")] + public async Task RepositoryScan(string name, CancellationToken cancellationToken) + => ShowRepository(await Api(api => api.Scan(name, cancellationToken))); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/scanning/{name}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task RepositoryPost( + string name, [FromQuery(Name = "min")] int minSeverity, [FromQuery(Name = "p")] int pageNumber, CancellationToken cancellationToken) + => ShowRepository(await Api(api => api.GetRepository(name, minSeverity, pageNumber, cancellationToken))); + + // ---------------------------------------------------------------- one project + + /// Shows the policy of a project. + [Route("admin/scanning/projects/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Project(string name, CancellationToken cancellationToken) + => ShowProject(await Api(api => api.GetProject(name, cancellationToken))); + + /// Saves the project policy; empty values remove it. + [Route("admin/scanning/projects/{name}"), HttpPost, PageHandler("Policy")] + public async Task ProjectPolicy( + string name, string? warn, string? blockDownload, string? blockDeploy, bool blockUnscanned, string? password, CancellationToken cancellationToken) + => ShowProject(await Api( + api => api.SaveProjectPolicy(name, new ScanPolicyBody(warn, blockDownload, blockDeploy, blockUnscanned, password), cancellationToken))); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/scanning/projects/{name}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task ProjectPost(string name, CancellationToken cancellationToken) + => ShowProject(await Api(api => api.GetProject(name, cancellationToken))); + + // ---------------------------------------------------------------- helpers + + // The use case names the package screen of each finding; the address is this controller's to build (it knows the routes). + private IActionResult ShowRepository(UiApiResponse response) + => Render( + response, + "Repository", + model => + { + Flash(model); + model.LinkResolver = link => Url.Action(link.Screen.Action, link.Screen.Controller, new RouteValueDictionary(link.RouteValues)); + return model; + }); + + private IActionResult ShowProject(UiApiResponse response) => RenderFlashed(response, "Project"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminSettingsController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminSettingsController.cs new file mode 100644 index 000000000..e79273e6b --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminSettingsController.cs @@ -0,0 +1,77 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Application.Screens; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Settings; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The server settings screen (/admin/settings): edits every registered setting, one form per section, the per-source log +/// levels, the database copy progress (?handler=CopyStatus) and the telemetry connection test. It replaces the Razor Page +/// /Admin/Settings (same URL and handlers); the work is done by the JSON twin +/// () and this controller only renders its answers. Every change asks the administrator's +/// password again and is refused with 503 while the read-only gate is closed. +/// +public sealed class AdminSettingsController : AdminControllerBase +{ + /// Shows the settings. is the id of the section to show. + [Route("admin/settings"), HttpGet, HttpHead, PageHandler] + public async Task Index(string? section = null) + => RenderFlashed(await Api(api => api.Get(section)), "Index"); + + /// The progress of the database copy as JSON, polled by the page. + [Route("admin/settings"), HttpGet, PageHandler("CopyStatus")] + public async Task CopyStatus() + { + var response = await Api(api => Task.FromResult(api.GetCopyStatus())); + + // The page's script reads the twin's model as it is: plain JSON, not a view. + return response.Raw ?? (response.Screen.Status == ScreenStatus.Ok ? new JsonResult(response.Screen.Model) : NotFound()); + } + + /// Saves the settings of one section after the administrator confirms. + [Route("admin/settings"), HttpPost, PageHandler] + public async Task Save(string? section, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Save(Submission(section, password), cancellationToken)), "Index"); + + /// Adds or changes a named OpenID Connect provider (the "Sign-in providers" panel). + [Route("admin/settings"), HttpPost, PageHandler("SaveProvider")] + public async Task SaveProvider(SignInProviderForm form, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.SaveProvider(form, cancellationToken)), "Index"); + + /// Removes a named OpenID Connect provider saved on this screen. + [Route("admin/settings"), HttpPost, PageHandler("RemoveProvider")] + public async Task RemoveProvider(string? id, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.RemoveProvider(new RemoveSignInProviderForm(id, password), cancellationToken)), "Index"); + + /// Sets the lowest level logged for one source. + [Route("admin/settings"), HttpPost, PageHandler("SetLogLevel")] + public async Task SetLogLevel(string? source, string? level, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.SetLogLevel(new LogLevelForm(source, level, password), cancellationToken)), "Index"); + + /// Removes a per-source level saved on this page. + [Route("admin/settings"), HttpPost, PageHandler("RemoveLogLevel")] + public async Task RemoveLogLevel(string? source, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.RemoveLogLevel(new LogLevelForm(source, null, password), cancellationToken)), "Index"); + + /// Sends one test span to the posted, unsaved telemetry endpoint and shows the outcome. + [Route("admin/settings"), HttpPost, PageHandler("TestTelemetry")] + public async Task TestTelemetry(string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.TestTelemetry(Submission(null, password), cancellationToken)), "Index"); + + // The posted form as the use case takes it: every field, as the page's form collection holds it. + private SettingsSubmission Submission(string? section, string? password) + => new( + section, + password, + Request.HasFormContentType + ? Request.Form.ToDictionary(field => field.Key, field => field.Value.Select(value => value ?? string.Empty).ToArray()) + : new Dictionary()); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminUsersController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminUsersController.cs new file mode 100644 index 000000000..0e8e8b27e --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/AdminUsersController.cs @@ -0,0 +1,127 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.Models.Shared; +using BaGet.Identity.Application.Models.Users; +using BaGet.Identity.Application.UseCases.Admin; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The administrator's account screens: the user list (/admin/users), one account (/admin/users/{name}), its deletion +/// (/admin/users/{name}/delete) and the packages it owns (/admin/users/{name}/packages). They replace the Razor Pages +/// /Admin/Users, /Admin/UserDetail, /Admin/DeleteUser and /Admin/UserPackages (same URLs, same +/// ?handler= values, ); the work is done by the JSON twin +/// (, over the Application project's use cases) and this controller only renders its answers. +/// Administrators only (); every action asks the administrator's password again and is refused with 503 +/// while the read-only gate is closed, as the pages did. +/// +public sealed class AdminUsersController : AdminControllerBase +{ + // ---------------------------------------------------------------- Users + + /// Lists the users. + [Route("admin/users"), HttpGet, HttpHead, PageHandler] + public async Task Index(string? q, [ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => RenderFlashed(await Api(api => api.List(q, pageNumber, cancellationToken)), "Index"); + + /// Enables a self-registered account that waits for approval. + [Route("admin/users"), HttpPost, PageHandler("Approve")] + public async Task Approve(string userName, string? password, string? q, [ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => RenderFlashed(await Api(api => api.Approve(new UserChange(userName, password, q, pageNumber), cancellationToken)), "Index"); + + /// Makes a user an administrator. + [Route("admin/users"), HttpPost, PageHandler("Promote")] + public async Task Promote(string userName, string? password, string? q, [ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => RenderFlashed(await Api(api => api.Promote(new UserChange(userName, password, q, pageNumber), cancellationToken)), "Index"); + + /// Removes a user's administrator flag. + [Route("admin/users"), HttpPost, PageHandler("Demote")] + public async Task Demote(string userName, string? password, string? q, [ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => RenderFlashed(await Api(api => api.Demote(new UserChange(userName, password, q, pageNumber), cancellationToken)), "Index"); + + /// Replaces a user's password with a generated one and shows it once (the response is the screen, not a redirect). + [Route("admin/users"), HttpPost, PageHandler("ResetPassword")] + public async Task ResetPassword(string userName, string? password, string? resetEmail, string? q, [ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => RenderFlashed(await Api(api => api.ResetPassword(new UserChange(userName, password, q, pageNumber, resetEmail), cancellationToken)), "Index"); + + /// Mails a user a password reset link. + [Route("admin/users"), HttpPost, PageHandler("SendResetLink")] + public async Task SendResetLink(string userName, string? password, string? q, [ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => RenderFlashed(await Api(api => api.SendResetLink(new UserChange(userName, password, q, pageNumber), cancellationToken)), "Index"); + + /// Creates an account (typed, generated or invited password). + [Route("admin/users"), HttpPost, PageHandler("Create")] + public async Task Create( + string? newUserName, + string? newEmail, + string? newPassword, + bool invite, + string? password, + string? q, + [ModelBinder(Name = "p")] int pageNumber = 1, + CancellationToken cancellationToken = default) + => RenderFlashed( + await Api(api => api.Create(new UserCreation(newUserName, newEmail, newPassword, invite, password, q, pageNumber), cancellationToken)), + "Index"); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/users"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task IndexPost(string? q, [ModelBinder(Name = "p")] int pageNumber = 1, CancellationToken cancellationToken = default) + => RenderFlashed(await Api(api => api.List(q, pageNumber, cancellationToken)), "Index"); + + // ---------------------------------------------------------------- UserDetail + + /// Shows one account. + [Route("admin/users/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Detail(string name, string? package, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Get(name, package, cancellationToken)), "Detail"); + + /// Enables the account when it waits for approval. + [Route("admin/users/{name}"), HttpPost, PageHandler("Approve")] + public async Task DetailApprove(string name, string? package, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.ApproveAccount(name, new PasswordForm(password), cancellationToken)), "Detail"); + + /// Revokes one of the account's API keys. + [Route("admin/users/{name}"), HttpPost, PageHandler("RevokeKey")] + public async Task RevokeKey(string name, string? package, int key, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.RevokeKey(name, new UserKeyForm(key, password), cancellationToken)), "Detail"); + + /// Adds the account to a group. + [Route("admin/users/{name}"), HttpPost, PageHandler("AddGroup")] + public async Task AddGroup(string name, string? package, string? group, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.AddGroup(name, new UserGroupForm(group, password), cancellationToken)), "Detail"); + + /// Removes the account from a group. + [Route("admin/users/{name}"), HttpPost, PageHandler("RemoveGroup")] + public async Task RemoveGroup(string name, string? package, string? group, string? password, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.RemoveGroup(name, new UserGroupForm(group, password), cancellationToken)), "Detail"); + + /// A form posted to the screen's own URL, with no handler: the screen is rendered (the page had no default handler). + [Route("admin/users/{name}"), HttpPost, PageHandler, ImplicitPageHandler] + public async Task DetailPost(string name, string? package, CancellationToken cancellationToken) + => RenderFlashed(await Api(api => api.Get(name, package, cancellationToken)), "Detail"); + + // ---------------------------------------------------------------- DeleteUser + + /// Shows what deleting the account does. + [Route("admin/users/{name}/delete"), HttpGet, HttpHead, PageHandler] + public async Task DeleteUser(string name, CancellationToken cancellationToken) + => Render(await Api(api => api.GetDeletion(name, cancellationToken)), "Delete"); + + /// Deletes the account after the administrator's password. + [Route("admin/users/{name}/delete"), HttpPost, PageHandler] + public async Task DeleteUserConfirmed(string name, string? soleOwned, string? password, CancellationToken cancellationToken) + => Render(await Api(api => api.Delete(name, new UserDeletionForm(soleOwned, password), cancellationToken)), "Delete"); + + // ---------------------------------------------------------------- UserPackages + + /// Lists the package IDs one user owns. + [Route("admin/users/{name}/packages"), HttpGet, HttpHead, PageHandler, RepositoryPage] + public async Task UserPackages(string name, CancellationToken cancellationToken) + => Render(await Api(api => api.GetPackages(name, cancellationToken)), "Packages"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ContactOwnersController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ContactOwnersController.cs new file mode 100644 index 000000000..e29a3ea14 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ContactOwnersController.cs @@ -0,0 +1,38 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// Lets a signed-in user write to the owners of a package (/packages/{id}/contact-owners, also at /r/{repo}/…). It +/// replaces the /Packages/ContactOwners Razor Page (same URLs and form fields, same gates: accounts enabled, mail configured, +/// signed in); the work is done by (the JSON twin, over ContactOwnersUseCase), which this +/// controller calls in process and renders. +/// +[Route("packages/{id}/contact-owners")] +[RepositoryPage(NotOnVirtual = true)] +public sealed class ContactOwnersController : AccountControllerBase +{ + private const string ViewName = "Index"; + + /// + protected override bool RequiresSignIn => true; + + /// + protected override bool RequiresEmail => true; + + /// Shows the form; 404 when the package has no owner. + [HttpGet, HttpHead, PageHandler] + public async Task Index([FromRoute] string? id, CancellationToken cancellationToken) + => Render(await Api(api => api.Get(id, cancellationToken)), ViewName); + + /// Sends the message to the owners. + [HttpPost, PageHandler] + public async Task Send([FromRoute] string? id, [FromForm] ContactOwnersForm form, CancellationToken cancellationToken) + => Render(await Api(api => api.Send(id, form, cancellationToken)), ViewName); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/DockerManageController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/DockerManageController.cs new file mode 100644 index 000000000..7bc931ef2 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/DockerManageController.cs @@ -0,0 +1,89 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The delete tools of a Docker image (/docker-manage/{**image}, also at /r/{repo}/…): delete a tag, a manifest, the +/// unused layers or the whole image. It replaces the /Packages/DockerManage Razor Page (same URLs, same ?handler= +/// forms, same gates); the work is done by (the JSON twin, over DockerManageUseCase), +/// which this controller calls in process and renders. The image-name / repository-kind / Delete-permission check runs in +/// , before the global repository filter. +/// +[Route("docker-manage/{**image}")] +[RepositoryPage(Format = RepositoryFormat.Docker, NotOnVirtual = true)] +public sealed class DockerManageController : AccountControllerBase +{ + private const string ViewName = "Index"; + + /// + protected override bool RequiresSignIn => true; + + private string? Image => RouteData.Values.TryGetValue("image", out var image) ? image as string : null; + + /// + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + OnActionExecuting(context); + if (context.Result != null) return; + + var refusal = await UiApiEntry.InvokeAsync( + this, + api => api.EnterAsync(PackageControllerSupport.Route(context, "image"), HttpMethods.IsPost(Request.Method), context.HttpContext.RequestAborted)); + if (refusal != null) + { + context.Result = Present(refusal); + return; + } + + OnActionExecuted(await next()); + } + + /// The screen. + [HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => Present(await Api(api => api.Get(Image, cancellationToken))); + + /// Deletes a tag, after the password. + [HttpPost, PageHandler("DeleteTag")] + public async Task DeleteTag(string? tag, string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.DeleteTag(Image, new DockerManageForm { Tag = tag, Password = password }, cancellationToken))); + + /// Deletes a manifest with its tags, after the password. + [HttpPost, PageHandler("DeleteManifest")] + public async Task DeleteManifest(string? digest, string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.DeleteManifest(Image, new DockerManageForm { Digest = digest, Password = password }, cancellationToken))); + + /// Removes the layers no manifest uses, after the password. + [HttpPost, PageHandler("Prune")] + public async Task Prune(string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.Prune(Image, new DockerManageForm { Password = password }, cancellationToken))); + + /// Deletes the whole image, after the password. + [HttpPost, PageHandler("DeleteImage")] + public async Task DeleteImage(string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.DeleteImage(Image, new DockerManageForm { Password = password }, cancellationToken))); + + /// + /// A POST that names no handler (or one this screen does not have), such as a stray <form> without + /// ?handler=: the antiforgery check has already run, and there is nothing to do, so the answer is 404. (A Razor Page + /// with only named POST handlers behaved alike for the caller; without this action routing would answer 404 before the + /// antiforgery filter and an unprotected POST would not be refused with 400.) It is marked + /// : it is not one of the screen's handlers, so it stays out of the route contract. + /// + [HttpPost, PageHandler, FallbackHandler] + public IActionResult NoHandler() => NotFound(); + + private IActionResult Present(UiApiResponse response) => Render(response, ViewName); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/MavenManageController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/MavenManageController.cs new file mode 100644 index 000000000..d5ef561bf --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/MavenManageController.cs @@ -0,0 +1,110 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The owners' screen for a Maven artifact (/maven-manage/{group}/{artifact}, also at /r/{repo}/…): owners, versions, +/// the files of the chosen version, deletion and snapshot clean-up. It replaces the /Packages/MavenManage Razor Page (same +/// URLs, same ?handler= forms, same gates); the work is done by (the JSON twin, over +/// MavenManageUseCase), which this controller calls in process and renders. The coordinates / repository-kind / ownership check +/// runs in , before the global repository filter. +/// +[Route("maven-manage/{group}/{artifact}")] +[RepositoryPage(Format = RepositoryFormat.Maven, NotOnVirtual = true, NotOnRemote = true)] +public sealed class MavenManageController : AccountControllerBase +{ + private const string ViewName = "Index"; + + /// + protected override bool RequiresSignIn => true; + + private string? Group => RouteData.Values.TryGetValue("group", out var group) ? group as string : null; + + private string? Artifact => RouteData.Values.TryGetValue("artifact", out var artifact) ? artifact as string : null; + + /// The version whose files are listed: the form field of a POST, else the query string. + private string? SelectedVersion => PackageControllerSupport.FormOrQuery(Request, "version"); + + /// + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + OnActionExecuting(context); + if (context.Result != null) return; + + var refusal = await UiApiEntry.InvokeAsync( + this, + api => api.EnterAsync( + PackageControllerSupport.Route(context, "group"), + PackageControllerSupport.Route(context, "artifact"), + PackageControllerSupport.FormOrQuery(context, "version"), + PackageControllerSupport.HandlerName(context), + HttpMethods.IsPost(Request.Method), + context.HttpContext.RequestAborted)); + if (refusal != null) + { + context.Result = Present(refusal); + return; + } + + OnActionExecuted(await next()); + } + + /// The screen. + [HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => Present(await Api(api => api.Get(Group, Artifact, SelectedVersion, cancellationToken))); + + /// Adds an owner. + [HttpPost, PageHandler("AddOwner")] + public async Task AddOwner(string ownerName, CancellationToken cancellationToken) + => Present(await Api(api => api.AddOwner(Group, Artifact, new MavenManageForm { Version = SelectedVersion, OwnerName = ownerName }, cancellationToken))); + + /// Removes an owner. + [HttpPost, PageHandler("RemoveOwner")] + public async Task RemoveOwner(string ownerName, CancellationToken cancellationToken) + => Present(await Api(api => api.RemoveOwner(Group, Artifact, new MavenManageForm { Version = SelectedVersion, OwnerName = ownerName }, cancellationToken))); + + /// Deletes one file of the chosen version, after the password. + [HttpPost, PageHandler("DeleteFile")] + public async Task DeleteFile(string? fileName, string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.DeleteFile(Group, Artifact, new MavenManageForm { Version = SelectedVersion, FileName = fileName, Password = password }, cancellationToken))); + + /// Deletes one version, after the password. + [HttpPost, PageHandler("DeleteVersion")] + public async Task DeleteVersion(string? version, string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.DeleteVersion(Group, Artifact, new MavenManageForm { Version = version, Password = password }, cancellationToken))); + + /// Deletes the whole artifact, after the password. + [HttpPost, PageHandler("DeleteArtifact")] + public async Task DeleteArtifact(string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.DeleteArtifact(Group, Artifact, new MavenManageForm { Version = SelectedVersion, Password = password }, cancellationToken))); + + /// Deletes old snapshot builds of a version, after the password. + [HttpPost, PageHandler("Cleanup")] + public async Task Cleanup(string? version, string? keep, string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.Cleanup(Group, Artifact, new MavenManageForm { Version = version, Keep = keep, Password = password }, cancellationToken))); + + /// + /// A POST that names no handler (or one this screen does not have), such as a stray <form> without + /// ?handler=: the antiforgery check has already run, and there is nothing to do, so the answer is 404. (A Razor Page + /// with only named POST handlers behaved alike for the caller; without this action routing would answer 404 before the + /// antiforgery filter and an unprotected POST would not be refused with 400.) It is marked + /// : it is not one of the screen's handlers, so it stays out of the route contract. + /// + [HttpPost, PageHandler, FallbackHandler] + public IActionResult NoHandler() => NotFound(); + + private IActionResult Present(UiApiResponse response) => Render(response, ViewName); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/NpmManageController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/NpmManageController.cs new file mode 100644 index 000000000..c28067690 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/NpmManageController.cs @@ -0,0 +1,108 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The owners' screen for an npm package (/npm-manage/{*id}, also at /r/{repo}/…): owners, dist-tags, deprecation and +/// unpublishing. It replaces the /Packages/NpmManage Razor Page (same URLs, same ?handler= forms, same gates); the work is done +/// by (the JSON twin, over NpmManageUseCase), which this controller calls in process and +/// renders. The name / repository-kind / ownership check runs in , before the global repository filter. +/// +[Route("npm-manage/{*id}")] +[RepositoryPage(Format = RepositoryFormat.Npm, NotOnVirtual = true, NotOnRemote = true)] +public sealed class NpmManageController : AccountControllerBase +{ + private const string ViewName = "Index"; + + /// + protected override bool RequiresSignIn => true; + + private string? Id => RouteData.Values.TryGetValue("id", out var id) ? id as string : null; + + /// + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + OnActionExecuting(context); + if (context.Result != null) return; + + var refusal = await UiApiEntry.InvokeAsync( + this, + api => api.EnterAsync(PackageControllerSupport.Route(context, "id"), PackageControllerSupport.HandlerName(context), HttpMethods.IsPost(Request.Method), context.HttpContext.RequestAborted)); + if (refusal != null) + { + context.Result = Present(refusal); + return; + } + + OnActionExecuted(await next()); + } + + /// The screen. + [HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => Present(await Api(api => api.Get(Id, cancellationToken))); + + /// Adds an owner. + [HttpPost, PageHandler("AddOwner")] + public async Task AddOwner(string ownerName, CancellationToken cancellationToken) + => Present(await Api(api => api.AddOwner(Id, new NpmManageOwnerForm { OwnerName = ownerName }, cancellationToken))); + + /// Removes an owner. + [HttpPost, PageHandler("RemoveOwner")] + public async Task RemoveOwner(string ownerName, CancellationToken cancellationToken) + => Present(await Api(api => api.RemoveOwner(Id, new NpmManageOwnerForm { OwnerName = ownerName }, cancellationToken))); + + /// Points a dist-tag at a version. + [HttpPost, PageHandler("SetTag")] + public async Task SetTag(string tag, string version, CancellationToken cancellationToken) + => Present(await Api(api => api.SetTag(Id, new NpmManageTagForm { Tag = tag, Version = version }, cancellationToken))); + + /// Removes a dist-tag. + [HttpPost, PageHandler("RemoveTag")] + public async Task RemoveTag(string tag, CancellationToken cancellationToken) + => Present(await Api(api => api.RemoveTag(Id, new NpmManageTagForm { Tag = tag }, cancellationToken))); + + /// Deprecates a version. + [HttpPost, PageHandler("Deprecate")] + public async Task Deprecate(string version, string? message, CancellationToken cancellationToken) + => Present(await Api(api => api.Deprecate(Id, new NpmManageDeprecateForm { Version = version, Message = message }, cancellationToken))); + + /// Removes a version's deprecation. + [HttpPost, PageHandler("Undeprecate")] + public async Task Undeprecate(string version, CancellationToken cancellationToken) + => Present(await Api(api => api.Undeprecate(Id, new NpmManageDeprecateForm { Version = version }, cancellationToken))); + + /// Unpublishes one version, after the password is confirmed. + [HttpPost, PageHandler("Unpublish")] + public async Task Unpublish(string version, string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.Unpublish(Id, new NpmManageUnpublishForm { Version = version, Password = password }, cancellationToken))); + + /// Unpublishes every version, after the password is confirmed. + [HttpPost, PageHandler("UnpublishAll")] + public async Task UnpublishAll(string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.UnpublishAll(Id, new NpmManageUnpublishForm { Password = password }, cancellationToken))); + + /// + /// A POST that names no handler (or one this screen does not have), such as a stray <form> without + /// ?handler=: the antiforgery check has already run, and there is nothing to do, so the answer is 404. (A Razor Page + /// with only named POST handlers behaved alike for the caller; without this action routing would answer 404 before the + /// antiforgery filter and an unprotected POST would not be refused with 400.) It is marked + /// : it is not one of the screen's handlers, so it stays out of the route contract. + /// + [HttpPost, PageHandler, FallbackHandler] + public IActionResult NoHandler() => NotFound(); + + private IActionResult Present(UiApiResponse response) => Render(response, ViewName); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/PackageManageController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/PackageManageController.cs new file mode 100644 index 000000000..9aa35f430 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/PackageManageController.cs @@ -0,0 +1,161 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Frontend.Mvc.Screens; +using BaGet.Frontend.Mvc.UI; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using BaGet.Identity.Application.Models.Packages; +using BaGet.Identity.Application.UseCases.Packages; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// The owners' screen for a package ID (/packages/{id}/manage, also at /r/{repo}/…): owners, versions, deprecation, +/// vulnerabilities, symbols and abuse reports. It replaces the /Packages/Manage Razor Page (same URLs, same +/// ?handler= forms, same gates); the work is done by (the JSON twin, over +/// ), which this controller calls in process and renders. +/// +/// +/// The fallback NoHandler is marked : it is not a handler of the screen. +/// The ownership / administrator check runs in , before the global repository filter. +/// +[Route("packages/{id}/manage")] +[RepositoryPage(NotOnVirtual = true)] +public sealed class PackageManageController : AccountControllerBase +{ + private const string ViewName = "Index"; + + /// + protected override bool RequiresSignIn => true; + + private string? Id => RouteData.Values.TryGetValue("id", out var id) ? id as string : null; + + /// + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + OnActionExecuting(context); + if (context.Result != null) return; + + var refusal = await UiApiEntry.InvokeAsync( + this, + api => api.EnterAsync(PackageControllerSupport.Route(context, "id"), PackageControllerSupport.HandlerName(context), HttpMethods.IsPost(Request.Method), context.HttpContext.RequestAborted)); + if (refusal != null) + { + context.Result = Present(refusal); + return; + } + + OnActionExecuted(await next()); + } + + /// The screen. + [HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => Present(await Api(api => api.Get(Id!, cancellationToken))); + + /// Adds an owner. + [HttpPost, PageHandler("AddOwner")] + public async Task AddOwner(string ownerName, CancellationToken cancellationToken) + => Present(await Api(api => api.AddOwner(Id!, new PackageManageOwnerForm { OwnerName = ownerName }, cancellationToken))); + + /// Removes an owner. + [HttpPost, PageHandler("RemoveOwner")] + public async Task RemoveOwner(string ownerName, CancellationToken cancellationToken) + => Present(await Api(api => api.RemoveOwner(Id!, new PackageManageOwnerForm { OwnerName = ownerName }, cancellationToken))); + + /// Unlists a version. + [HttpPost, PageHandler("Unlist")] + public async Task Unlist(string version, CancellationToken cancellationToken) + => Present(await Api(api => api.Unlist(Id!, new PackageManageVersionForm { Version = version }, cancellationToken))); + + /// Relists a version. + [HttpPost, PageHandler("Relist")] + public async Task Relist(string version, CancellationToken cancellationToken) + => Present(await Api(api => api.Relist(Id!, new PackageManageVersionForm { Version = version }, cancellationToken))); + + /// Deletes a version as the server is configured to (unlist or permanent). + [HttpPost, PageHandler("Delete")] + public async Task Delete(string version, CancellationToken cancellationToken) + => Present(await Api(api => api.Delete(Id!, new PackageManageVersionForm { Version = version }, cancellationToken))); + + /// Permanently deletes a version (administrators, after the password). + [HttpPost, PageHandler("HardDelete")] + public async Task HardDelete(string version, string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.HardDelete(Id!, new PackageManageHardDeleteForm { Version = version, Password = password }, cancellationToken))); + + /// Permanently deletes every version and the owners (administrators, after the password). + [HttpPost, PageHandler("HardDeleteAll")] + public async Task HardDeleteAll(string? password, CancellationToken cancellationToken) + => Present(await Api(api => api.HardDeleteAll(Id!, new PackageManagePasswordForm { Password = password }, cancellationToken))); + + /// Deprecates a version. + [HttpPost, PageHandler("Deprecate")] + public async Task Deprecate( + string version, + List? reasons, + string message, + string alternatePackageId, + string? alternateVersionRange, + CancellationToken cancellationToken) + => Present(await Api(api => api.Deprecate( + Id!, + new PackageManageDeprecateForm { Version = version, Reasons = reasons, Message = message, AlternatePackageId = alternatePackageId, AlternateVersionRange = alternateVersionRange }, + cancellationToken))); + + /// Removes a version's deprecation. + [HttpPost, PageHandler("Undeprecate")] + public async Task Undeprecate(string version, CancellationToken cancellationToken) + => Present(await Api(api => api.Undeprecate(Id!, new PackageManageVersionForm { Version = version }, cancellationToken))); + + /// Adds a vulnerability to a version. + [HttpPost, PageHandler("AddVulnerability")] + public async Task AddVulnerability( + string version, + string? advisoryUrl, + int severity, + string? versionRange, + CancellationToken cancellationToken) + => Present(await Api(api => api.AddVulnerability( + Id!, + new PackageManageVulnerabilityForm { Version = version, AdvisoryUrl = advisoryUrl, Severity = severity, VersionRange = versionRange }, + cancellationToken))); + + /// Removes a vulnerability from a version. + [HttpPost, PageHandler("RemoveVulnerability")] + public async Task RemoveVulnerability(string version, int key, CancellationToken cancellationToken) + => Present(await Api(api => api.RemoveVulnerability(Id!, new PackageManageRemoveVulnerabilityForm { Version = version, Key = key }, cancellationToken))); + + /// Marks or unmarks the ID as verified (administrators). + [HttpPost, PageHandler("SetVerified")] + public async Task SetVerified(bool verified, CancellationToken cancellationToken) + => Present(await Api(api => api.SetVerified(Id!, new PackageManageVerifiedForm { Verified = verified }, cancellationToken))); + + /// Deletes the PDBs recorded for a version. + [HttpPost, PageHandler("DeleteSymbols")] + public async Task DeleteSymbols(string version, CancellationToken cancellationToken) + => Present(await Api(api => api.DeleteSymbols(Id!, new PackageManageVersionForm { Version = version }, cancellationToken))); + + /// Resolves an abuse report. + [HttpPost, PageHandler("ResolveReport")] + public async Task ResolveReport(int key, CancellationToken cancellationToken) + => Present(await Api(api => api.ResolveReport(Id!, new PackageManageReportForm { Key = key }, cancellationToken))); + + /// + /// A POST that names no handler (or one this screen does not have), such as a stray <form> without + /// ?handler=: the antiforgery check has already run, and there is nothing to do, so the answer is 404. (A Razor Page + /// with only named POST handlers behaved alike for the caller; without this action routing would answer 404 before the + /// antiforgery filter and an unprotected POST would not be refused with 400.) It is marked + /// : it is not one of the screen's handlers, so it stays out of the route contract. + /// + [HttpPost, PageHandler, FallbackHandler] + public IActionResult NoHandler() => NotFound(); + + private IActionResult Present(UiApiResponse response) + => Render(response, ViewName, screen => ManageViewModel.From(screen)); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ProfileController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ProfileController.cs new file mode 100644 index 000000000..40bb83451 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ProfileController.cs @@ -0,0 +1,22 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Account; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// A user's or an organization's public page: the packages it owns (/profiles/{name}, and under +/// /r/{repo}/ too). It replaces the Razor Page Profiles/Profile. The work is done by . +/// +[RepositoryPage] +public sealed class ProfileController : AccountControllerBase +{ + /// The profile named ; 404 when neither a user nor an organization has it. + [Route("profiles/{name}"), HttpGet, HttpHead, PageHandler] + public async Task Profile(string? name, CancellationToken cancellationToken) + => Render(await Api(api => api.Profile(name, cancellationToken)), "Profile"); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ScanArtifactController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ScanArtifactController.cs new file mode 100644 index 000000000..4a735f13f --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ScanArtifactController.cs @@ -0,0 +1,38 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Policies; +using BaGet.Identity.Models.Packages; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// Scan now for one version of an artifact of any format (/scan-artifact, also at /r/{repo}/…). It replaces +/// the /Packages/Scan Razor Page (same URL, same form fields, same gates: signed in, the Manage action on the artifact); the work is +/// done by (the JSON twin, over ScanArtifactUseCase), which this controller calls in +/// process and renders. +/// +[Route("scan-artifact")] +[RepositoryPage(AnyFormat = true, NotOnVirtual = true)] +public sealed class ScanArtifactController : AccountControllerBase +{ + private const string ViewName = "Index"; + + /// + protected override bool RequiresSignIn => true; + + /// Shows the form (and the stored result) of the version. + [HttpGet, HttpHead, PageHandler] + public async Task Index(string? name, string? version, string? returnUrl, CancellationToken cancellationToken) + => Render(await Api(api => api.Get(name, version, returnUrl, cancellationToken)), ViewName); + + /// Scans the version now (or queues it, for an image) and shows the outcome. + [HttpPost, PageHandler] + public async Task Scan(string? name, string? version, string? returnUrl, CancellationToken cancellationToken) + => Render( + await Api(api => api.Scan(new ScanArtifactForm { Name = name, Version = version, ReturnUrl = returnUrl }, cancellationToken)), + ViewName); +} diff --git a/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ValidationStatusPageController.cs b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ValidationStatusPageController.cs new file mode 100644 index 000000000..3f1b9bf4e --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Controllers/FrontEnd/ValidationStatusPageController.cs @@ -0,0 +1,30 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Identity.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Identity.Application.Models.Operations; + +namespace BaGet.Identity.Controllers.FrontEnd; + +/// +/// Where a pushed package stands in validation (/packages/{id}/validation, also at /r/{repo}/…): the newest submission +/// of each version and its steps. It replaces the /Packages/ValidationStatus Razor Page (same URL, same gates); the work is done by +/// (the JSON twin, over ValidationStatusUseCase), which this controller calls in +/// process and renders. +/// +[Route("packages/{id}/validation")] +[RepositoryPage(NotOnVirtual = true)] +public sealed class ValidationStatusPageController : AccountControllerBase +{ + private const string ViewName = "Index"; + + /// + protected override bool RequiresSignIn => true; + + /// Shows the submissions of the ID, 403 without the permission, 404 when validation never saw it. + [HttpGet, HttpHead, PageHandler] + public async Task Index([FromRoute] string? id, CancellationToken cancellationToken) + => Render(await Api(api => api.Get(id, cancellationToken)), ViewName); +} diff --git a/src/BaGet.Identity.FrontEnd/Extensions/RepositoryLinks.cs b/src/BaGet.Identity.FrontEnd/Extensions/RepositoryLinks.cs new file mode 100644 index 000000000..d6b307b3f --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Extensions/RepositoryLinks.cs @@ -0,0 +1,39 @@ +using System; +using BaGet.Core; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Identity.Extensions; + +/// +/// Links to a repository's pages that keep the package ID or user name exactly as written. Url.Action lowercases +/// the whole path (RouteOptions.LowercaseUrls), which would turn Contoso.Lib into contoso.lib in +/// every link and in the heading of the page it opens; these keep the case and add the r/{name}/ prefix of the +/// repository instead. +/// +public static class RepositoryLinks +{ + /// + /// ~/{path} in the repository of the current request (~/r/{name}/{path} for a non-default one). + /// + public static string RepositoryContent(this IUrlHelper url, string path) + { + if (url == null) throw new ArgumentNullException(nameof(url)); + + var repository = url.ActionContext.HttpContext.RequestServices.GetService()?.Current + ?? RepositoryInfo.Default; + + return url.RepositoryContent(repository, path); + } + + /// + /// ~/{path} in . + /// + public static string RepositoryContent(this IUrlHelper url, RepositoryInfo repository, string path) + { + if (url == null) throw new ArgumentNullException(nameof(url)); + if (repository == null) throw new ArgumentNullException(nameof(repository)); + + return url.Content("~/" + repository.PathPrefix + (path ?? string.Empty).TrimStart('/')) ?? string.Empty; + } +} diff --git a/src/BaGet.Identity.FrontEnd/Models/Packages/ManageViewModel.cs b/src/BaGet.Identity.FrontEnd/Models/Packages/ManageViewModel.cs new file mode 100644 index 000000000..29eef2c26 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Models/Packages/ManageViewModel.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; +using BaGet.Identity.Application.Models.Packages; + +namespace BaGet.Identity.Models.Packages; + +/// +/// What the package management screen (/packages/{id}/manage) shows to the view: built from the screen's plain model +/// (, the JSON model of the twin) so a host's view override keeps the entities it was written against. +/// +public sealed class ManageViewModel +{ + /// The view's model for what the screen's use case produced. + internal static ManageViewModel From(PackageManageScreen screen) + { + if (screen == null) throw new ArgumentNullException(nameof(screen)); + + var model = new ManageViewModel + { + Id = screen.Id, + Message = screen.Message, + HasValidation = screen.HasValidation, + SymbolsSupported = screen.SymbolsSupported, + SeverityNames = screen.SeverityNames, + IsAdministrator = screen.IsAdministrator, + ActingAsAdministrator = screen.ActingAsAdministrator, + HasPassword = screen.HasPassword, + Reauthenticated = screen.Reauthenticated, + CanReauthenticate = screen.CanReauthenticate, + DeletionBehavior = screen.DeletionBehavior, + IsReadOnlyMode = screen.IsReadOnlyMode, + Owners = screen.Owners.Select(o => new PackageOwner { PackageId = screen.Id, OwnerName = o.OwnerName, IsVerified = o.IsVerified }).ToList(), + Versions = screen.Versions.Select(v => new Package + { + Id = screen.Id, + NormalizedVersionString = v.NormalizedVersion, + OriginalVersionString = v.Version, + Downloads = v.Downloads, + Listed = v.Listed, + Deprecation = v.Deprecation == null + ? null + : new PackageDeprecation + { + Reasons = v.Deprecation.Reasons.ToArray(), + Message = v.Deprecation.Message, + AlternatePackageId = v.Deprecation.AlternatePackageId, + AlternateVersionRange = v.Deprecation.AlternateVersionRange, + }, + Vulnerabilities = v.Vulnerabilities + .Select(x => new PackageVulnerability { Key = x.Key, AdvisoryUrl = x.AdvisoryUrl, Severity = x.Severity, VersionRange = x.VersionRange, Source = x.Source }) + .ToList(), + }).ToList(), + Reports = screen.Reports + .Select(r => new AbuseReport { Key = r.Key, PackageId = screen.Id, PackageVersion = r.PackageVersion, Reason = r.Reason, Details = r.Details, ReporterEmail = r.ReporterEmail }) + .ToList(), + Symbols = screen.Symbols.ToDictionary( + p => p.Key, + p => (IReadOnlyList)p.Value.Select(s => new SymbolReference(s.FileName, s.Key)).ToList(), + StringComparer.OrdinalIgnoreCase), + }; + + return model; + } + + /// The package ID from the address. + public string? Id { get; internal set; } + + /// The ID's owners. + public IReadOnlyList Owners { get; internal set; } = Array.Empty(); + + /// The ID's versions, newest first, unlisted ones included. + public IReadOnlyList Versions { get; internal set; } = Array.Empty(); + + /// The open abuse reports against the ID. + public IReadOnlyList Reports { get; internal set; } = Array.Empty(); + + /// The outcome of the last action. + public string? Message { get; internal set; } + + /// Whether validation has submissions for the ID (the page links to their status). + public bool HasValidation { get; internal set; } + + /// Whether the ID is verified (reserved): an owner row carries the flag. + public bool IsVerified => Owners.Any(o => o.IsVerified); + + /// The PDBs indexed from each version's symbol package, by normalized version (case-insensitive). + public IReadOnlyDictionary> Symbols { get; internal set; } + = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + /// Whether the database records symbols per package version (false for Azure Table). + public bool SymbolsSupported { get; internal set; } + + /// The severity names a vulnerability can have, by their protocol number. + public IReadOnlyList SeverityNames { get; internal set; } = Array.Empty(); + + /// Whether the signed in user is an administrator. + public bool IsAdministrator { get; internal set; } + + /// Whether the user manages this ID only as an administrator (not as an owner). + public bool ActingAsAdministrator { get; internal set; } + + /// Whether the signed in administrator has a password to confirm with. + public bool HasPassword { get; internal set; } = true; + + /// For an account without a password: it signed in again with its provider a moment ago. + public bool Reauthenticated { get; internal set; } + + /// Whether an external provider is available to sign in again with. + public bool CanReauthenticate { get; internal set; } + + /// What a deletion does on this server. + public PackageDeletionBehavior DeletionBehavior { get; internal set; } + + /// Whether the server refuses writes. + public bool IsReadOnlyMode { get; internal set; } + + /// Whether a deletion removes the rows and files (rather than unlisting). + public bool DeletionIsPermanent => DeletionBehavior == PackageDeletionBehavior.HardDelete; + + /// The label of the delete button. + public string DeleteLabel => DeletionIsPermanent + ? "Delete this version permanently" + : "Unlist this version"; + + /// What the delete button does, in words. + public string DeleteCaption => DeletionIsPermanent + ? "Removes the database rows and the .nupkg, .nuspec, readme and icon from storage. " + + "Consumers can no longer restore it. Indexed PDBs keep being served, and an " + + "external search index keeps the version until it is reindexed." + : "Hidden from search and from the version list; anyone who knows the exact version " + + "can still restore it."; +} diff --git a/src/BaGet.Identity.FrontEnd/README.md b/src/BaGet.Identity.FrontEnd/README.md new file mode 100644 index 000000000..ae1fa4431 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/README.md @@ -0,0 +1,30 @@ +# Extension.BaGet.Identity.FrontEnd + +The account and administration **screens** of [BaGet Extension](https://pieroviano.github.io/BaGet/): view controllers and views (sign-in, profile, API keys, +package management, administration). Each controller binds the form, calls its JSON twin (`Extension.BaGet.Identity.Api`) in process and renders. +A host that serves only the APIs does not reference it. + +```powershell +dotnet add package Extension.BaGet.Identity.FrontEnd +``` + +Registered by `AddBaGetFrontEnd()` of `Extension.BaGet.Web.FrontEnd`, which adds this assembly as an MVC application part. + +## Contents + +| Folder | Role | +|---|---| +| `Controllers/FrontEnd` | The view controllers: `Account*`, `ProfileController`, `PackageManage`, `NpmManage`, `MavenManage`, `DockerManage`, `ContactOwners`, `ScanArtifact`, `ValidationStatusPage`, `Admin*` | +| `Views//.cshtml` | The screens; a host overrides one with its own `Views//.cshtml`. The layout and shared partials are in `Extension.BaGet.Frontend.Base` | +| `Models/Packages` | `ManageViewModel` (the form models the twins also bind stay in `Extension.BaGet.Identity.Api`) | +| `Extensions` | `RepositoryLinks` (`Url.RepositoryContent`) | + +In a view, link with `asp-controller` / `asp-action` (and `asp-route-handler="X"` for a named handler). + +## Layout + +One type per file, no nested types, namespace = `BaGet.Identity` + folder (`CodeLayoutTests`). + +## Links + +[UI API](https://pieroviano.github.io/BaGet/ui-api/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/ConfirmEmail.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/ConfirmEmail.cshtml new file mode 100644 index 000000000..c6d361159 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/ConfirmEmail.cshtml @@ -0,0 +1,25 @@ +@model BaGet.Identity.Application.Models.Account.ConfirmEmailViewModel +@{ + ViewData["Title"] = "Confirm email"; +} + +
+

Confirm email

+ + + @if (Model.Succeeded) + { + + @if (Model.PendingApproval) + { +

An administrator must still enable your account before you can sign in.

+ } +

Sign in

+ } + else + { + + } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/ForgotPassword.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/ForgotPassword.cshtml new file mode 100644 index 000000000..b3d76d28b --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/ForgotPassword.cshtml @@ -0,0 +1,28 @@ +@model BaGet.Identity.Application.Models.Account.ForgotPasswordViewModel +@{ + ViewData["Title"] = "Forgot password"; +} + +
+

Forgot password

+ + + @if (Model.Sent) + { + + } + else + { +
+
+
+ + + +
+ +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/Login.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/Login.cshtml new file mode 100644 index 000000000..aa3920397 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/Login.cshtml @@ -0,0 +1,60 @@ +@model BaGet.Identity.Application.Models.Account.LoginViewModel +@{ + ViewData["Title"] = "Sign in"; +} + +
+

Sign in

+ + + @if (Model.Error != null) + { + + } + + @if (Model.Notice != null) + { +
@Model.Notice
+ } + +
+ +
+ + + +
+
+ + + +
+
+ +
+ +
+ + @if (Model.EmailIsConfigured) + { +

Forgot password?

+ } + + @if (Model.HasExternalProvider) + { +
+
+ + @foreach (var provider in Model.ExternalProviders) + { + + } +
+ } + + @if (Model.AllowRegistration) + { +
+

No account? Create one.

+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/LoginWith2fa.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/LoginWith2fa.cshtml new file mode 100644 index 000000000..621ff3409 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/LoginWith2fa.cshtml @@ -0,0 +1,30 @@ +@model BaGet.Identity.Application.Models.Account.TwoFactorLoginViewModel +@{ + ViewData["Title"] = "Two-factor authentication"; +} + +
+

Two-factor authentication

+ + + @if (Model.Error != null) + { + + } + +

Enter the code from your authenticator app.

+
+ + +
+ + + +
+ +
+

+ Lost the device? + Use a recovery code. +

+
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/LoginWithRecoveryCode.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/LoginWithRecoveryCode.cshtml new file mode 100644 index 000000000..fada1d56a --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/LoginWithRecoveryCode.cshtml @@ -0,0 +1,25 @@ +@model BaGet.Identity.Application.Models.Account.RecoveryCodeLoginViewModel +@{ + ViewData["Title"] = "Recovery code"; +} + +
+

Recovery code

+ + + @if (Model.Error != null) + { + + } + +

Enter one of the recovery codes you saved when you turned on two-factor authentication.

+
+ +
+ + + +
+ +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/Logout.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/Logout.cshtml new file mode 100644 index 000000000..2159ca59c --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/Logout.cshtml @@ -0,0 +1,12 @@ +@{ + ViewData["Title"] = "Sign out"; +} + +
+

Sign out

+ + +
+ +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/Reauthenticate.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/Reauthenticate.cshtml new file mode 100644 index 000000000..30d8e26e6 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/Reauthenticate.cshtml @@ -0,0 +1,26 @@ +@model BaGet.Identity.Application.Models.Account.ReauthenticateViewModel +@{ + ViewData["Title"] = "Confirm it is you"; +} + +
+

Confirm it is you

+ + + @if (Model.Error != null) + { + + } + @if (Model.Providers is { Count: > 0 }) + { +

Which provider do you want to sign in again with?

+
+ + @foreach (var provider in Model.Providers) + { + + } +
+ } +

Back to account settings

+
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/Register.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/Register.cshtml new file mode 100644 index 000000000..17d9ecb25 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/Register.cshtml @@ -0,0 +1,55 @@ +@model BaGet.Identity.Application.Models.Account.RegisterViewModel +@{ + ViewData["Title"] = "Create an account"; +} + +
+

Create an account

+ + + @if (Model.ConfirmationSent) + { + + } + else if (Model.AwaitingApproval) + { + + } + else + { +
+
+ +
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+ +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/Account/ResetPassword.cshtml b/src/BaGet.Identity.FrontEnd/Views/Account/ResetPassword.cshtml new file mode 100644 index 000000000..fd05a73f5 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Account/ResetPassword.cshtml @@ -0,0 +1,34 @@ +@model BaGet.Identity.Application.Models.Account.ResetPasswordViewModel +@{ + ViewData["Title"] = "Reset password"; +} + +
+

Reset password

+ + + @if (Model.Error != null) + { + + } + + @if (Model.LinkIsUsable) + { +
+
+ + +
+ + + +
+
+ + + +
+ +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AccountOrganizations/Organizations.cshtml b/src/BaGet.Identity.FrontEnd/Views/AccountOrganizations/Organizations.cshtml new file mode 100644 index 000000000..206c72b72 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AccountOrganizations/Organizations.cshtml @@ -0,0 +1,55 @@ +@model BaGet.Identity.Application.Models.Organizations.OrganizationsViewModel +@{ + ViewData["Title"] = "Organizations"; +} + +
+

Organizations

+ + + @if (Model.Message != null) + { + + } + + @foreach (var organization in Model.Organizations) + { +

@organization.Name

+ + + @foreach (var member in organization.Members ?? []) + { + + + + + } + +
@member.UserName@(member.IsAdmin ? " (administrator)" : "") + @if (organization.IsAdmin || member.UserName == User.Identity?.Name) + { +
+ + + +
+ } +
+ + @if (organization.IsAdmin) + { +
+ + + + +
+ } + } + +

Create an organization

+
+ + +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AccountPackages/Access.cshtml b/src/BaGet.Identity.FrontEnd/Views/AccountPackages/Access.cshtml new file mode 100644 index 000000000..94fa30f16 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AccountPackages/Access.cshtml @@ -0,0 +1,60 @@ +@model BaGet.Identity.Application.Models.Account.AccountAccessViewModel +@{ + ViewData["Title"] = "My access"; +} + +
+

My access

+ + +

+ What you may do in each repository, and which permission targets or project roles say so. Changing an existing package + ID also needs you to own it; that is not shown here. Repositories where you hold nothing are not listed. +

+ + @if (!Model.ModelAvailable) + { + + } + +
+
+ + +
+ + Optional: shows how include and exclude patterns apply to one package. +
+ + @if (Model.AdministeredProjects.Count > 0) + { +

+ You administer + @foreach (var project in Model.AdministeredProjects) + { + @project + } +

+ } + + @if (Model.Rows.Count == 0) + { +

You hold no action in any repository.

+ } + + @foreach (var row in Model.Rows) + { +
+

+ @row.Repository.Name + @if (row.Repository.IsDefault) + { + Default + } +

+ +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AccountPackages/Packages.cshtml b/src/BaGet.Identity.FrontEnd/Views/AccountPackages/Packages.cshtml new file mode 100644 index 000000000..9c5a6f654 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AccountPackages/Packages.cshtml @@ -0,0 +1,105 @@ +@using BaGet.Identity.Extensions +@model BaGet.Identity.Application.Models.Packages.AccountPackagesViewModel +@{ + ViewData["Title"] = "My packages"; +} + +
+

My packages

+ + + @if (Model.IsEmpty) + { +

+ You do not own any package yet. Upload one, or push with + dotnet nuget push - the ID you push first becomes yours. +

+ } + else + { + @foreach (var group in Model.Groups) + { +
+ @if (Model.ShowRepositoryNames) + { +

Repository: @group.Repository.Name

+ } + + + + + + @foreach (var package in group.Packages) + { + var isNpm = group.Repository.Format == BaGet.Core.RepositoryFormat.Npm; + + @if (isNpm) + { + + + + + + } + else if (group.Repository.Format == BaGet.Core.RepositoryFormat.Maven) + { + var mavenPath = string.Join("/", (package.Id ?? string.Empty).Split(':').Select(Uri.EscapeDataString)); + + + + + + } + else + { + + + + + + } + + } + +
PackageLatest versionVersionsDownloads
@package.Id + @if (package.LatestVersion == null) + { + None + } + else + { + @package.LatestVersion + } + @package.VersionCount@package.Downloads.ToString("N0") + Manage · + Upload new version + @package.Id + @if (package.LatestVersion == null) + { + None + } + else + { + @package.LatestVersion + } + @package.VersionCount@package.Downloads.ToString("N0") + Manage · + Upload new version + @package.Id + @if (package.LatestVersion == null) + { + None + } + else + { + @package.LatestVersion + @(package.LatestVersionIsListed ? "" : " (unlisted)") + } + @package.VersionCount@package.Downloads.ToString("N0") + Manage · + Upload new version +
+
+ } + } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AccountSettings/ApiKeys.cshtml b/src/BaGet.Identity.FrontEnd/Views/AccountSettings/ApiKeys.cshtml new file mode 100644 index 000000000..3e0b91038 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AccountSettings/ApiKeys.cshtml @@ -0,0 +1,92 @@ +@model BaGet.Identity.Application.Models.Account.ApiKeysViewModel +@{ + ViewData["Title"] = "API keys"; +} + +
+

API keys

+ + + @if (Model.CreatedKey != null) + { + + } + +

Your keys

+ @if (Model.Keys.Count == 0) + { +

You have no API keys.

+ } + else + { + + + + + + @foreach (var key in Model.Keys) + { + + + + + + + + + } + +
DescriptionCanRepositoriesCreatedExpires
@key.Description@ApiKeysViewModel.Describe(key)@Model.DescribeRepositories(key)@key.Created.ToString("yyyy-MM-dd")@(key.Expires?.ToString("yyyy-MM-dd") ?? "never") +
+ +
+
+ } + +

Create a key

+
+
+
+ + +
+
+ + @foreach (var scope in Model.AllScopes) + { +
+ +
+ } + @if (Model.AllScopes.Contains(BaGet.Core.ApiKeyScopes.Admin)) + { + admin:api lets the key call the administration REST API (/api/v1, see REST API). Keep it short-lived and out of build logs. + } +
+
+ + +
+ @if (Model.Repositories.Count > 0) + { +
+ + Tick the repositories the key may be used in. None ticked: every repository. + @foreach (var repository in Model.Repositories) + { +
+ +
+ } +
+ } +
+ + +
+ +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AccountSettings/Settings.cshtml b/src/BaGet.Identity.FrontEnd/Views/AccountSettings/Settings.cshtml new file mode 100644 index 000000000..6fe2b67e3 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AccountSettings/Settings.cshtml @@ -0,0 +1,164 @@ +@model BaGet.Identity.Application.Models.Settings.SettingsViewModel +@{ + ViewData["Title"] = "Account settings"; +} + +
+

Account settings

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + @if (Model.Blockers != null) + { + @if (Model.Blockers.LastOwnerPackageIds.Count > 0) + { + + } + @if (Model.Blockers.LastAdministrator) + { + + } + @if (Model.Blockers.Organizations.Count > 0) + { + + } + } + +

Email

+

+ @(string.IsNullOrEmpty(Model.Email) ? "No email address." : Model.Email) + @if (!string.IsNullOrEmpty(Model.Email) && Model.CanSendEmail) + { + @(Model.EmailConfirmed ? "confirmed" : "unconfirmed") + } +

+
+
+ + + @if (Model.CanSendEmail) + { +

We send a link to the new address; it changes when you follow it.

+ } +
+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + +

Password

+
+ @if (Model.HasPassword) + { +
+ + +
+ } +
+ + +
+
+ + +
+ @if (!Model.HasPassword) + { + + } + + + + @if (Model.ExternalLogins.Count > 0) + { +

Sign-in providers

+

Link more than one provider to sign in with either. Linking and unlinking ask for your password.

+ + + @foreach (var login in Model.ExternalLogins) + { + + + + + + } + +
@login.DisplayName@(login.Linked ? "Linked" : "Not linked") +
+ + @if (Model.HasPassword) + { + + } + else + { + + } + + +
+ } + +

Two-factor authentication

+

Manage two-factor authentication

+ +

Delete account

+

+ This removes your account, your API keys and your organization memberships, and cannot be undone. + You cannot delete it while you are the only owner of a package. +

+
+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AccountSettings/TwoFactor.cshtml b/src/BaGet.Identity.FrontEnd/Views/AccountSettings/TwoFactor.cshtml new file mode 100644 index 000000000..67ccf367f --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AccountSettings/TwoFactor.cshtml @@ -0,0 +1,84 @@ +@model BaGet.Identity.Application.Models.Account.TwoFactorViewModel +@{ + ViewData["Title"] = "Two-factor authentication"; +} + +
+

Two-factor authentication

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + + @if (Model.RecoveryCodes.Count > 0) + { +

Recovery codes

+
    + @foreach (var recoveryCode in Model.RecoveryCodes) + { +
  • @recoveryCode
  • + } +
+ } + + @if (Model.TwoFactorEnabled) + { +

Two-factor authentication is on. You have @Model.RecoveryCodesLeft recovery codes left.

+ +

Turn off

+
+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + +

Reset the authenticator

+

Use this if you lost the device. It turns two-factor authentication off and gives you a new key to set up again.

+
+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + } + else + { +

Protect your account with a code from an authenticator app.

+
    +
  1. Scan this code with an authenticator app, or type the key into it.
  2. +
  3. Enter the 6-digit code the app shows.
  4. +
+
@Html.Raw(Model.QrCodeSvg)
+

Key: @Model.SharedKey

+
+
+ + +
+ +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminAudit/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminAudit/Index.cshtml new file mode 100644 index 000000000..4a714c7cd --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminAudit/Index.cshtml @@ -0,0 +1,64 @@ +@model BaGet.Identity.Application.Models.Access.AuditViewModel +@{ + ViewData["Title"] = "Access audit"; +} + +
+

Access audit

+ + +

+ Every change to groups, memberships, permission targets, grants, projects, a repository's project and its anonymous-read + switch, newest first (at most @AdminAuditUseCase.PageSize). Times are UTC. +

+ + @if (Model.FilterError != null) + { + + } + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ + @if (Model.Entries.Count == 0) + { +

No entries.

+ } + else + { + + + + + + @foreach (var entry in Model.Entries) + { + + + + + + + + } + +
When (UTC)ActorActionSubjectDetails
@entry.Created.ToString("yyyy-MM-dd HH:mm:ss")@(entry.Actor ?? "server")@entry.Action@entry.Subject@entry.Details
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminGroups/Detail.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminGroups/Detail.cshtml new file mode 100644 index 000000000..b8d418b80 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminGroups/Detail.cshtml @@ -0,0 +1,132 @@ +@using BaGet.Frontend.Mvc.Screens +@model BaGet.Identity.Application.Models.Access.GroupDetailViewModel +@{ + ViewData["Title"] = "Group " + Model.Name; + var group = Model.Group?.Group; +} + +
+

Group @group?.Name

+ + +

Back to groups

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

@group?.Description

+ + @if (group?.IsBuiltIn == true) + { + + } + else + { +
+

Members (@Model.Group?.Members.Count)

+

Adding and removing members asks for your password again.

+
+ + + + @foreach (var member in Model.Group!.Members) + { + + + + + } + +
User
@member.UserName
+ @if (Model.Group.Members.Count == 0) + { +

The group has no members.

+ } + + + +

Add members

+
+ + +
+ @if (!string.IsNullOrWhiteSpace(Model.Q)) + { + if (Model.Found.Count == 0) + { +

No user matches (or all of them are members already).

+ } + else + { +
+ + + @foreach (var user in Model.Found) + { + + + + + } + +
@user.UserName
+ + + } + } +
+ +
+

Rename

+
+ + +
+
+ } + +
+

Grants

+ @if (Model.Group?.Grants.Count == 0) + { +

No permission target names this group.

+ } + else + { + + + + @foreach (var grant in Model.Group!.Grants) + { + + + + + } + +
Permission targetActions
@grant.Target@AccessSupport.Words(grant.Actions)
+ } +
+ + @if (group?.IsBuiltIn == false) + { +
+

Delete

+

Removes the group, its members and every grant and project role that names it.

+
+ + + +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminGroups/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminGroups/Index.cshtml new file mode 100644 index 000000000..6b1e119f5 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminGroups/Index.cshtml @@ -0,0 +1,59 @@ +@model BaGet.Identity.Application.Models.Access.GroupsViewModel +@{ + ViewData["Title"] = "Groups"; +} + +
+

Groups

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

+ A group is a set of users. Permission targets and + project roles grant access to groups instead of to each user. +

+ + + + + + + @foreach (var group in Model.Groups) + { + + + + + + } + +
NameDescriptionMembers
+ @group.Name + @if (group.IsBuiltIn) + { + Built-in + } + @group.Description@(group.IsBuiltIn ? "implicit" : group.MemberCount.ToString())
+ +

New group

+
+
+ + +
+
+ + +
+ +

Letters, digits, spaces, -, . and _, up to @BaGet.Core.AccessNames.MaxLength characters.

+
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Abuse.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Abuse.cshtml new file mode 100644 index 000000000..4accb52df --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Abuse.cshtml @@ -0,0 +1,73 @@ +@model BaGet.Identity.Application.Models.Operations.AbuseViewModel +@{ + ViewData["Title"] = "Abuse reports"; +} + +
+

Abuse reports

+ + + @if (Model.Message != null) + { + + } + + @if (!Model.IsSupported) + { + + } + else + { +

+ @if (Model.All) + { + Showing all reports. Show unresolved only + } + else + { + Showing unresolved reports. Show all + } +

+ + @if (!Model.Items.Any()) + { +

No reports.

+ } + else + { + + + + + + @foreach (var report in Model.Items) + { + + + + + + + + + + } + +
PackageRepositoryReasonDetailsReporterReported
+ @if (report.PackageId != null) + { + @report.PackageId @report.PackageVersion + } + else + { + @report.PackageId @report.PackageVersion + } + @report.Repository@report.Reason@report.Details@report.ReporterEmail@report.Created.ToString("u")@(report.IsResolved ? " (resolved " + report.Resolved!.Value.ToString("u") + ")" : "") +
+ + +
+
+ } + } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOperations/AccessUnavailable.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/AccessUnavailable.cshtml new file mode 100644 index 000000000..5e03c2f9a --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/AccessUnavailable.cshtml @@ -0,0 +1,17 @@ +@{ + ViewData["Title"] = "Access control unavailable"; +} + +
+

Access control is not available

+ + + +

+ Until then the server behaves as it did before the access model: everyone may read, any caller with a valid + API key or session may write, and package ownership decides which existing package IDs they may change. +

+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Cluster.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Cluster.cshtml new file mode 100644 index 000000000..05e10a948 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Cluster.cshtml @@ -0,0 +1,102 @@ +@model BaGet.Identity.Application.Models.Settings.ClusterViewModel +@{ + ViewData["Title"] = "Cluster"; +} + +
+

Cluster

+ + + @if (!Model.Status.Enabled) + { + + } + else + { +

+ This node is @Model.Status.ThisNode; the nodes share @Model.Status.Backend + (@(Model.Status.BackendReachable ? "reachable" : "not reachable")). + A node is listed while its heartbeat is recent; a job lease belongs to the node named and expires if that node stops. +

+ } + + @if (Model.Status.GateReason != null) + { + + } + +

Nodes

+ + + + + + @foreach (var node in Model.Status.Nodes) + { + + + + + + + + + } + +
NodeVersionStarted (UTC)Last heartbeat (UTC)HealthRead-only
@node.Id@(node.Id == Model.Status.ThisNode ? " (this node)" : "")@node.Version@node.Started.ToString("u")@node.Seen.ToString("u") + @if (node.Ready) + { + ready + } + else + { + not ready @node.Problem + } + @(node.GateClosed ? "yes" : "no")
+ +

Job leases

+ @if (Model.Status.Leases.Count == 0) + { +

No job is running.

+ } + else + { + + + + + + @foreach (var lease in Model.Status.Leases) + { + + + + + + } + +
JobHeld bySince (UTC)
@lease.Job@lease.Node@lease.Since.ToString("u")
+ } + +

This node's health checks

+

The same checks as /health/ready, checked @Model.Status.Readiness.CheckedAt.ToString("u"). Check again

+ + + + + + @foreach (var probe in Model.Status.Readiness.Probes) + { + + + + + + } + +
CheckResultDetail
@probe.Name@(probe.Healthy ? "healthy" : "unhealthy")@probe.Detail@(probe.Informational ? " (reported only: does not affect readiness)" : "")
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Formats.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Formats.cshtml new file mode 100644 index 000000000..779f926f0 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Formats.cshtml @@ -0,0 +1,33 @@ +@model BaGet.Identity.Application.Models.Repositories.FormatsViewModel +@{ + ViewData["Title"] = "Package formats"; +} + +
+

Package formats

+ + +

+ The formats this server can host. A repository has one format; its clients are configured with the feed address below. + Repositories are created on the Repositories page. +

+ + + + + + + @foreach (var row in Model.Rows) + { + + + + + + + + + } + +
FormatFeed addressRepository kindsStorage foldersCapabilitiesRepositories
@row.Module.DisplayName@(row.Module.RoutePrefix.Length == 0 ? "/" : "/" + row.Module.RoutePrefix + "/") (@row.Module.FeedPath)@string.Join(", ", row.Module.CreatableKinds.Concat(row.Module.SupportsVirtual ? new[] { BaGet.Core.RepositoryKind.Virtual } : System.Array.Empty()))@string.Join(", ", row.Module.StorageFolders)@(row.Capabilities.Count == 0 ? "-" : string.Join(", ", row.Capabilities))@row.Repositories
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Index.cshtml new file mode 100644 index 000000000..7fbddc91e --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Index.cshtml @@ -0,0 +1,78 @@ +@model BaGet.Identity.Application.Models.Operations.OperationsViewModel +@{ + ViewData["Title"] = "Operations"; +} + +
+

Operations

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

Maintenance jobs run in the background, one at a time per operation and repository. Their status is kept in memory until the server restarts. They are refused while the server is read-only for maintenance. An operation that deletes data (the Docker garbage collection) asks for your password again; its dry run reports what it would remove and asks for nothing.

+ + @if (!Model.Rows.Any()) + { + + } + else + { + + + + + + @foreach (var row in Model.Rows) + { + var running = row.Status?.State == BaGet.Core.AdminJobState.Running; + + + + + + + } + +
OperationRepositoryStatus
@row.Operation.Title
@row.Operation.Description
@row.Repository.Name + @if (row.Status == null) + { + Never run since the last start + } + else + { + @row.Status.State + started @row.Status.Started.ToString("u")@(row.Status.Actor != null ? " by " + row.Status.Actor : "") + @if (row.Status.Finished != null) + { + , finished @row.Status.Finished.Value.ToString("u") + } + @if (!string.IsNullOrEmpty(row.Status.Message)) + { +
@row.Status.Message + } + } +
+
+ + + @if (row.Operation.RequiresConfirmation) + { + + } + + +
+ } +
+ +@if (Model.AnyRunning) +{ + +} diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Validation.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Validation.cshtml new file mode 100644 index 000000000..89937b958 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOperations/Validation.cshtml @@ -0,0 +1,87 @@ +@model BaGet.Identity.Application.Models.Operations.ValidationViewModel +@{ + ViewData["Title"] = "Validation"; +} + +
+

Validation queue

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + + @if (!Model.IsSupported) + { + + } + else if (!Model.Submissions.Any()) + { +

No submission is pending or quarantined.

+ } + else + { +

+ A quarantined package is staged but not served. Release indexes it although validation failed (logged and audited); + Reject deletes it (also a submission stuck pending); Retry validates it again. Release and reject need your password. +

+ +
+
+ @if (Model.HasPassword) + { + + + } + else + { + + } +
+ + + + + + + @foreach (var submission in Model.Submissions) + { + + + + + + + + + } + +
PackageRepositoryStateSubmittedWhy
@submission.PackageId @submission.PackageVersion@submission.Repository@submission.State@submission.Created.ToString("u") + @foreach (var message in submission.FailureMessages) + { +
@message
+ } +
+ + @if (submission.State == BaGet.Core.ValidationSubmissionState.Quarantined) + { + + + } + else + { + @* A submission whose validation keeps failing stays pending: it can be rejected too. *@ + + } +
+
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOrganizations/Detail.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOrganizations/Detail.cshtml new file mode 100644 index 000000000..c547b7878 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOrganizations/Detail.cshtml @@ -0,0 +1,97 @@ +@model BaGet.Identity.Application.Models.Organizations.OrganizationDetailViewModel +@{ + ViewData["Title"] = Model.Organization?.Name ?? "Organization"; +} + +
+

@Model.Organization?.Name

+ + +

Back to organizations

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

Created @Model.Organization?.Created.ToString("yyyy-MM-dd"). It owns @Model.OwnedPackageIds package ID(s) across all repositories.

+

Every action on this page asks for your password again.

+ +
+

Members

+
+ + + + + + @foreach (var member in Model.Members) + { + + + + + + } + +
UserRole
@member.UserName@(member.IsAdmin ? "Administrator" : "Member") + @if (member.IsAdmin) + { + + } + else + { + + } + +
+ @if (Model.Members.Count == 0) + { +

The organization has no members.

+ } + + + +
+

Add a member

+ + + + + +
+ +
+

Rename

+

+ Package ownership follows in every repository, in one step. The name must not belong to a user or another organization. +

+
+ + + + +
+ +
+

Delete

+ @if (Model.OwnedPackageIds > 0) + { +

It owns packages, so it cannot be deleted. Remove it as an owner of those packages first.

+ } + else + { +

Removes the organization and its memberships.

+
+ + + + } +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminOrganizations/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminOrganizations/Index.cshtml new file mode 100644 index 000000000..7e8317fd7 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminOrganizations/Index.cshtml @@ -0,0 +1,39 @@ +@model BaGet.Identity.Application.Models.Organizations.AdminOrganizationsViewModel +@{ + ViewData["Title"] = "Organizations"; +} + +
+

Organizations

+ + +

+ Every organization on the server. Users create them from their own Organizations page; here an administrator + renames them, manages their members and deletes those that own no package. +

+ + @if (Model.Organizations.Count == 0) + { +

There are no organizations.

+ } + else + { + + + + + + @foreach (var organization in Model.Organizations) + { + + + + + + + + } + +
NameMembersAdministratorsPackage IDsCreated
@organization.Name@organization.Members@organization.Administrators@organization.PackageIds@organization.Created.ToString("yyyy-MM-dd")
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminPackages/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminPackages/Index.cshtml new file mode 100644 index 000000000..07a4d6c8f --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminPackages/Index.cshtml @@ -0,0 +1,55 @@ +@model BaGet.Identity.Application.Models.Packages.AdminPackagesViewModel +@{ + ViewData["Title"] = "Packages without owners"; +} + +
+

Packages without owners

+ + +

+ These IDs (per repository) predate accounts, or lost their only owner when an account was deleted. Only + administrators and the global API key can change them. +

+ + @if (Model.Packages.Count == 0) + { +

Every package has an owner.

+ } + else + { + + + @if (Model.ShowRepository) {} + + + @foreach (var row in Model.Packages) + { + + + @if (Model.ShowRepository) {} + + + + + + } + +
PackageRepositoryLatest versionVersionsDownloads
@row.Package.Id@row.RepositoryName@(row.Package.LatestVersion ?? "None")@row.Package.VersionCount@row.Package.Downloads.ToString("N0")Manage
+ } + + @if (Model.PageCount > 1) + { +
    + @if (Model.PageNumber > 1) + { + + } +
  • Page @Model.PageNumber of @Model.PageCount
  • + @if (Model.PageNumber < Model.PageCount) + { + + } +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminPermissions/Detail.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminPermissions/Detail.cshtml new file mode 100644 index 000000000..0f6c698f0 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminPermissions/Detail.cshtml @@ -0,0 +1,113 @@ +@using BaGet.Frontend.Mvc.Screens +@model BaGet.Identity.Application.Models.Access.PermissionDetailViewModel +@{ + ViewData["Title"] = "Permission target " + Model.Name; + var target = Model.Target?.Target; +} + +
+

Permission target @target?.Name

+ + +

+ @if (Model.IsServerAdministrator) + { + Back to permission targets + } + else if (target?.ProjectName != null) + { + Back to project @target.ProjectName + } +

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + + @if (target?.ProjectName != null) + { +

Project target of @target.ProjectName: it applies only to that project's repositories.

+ } +

Saving patterns, changing grants and deleting the target ask for your password again. Package ownership still applies inside Deploy, Delete, Annotate and Manage.

+ +
+

Patterns

+
+ + + + +
+ +
+

Grants

+ @if (Model.Target?.Grants.Count == 0) + { +

Nobody holds anything through this target yet.

+ } + else + { +
+ + + @foreach (var action in AccessSupport.AllActions) { } + + + @foreach (var grant in Model.Target!.Grants) + { + + + @foreach (var action in AccessSupport.AllActions) + { + + } + + + } + +
Principal@action
@grant.Principal@((grant.Actions & action) == action ? "yes" : "") + Edit + +
+ + + } + +

Set a grant

+

Replaces the actions the principal holds through this target; ticking none removes the grant.

+
+
+ + +
+
+ @foreach (var action in AccessSupport.AllActions) + { + + } +
+ + + +
+ +
+

Delete

+

Removes the target and its grants@(target?.IsBuiltIn == true ? ". It is a built-in default: Restore built-in groups and targets on the permission targets page brings it back." : ".")

+
+ + + +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminPermissions/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminPermissions/Index.cshtml new file mode 100644 index 000000000..e9d76f60d --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminPermissions/Index.cshtml @@ -0,0 +1,90 @@ +@using BaGet.Frontend.Mvc.Screens +@model BaGet.Identity.Application.Models.Access.PermissionsViewModel +@{ + ViewData["Title"] = "Permission targets"; +} + +
+

Permission targets

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

+ A target says which repositories and package IDs its grants apply to. A grant gives a user, a + group or an organization some of Read, Annotate, Deploy, Delete and Manage. + Package ownership still applies inside Deploy, Delete, Annotate and Manage. Server administrators hold every action. +

+ + + + + + + @foreach (var target in Model.Targets) + { + + + + + + + + } + +
NameRepositoriesPackagesProjectGrants
+ @target.Name + @if (target.IsBuiltIn) + { + Built-in + } + @AccessSupport.Join(target.RepositoryPatterns) + @(BaGet.Core.AccessPatterns.DescribeScope(target.IncludePatterns, target.ExcludePatterns) ?? "*") + + @if (target.ProjectName != null) + { + @target.ProjectName + } + @target.GrantCount
+ +

New permission target

+
+
+ + +
+ + @if (Model.Projects.Count > 0) + { +
+ + + A project target applies only to the project's repositories, and the project's administrators manage its grants. +
+ } + + + +

Defaults

+

+ The upgrade created Anyone reads every repository and Authenticated users deploy, which keep the behaviour of + a server without an access model. If you deleted them, this brings back the missing ones. +

+
+ + + +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminProjects/Detail.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminProjects/Detail.cshtml new file mode 100644 index 000000000..f170af928 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminProjects/Detail.cshtml @@ -0,0 +1,178 @@ +@using BaGet.Frontend.Mvc.Screens +@model BaGet.Identity.Application.Models.Access.ProjectDetailViewModel +@{ + ViewData["Title"] = "Project " + Model.Name; + var project = Model.Project?.Project; +} + +
+

Project @project?.Name

+ + +

Back to projects

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

@project?.DisplayName

+

Changing members, repositories and deleting the project ask for your password again.

+ +
+

Repositories

+ @if (Model.Project?.Repositories.Count == 0) + { +

The project has no repositories.

+ } + else + { +
+ + + @foreach (var repository in Model.Project!.Repositories) + { + + + + + } + +
@repository + @if (Model.IsServerAdministrator) + { + + } +
+ @if (Model.IsServerAdministrator) + { + + } + + } + + @if (Model.IsServerAdministrator && Model.Assignable.Count > 0) + { +
+ + + + A repository is in at most one project: adding it here takes it out of another. + + } +
+ + @if (Model.IsServerAdministrator) + { +
+

Scanning policy

+

The vulnerability scanning policy of the project (warn, block download, block deploy) applies to its repositories that have none of their own. Edit the scanning policy.

+
+ } + +
+

Members

+

Viewer: Read. Developer: Read, Annotate, Deploy. Admin: every action, and manages this project's members and permission targets.

+ @if (Model.Project?.Members.Count == 0) + { +

The project has no members.

+ } + else + { +
+ + + + @foreach (var member in Model.Project!.Members) + { + + + + + + } + +
MemberRole
@member.Principal@member.Role + +
+ + + } + +

Set a member's role

+
+
+ + + +
+ + + +
+ +
+

Permission targets

+ @if (Model.Project?.Targets.Count == 0) + { +

The project has no permission targets of its own.

+ } + else + { + + + + @foreach (var target in Model.Project!.Targets) + { + + + + + + } + +
NameRepositoriesGrants
@target.Name@AccessSupport.Join(target.RepositoryPatterns)@target.GrantCount
+ } + +

New target

+

A project target applies only to this project's repositories, whatever its repository patterns say.

+
+
+ + +
+ + + +
+ + @if (Model.IsServerAdministrator) + { +
+

Delete

+

Removes the project, its members and its permission targets with their grants. The repositories stay.

+
+ + + +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminProjects/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminProjects/Index.cshtml new file mode 100644 index 000000000..09e8fdaa7 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminProjects/Index.cshtml @@ -0,0 +1,56 @@ +@model BaGet.Identity.Application.Models.Access.ProjectsViewModel +@{ + ViewData["Title"] = "Projects"; +} + +
+

Projects

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

+ A project groups repositories and gives its members a role on all of them: Viewer (Read), Developer (Read, Annotate, + Deploy) or Admin (every action, and the project's members and permission targets). +

+ + + + + + + @foreach (var project in Model.Projects) + { + + + + + + + } + +
NameDisplay nameRepositoriesMembers
@project.Name@project.DisplayName@project.RepositoryCount@project.MemberCount
+ + @if (Model.IsServerAdministrator) + { +

New project

+
+
+ + +
+
+ + +
+ +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminReplication/Config.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminReplication/Config.cshtml new file mode 100644 index 000000000..b31393ec8 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminReplication/Config.cshtml @@ -0,0 +1,127 @@ +@using BaGet.Frontend.Controllers.Base +@model BaGet.Identity.Application.Models.Policies.ReplicationConfigViewModel +@{ + var config = Model.View!.Config; + ViewData["Title"] = "Replication " + config.Name; + var running = Model.Running; +} + +
+

@config.Name

+ +

All replications

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + @if (Model.Test != null) + { + + } + +

+ @ReplicationControllerBase.Describe(config): + repository @(Model.View.Repository ?? "(gone)") + @(config.Direction == BaGet.Core.ReplicationDirection.Push ? "to" : "from") + @config.PeerUrl repository @config.PeerRepository. + @(config.Enabled ? "Enabled." : "Disabled.") + @(Model.View.HasApiKey ? "A peer API key is stored." : "No peer API key is stored.") + @if (Model.LocalItems is int items) { The local repository holds @items item(s). } +

+ +

Run

+
+
+
+ + + Copies what the target lacks. Skips what it holds. + +
+
+ @if (Model.Resumable != null) + { +
+ + + Run @Model.Resumable.Key ended @Model.Resumable.Status.ToString().ToLowerInvariant(); a new run continues from what is in place. + + } +
+
+
+ + The run ends as interrupted and can be resumed. +
+
+
+ @if (Model.Job?.Refusal != null) + { + + } + +

Log

+ + + + + + @foreach (var run in Model.Runs) + { + + + + + + + + + + + + + + @if (run.Error != null || run.Detail != null) + { + + + + + } + } + +
RunStartedTriggerStatusExaminedCopiedSkippedDeletedConflictsFailedBytes
@run.Key@(run.ResumedFrom is int from ? " (continues " + from + ")" : "")@run.Started.ToString("u")@(run.Finished is DateTime done ? " to " + done.ToString("u") : "")@run.Trigger@(run.Actor != null ? " by " + run.Actor : "")@run.Status@run.Examined@run.Transferred@run.Skipped@run.Deleted@run.Conflicts@run.Failures@BaGet.Core.RetentionReport.FormatBytes(run.Bytes)
+ @if (run.Error != null) {
@run.Error
} + @if (run.Detail != null) {
@run.Detail
} +
+ @if (!Model.Runs.Any()) + { +

It has not run yet.

+ } + +

Settings

+
+ + + + + Test connection uses the values typed above (a stored key only while the peer address is unchanged) and saves nothing. + + +

Delete the replication

+
+ + + Its log and its record of what it copied go; what it copied stays where it is. + +
+ +@if (running) +{ + +} diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminReplication/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminReplication/Index.cshtml new file mode 100644 index 000000000..c4b56351d --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminReplication/Index.cshtml @@ -0,0 +1,68 @@ +@using BaGet.Frontend.Controllers.Base +@model BaGet.Identity.Application.Models.Policies.ReplicationViewModel +@{ + ViewData["Title"] = "Replication"; +} + +
+

Replication

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

+ A replication copies a local repository to (push) or from (pull) a repository of another BaGet + server, in the same format, through that format's own protocol. It runs when you start it, on a schedule, and (push) after a deploy. + What the target already holds is skipped, so an interrupted run is continued by running it again. The peer API key + (an administrator's key with the admin:api scope) is stored protected and never shown again. +

+ + + + + + + @foreach (var view in Model.Replications) + { + var config = view.Config; + + + + + + + + } + +
ReplicationRepositoryPeerModeLast run
+ @config.Name + @if (!config.Enabled) { disabled } + @(view.Repository ?? "(gone)")@(view.Format is { } format ? " (" + format + ")" : "")@config.PeerUrl repository @config.PeerRepository@ReplicationControllerBase.Describe(config) + @if (config.LastRun is DateTime last) + { + @last.ToString("u")
@config.LastResult + } + else + { + never + } +
+ @if (!Model.Replications.Any()) + { +

There is no replication yet.

+ } + +

New replication

+
+ + + + +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Delete.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Delete.cshtml new file mode 100644 index 000000000..ddf2bf3a7 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Delete.cshtml @@ -0,0 +1,53 @@ +@model BaGet.Identity.Application.Models.Repositories.RepositoryDeleteViewModel +@{ + ViewData["Title"] = "Delete " + Model.Name; +} + +
+

Delete @Model.Name

+ + + @if (Model.Error != null) + { + + } + + @if (Model.Repository?.IsDefault == true) + { + + } + else if (Model.ReferencedBy.Count > 0) + { + + } + else if (Model.Repository?.PackageCount > 0) + { + + } + else + { +

@Model.Name holds no packages. Deleting it removes the repository, its feed address, its history (catalog entries, owners, validations, abuse reports, API keys limited to it alone) and its files in storage (symbols, catalog files); this cannot be undone.

+
+ + Cancel +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Edit.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Edit.cshtml new file mode 100644 index 000000000..22fca1744 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Edit.cshtml @@ -0,0 +1,422 @@ +@using BaGet.Frontend.Mvc.Screens +@model BaGet.Identity.Application.Models.Repositories.RepositoryEditViewModel +@{ + ViewData["Title"] = "Repository " + Model.Name; +} + +
+

Repository @Model.Name

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +
+
Type
+
@Model.Repository?.Format / @Model.Repository?.Kind
+
Feed
+
+ @Model.FeedUrl + +
+ @if (Model.Repository?.Kind == BaGet.Core.RepositoryKind.Virtual) + { +
Members
+
@(Model.VirtualDetail?.Members.Count ?? 0) (stores no packages of its own)
+ } + else + { +
@(Model.Repository?.Kind == BaGet.Core.RepositoryKind.Remote ? "Cached packages" : "Packages")
+
@Model.Repository?.PackageCount
+ } +
+ + @if (Model.MirrorActive) + { +

+ Mirror:Enabled is on: this repository fetches packages it does not hold from the upstream of the remote repository + @BaGet.Core.Repository.MirrorName + (credentials, cache periods and offline mode are set there) and stores them here. In effect default is a + virtual repository of two members that keeps its URL: its own packages first, then that remote repository, whose + answers are stored in default itself. To put the mirror in a virtual repository of your own instead, + add @BaGet.Core.Repository.MirrorName + as a member there (that cache is the mirror repository's own). +

+ } + + @if (Model.ReferencedBy.Count > 0) + { +

+ Member of the virtual repositor@(Model.ReferencedBy.Count == 1 ? "y" : "ies"): + @foreach (var referenced in Model.ReferencedBy) + { + @referenced@(referenced == Model.ReferencedBy[^1] ? "" : ", ") + } + It cannot be deleted until it is removed from @(Model.ReferencedBy.Count == 1 ? "it" : "them"). +

+ } + + @if (Model.RemoteDetail != null && Model.RemoteDetail.HasPassword && Model.Repository!.AnonymousRead) + { + + } + +
+
+ + +
+ + @if (Model.RemoteDetail != null) + { +
+

Upstream

+ @if (Model.Remote.Url != null && Model.Remote.Username != null && Model.Remote.Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) + { + + } + + + @if (Model.TestResult != null) + { +
+ @Model.TestResult.Message + (@Model.TestResult.ElapsedMilliseconds ms) +
+ } + + Asks the upstream with the values above, saved or not, and saves nothing. Needs your password below, like saving does. +
+ } + + @if (Model.RemoteDetail != null) + { + + } + + Cancel + + + @if (Model.MavenSettings != null) + { +

Maven settings

+
+
+ + + A deploy the policy refuses is answered 409. A stricter policy deletes nothing already stored. +
+
+ + + When yes, a release file that exists may be replaced by a caller who also holds the Delete permission. +
+
+ + + 0 keeps every build. Otherwise older builds of a snapshot version are deleted when a newer one arrives; an artifact's manage page cleans up on demand. +
+ +
+ } + + @if (Model.VirtualDetail != null) + { + var virtualDetail = Model.VirtualDetail; +
+

Members

+

+ A request is answered by the first member, in this order, that has the package version; the version lists, the + registration index (npm: the packument, whose dist-tags follow the member order; Maven: maven-metadata.xml, + whose latest and release follow the member order; Docker: a tag or digest is the first member's, the tag list is the + members' merged), search and autocomplete merge the members (a package in several members is one result). + Only the members the caller may read are asked. Uploads go to the deploy repository and need Deploy there. + The catalog is not served by a virtual repository. +

+ + @if (virtualDetail.Members.Count == 0) + { +

No members yet: the repository is empty. Add one below.

+ } + else + { + + + + @for (var i = 0; i < virtualDetail.Members.Count; i++) + { + var member = virtualDetail.Members[i]; + + + + + + + + } + +
#MemberTypeDeploy
@(i + 1) + @if (member.Exists) + { + @member.Name + } + else + { + @member.Name + (no longer exists; it is skipped) + } + @(member.Repository?.Kind.ToString() ?? "-")@(virtualDetail.DeployRepository == member.Name ? "deploy repository" : "") +
+ + + +
+
+ + +
+
+ } + + @if (Model.MemberCandidates.Count > 0) + { +
+
+ + +
+ +
+ } + else + { +

Every other @Model.Repository?.Format repository is already a member (or would make this one contain itself).

+ } + +

Deploy repository

+
+
+ + +
+ +
+

+ @if (virtualDetail.DeployTarget != null) + { + A push to this repository is stored in @virtualDetail.DeployTarget.Name; the pusher needs Deploy there. + } + else + { + No uploads: the repository has no local deploy repository. A remote repository cannot be one. + } +

+ +

Where would a package come from?

+
+
+ + +
+
+ + +
+ +
+

Asks each member in order, without fetching or storing anything. A remote member that does not hold it yet is asked whether its upstream has it, unless an earlier member answers.

+ @if (Model.Preview != null) + { + + + + @for (var i = 0; i < Model.Preview.Steps.Count; i++) + { + var step = Model.Preview.Steps[i]; + + + + + + } + +
#MemberResult
@(i + 1)@step.Member.Name (@step.Member.Kind) + @(step.Outcome switch + { + BaGet.Core.ResolutionOutcome.Stored => "stored here", + BaGet.Core.ResolutionOutcome.WouldFetch => "not stored yet; its upstream has it and it would be fetched on first request", + BaGet.Core.ResolutionOutcome.Unavailable => "its upstream could not be asked", + BaGet.Core.ResolutionOutcome.NotAsked => "not asked: an earlier member answers", + BaGet.Core.ResolutionOutcome.Offline => "not stored; its upstream is in offline mode, so it is not asked", + _ => "not found", + }) + @if (Model.Preview.Answers?.Key == step.Member.Key) + { + - answers + } +
+

+ @if (Model.Preview.Answers != null) + { + @Model.Preview.PackageId @Model.Preview.Version comes from @Model.Preview.Answers.Name. + } + else + { + No member has @Model.Preview.PackageId @Model.Preview.Version. + } +

+ } +
+ } + + @if (Model.RemoteDetail != null && Model.Cache != null) + { + var status = Model.Cache.Status; +
+

Cache

+ + + @if (Model.Repository?.Format == BaGet.Core.RepositoryFormat.Docker) + { + + } + else + { + + } + + + + + + + +
Stored images@Model.Cache.PackageCount manifest(s) of @Model.Cache.PackageIdCount image(s), @Model.Cache.StoredBytes.ToString("N0") bytes of layers
@(Model.Repository?.Format == BaGet.Core.RepositoryFormat.Maven ? "Stored artifacts" : "Stored packages")@Model.Cache.PackageCount version(s) of @Model.Cache.PackageIdCount @(Model.Repository?.Format == BaGet.Core.RepositoryFormat.Maven ? "artifact(s)" : "package(s)")
Remembered answers@status.MetadataEntries metadata, @status.NegativeEntries not found (this node, since it started)
Cache hits / upstream requests@status.Hits / @status.Misses (not found from cache: @status.NegativeHits, expired served while the upstream was down: @status.StaleServed)
Upstream + @if (Model.RemoteDetail.Settings.Offline) + { + Offline mode: never contacted. + } + else if (status.FailingSinceUtc != null) + { + Failing since @status.FailingSinceUtc.Value.ToString("u"): @status.LastError + } + else if (status.LastSuccessUtc != null) + { + Answered at @status.LastSuccessUtc.Value.ToString("u"). + } + else + { + Not contacted yet. + } + @if (status.Failures > 0) + { + @status.Failures failed attempt(s) so far. + } +
+

+ Browse the cached packages +

+ +
+ + + Deletes the stored packages and forgets the remembered answers. + + +
+
+ + +
+
+ + +
+ + + +
+ } + + @if (Model.Access != null) + { +
+

Effective access

+ @if (!Model.Access.ModelAvailable) + { +

+ The configured database has no access model: everyone reads and any caller with valid credentials writes, subject + to package ownership. +

+ } + else + { +

+ Who holds each action here, from the permission targets that match this + repository and its project's roles. Server administrators hold every action. Package ownership still applies inside + Deploy, Delete, Annotate and Manage. Anonymous read is @(Model.Access.AnonymousRead ? "on" : "off")@(Model.Access.AnonymousRead ? "" : ": Everyone's Read does not apply here"). + @if (Model.Access.Project != null) + { + Project: @Model.Access.Project. + } +

+ + + @foreach (var action in AccessSupport.AllActions) + { + var who = Model.Access.Who(action); + var remoteDeploy = action == BaGet.Core.AccessAction.Deploy && Model.Repository?.Kind == BaGet.Core.RepositoryKind.Remote; + var virtualDeploy = action == BaGet.Core.AccessAction.Deploy && Model.Repository?.Kind == BaGet.Core.RepositoryKind.Virtual; + + + + + } + +
@action@(remoteDeploy ? "nobody: a remote repository takes no deployments, the server caches what it fetches" : virtualDeploy ? "decided by the deploy repository (" + (Model.VirtualDetail?.DeployTarget?.Name ?? "none") + "), not here" : who.Count == 0 ? "nobody but administrators" : string.Join(", ", who))
+ } +
+ } + + @if (Model.Repository != null && Model.Repository.Kind != BaGet.Core.RepositoryKind.Virtual) + { +
+

Vulnerabilities

+

Findings, the scanning policy of this repository and Scan now: vulnerability dashboard.

+
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Index.cshtml new file mode 100644 index 000000000..a207e1ffa --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminRepositories/Index.cshtml @@ -0,0 +1,216 @@ +@model BaGet.Identity.Application.Models.Repositories.RepositoriesViewModel +@{ + ViewData["Title"] = "Repositories"; +} + +
+

Repositories

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

Package formats this server can host.

+ +
+ + + + + @if (Model.FilterName != null || Model.FilterFormat != null || Model.FilterKind != null) + { + Clear + } +
+ + + + + + + @foreach (var repository in Model.Repositories) + { + var feed = Model.FeedUrl(repository); + + + + + + + + } + +
NameTypePackagesFeed
+ @repository.Name + @if (repository.IsDefault) + { + Default + } + @repository.Format / @repository.Kind@(repository.Kind == BaGet.Core.RepositoryKind.Virtual ? "-" : repository.PackageCount.ToString()) + @feed + + + @foreach (var link in Model.LinksOf(repository)) + { + @link.Label + | + } + Edit + @if (!repository.IsDefault) + { + | + Delete + } +
+ +

New repository

+ @if (!Model.CanCreate) + { + + } + else + { +
+
+ + +
+ +

Local NuGet repository. Lowercase letters, digits, -, . and _; it cannot be renamed later.

+
+ + @foreach (var module in Model.OtherFormats) + { +

New @module.DisplayName repository

+
+ +
+ + +
+ @foreach (var field in module.CreateFields) + { +
+ + @if (field.Options != null) + { + + } + else + { + + } + @if (field.Help != null) + { + @field.Help + } +
+ } +
+ + +
+ +
+ } + +

New virtual repository

+

+ Presents several repositories of one format (local, remote or other virtual ones) as one feed: the first member that has a + package answers, version lists and search merge them (an npm package's dist-tags and a Maven artifact's latest and release follow the member order), and uploads go + to the member you pick as the deploy repository. Created empty; you add the members on its page. +

+
+
+ + +
+
+ + +
+
+ + +
+ +
+ +

New remote repository

+

+ Caches another feed or registry (NuGet: nuget.org, another BaGet, Artifactory, Azure Artifacts...; npm: registry.npmjs.org, + Verdaccio, Artifactory...; Maven: Maven Central, Artifactory, Nexus...): a package not stored here is fetched from the upstream + the first time it is requested. Clients cannot push to it. +

+
+
+ + + NuGet: a V3 index.json or V2 feed URL. npm: the registry's base URL, such as https://registry.npmjs.org/. Maven: the root of the repository, such as https://repo.maven.apache.org/maven2/ (Maven Central). Docker: the registry's address, such as https://registry-1.docker.io (Docker Hub). +
+
+ + +
+ +
+ + + + Whatever the upstream credentials can fetch is served to the readers: do not make a credentialed upstream + anonymously readable unless that is intended. + +
+ + + + } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Holds.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Holds.cshtml new file mode 100644 index 000000000..2af2f79b1 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Holds.cshtml @@ -0,0 +1,97 @@ +@model BaGet.Identity.Application.Models.Policies.RetentionHoldsViewModel +@{ + ViewData["Title"] = "Legal holds"; +} + +
+

Legal holds

+ +

Retention policies

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

+ A hold keeps an artifact, or one version of it, out of every retention policy, however old or unused. It governs + retention only: someone allowed to delete a version still can. Docker holds name the image and, optionally, a tag or digest. +

+ +
+
+ + +
+ +
+ + + + + + + @foreach (var hold in Model.Holds) + { + + + + + + + + + } + +
RepositoryArtifactVersionReasonPlaced
@hold.Repository@hold.Name@(hold.Version.Length == 0 ? "every version" : hold.Version)@hold.Reason@hold.Created.ToString("u")@(hold.CreatedBy != null ? " by " + hold.CreatedBy : "") +
+ + + + + +
+ @if (!Model.Holds.Any()) + { +

No hold is placed.

+ } + +

Place a hold

+
+ +
+ + +
+
+ + + Package id, npm name, Maven group:artifact or Docker image. +
+
+ + + Empty holds every version, including ones published later. +
+
+ + +
+ +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Index.cshtml new file mode 100644 index 000000000..6ed03fc22 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Index.cshtml @@ -0,0 +1,72 @@ +@using BaGet.Frontend.Controllers.Base +@model BaGet.Identity.Application.Models.Policies.RetentionViewModel +@{ + ViewData["Title"] = "Retention"; +} + +
+

Retention

+ + + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

+ A policy deletes old versions from a repository, or from every repository of a project: keep the newest N, delete by age, + by lack of downloads, trim a remote cache, remove untagged Docker manifests. Open a policy for a dry run + (the exact list a run would delete), to run it now, or to set a schedule. Versions under a + legal hold are never deleted. +

+ + + + + + + @foreach (var view in Model.Policies) + { + var policy = view.Policy; + + + + + + + + } + +
PolicyApplies toRulesScheduleLast run
+ @policy.Name + @if (!policy.Enabled) { disabled } + + @if (view.Repository != null) { repository @view.Repository } + else if (view.Project != null) { project @view.Project (@view.Targets repositories) } + else { nothing (its repository or project is gone) } + @RetentionControllerBase.Describe(policy)@(policy.ScheduleHours is int hours ? "every " + hours + " h" : "manual") + @if (policy.LastRun is DateTime last) + { + @last.ToString("u")
@policy.LastResult + } + else + { + never + } +
+ @if (!Model.Policies.Any()) + { +

There is no policy yet.

+ } + +

New policy

+
+ + + + +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Policy.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Policy.cshtml new file mode 100644 index 000000000..9d4c718cc --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminRetention/Policy.cshtml @@ -0,0 +1,127 @@ +@using BaGet.Frontend.Controllers.Base +@model BaGet.Identity.Application.Models.Policies.RetentionPolicyViewModel +@{ + var policy = Model.View!.Policy; + ViewData["Title"] = "Retention policy " + policy.Name; + var status = Model.Status; + var report = status?.Report; +} + +
+

@policy.Name

+ +

All policies | Legal holds

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

+ @RetentionControllerBase.Describe(policy) on + @if (Model.View.Repository != null) { repository @Model.View.Repository } + else { project @Model.View.Project (@Model.View.Targets repositories) }. + @(policy.Enabled ? "Enabled." : "Disabled.") + @if (policy.LastRun is DateTime last) { Last run @last.ToString("u"): @policy.LastResult } +

+ +

Run

+
+
+
+ + Lists what a run would delete. Deletes nothing. +
+
+
+
+ + + Deletes the selected versions for good. + +
+
+ + @if (status != null) + { +
+

@(status.DryRun ? "Dry run" : "Run") @status.State.ToString().ToLowerInvariant()

+

started @status.Started.ToString("u")@(status.Actor != null ? " by " + status.Actor : "")@(status.Finished is DateTime done ? ", finished " + done.ToString("u") : "")

+ @if (status.Error != null) + { + + } +
+ } + @if (report != null) + { +
+

@report.Summary

+ @foreach (var part in report.Repositories) + { +

@part.Repository @part.Format; examined @part.Examined, @(report.DryRun ? "to delete" : "deleted") @(report.DryRun ? part.Selected : part.Deleted), held @part.Held@(part.Failed > 0 ? ", failed " + part.Failed : "")

+ @if (part.Error != null) + { + + } + @foreach (var note in part.Notes) + { +

@note

+ } + @if (part.GarbageCollection != null) + { +

Garbage collection: @part.GarbageCollection.Summary

+ } + @if (part.Items.Count > 0) + { + + + + + + @foreach (var item in part.Items) + { + + + + + + + + + + } + +
ArtifactVersionPublishedLast downloadSizeWhyOutcome
@item.Name@item.Version@item.Published.ToString("u")@(item.LastDownloaded?.ToString("u") ?? "never recorded")@(item.Size is long size ? BaGet.Core.RetentionReport.FormatBytes(size) : "unknown")@item.Rules@item.Outcome@(item.Error != null ? ": " + item.Error : "")
+ @if (part.ItemsTruncated) + { +

Only the first @BaGet.Core.RetentionRepositoryReport.MaxItems versions are listed; the counts are complete.

+ } + } + } +
+ } + +

Rules

+
+ + + + + +

Delete the policy

+
+ + + Versions it already deleted stay deleted. + +
+ +@if (Model.Running) +{ + +} diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Index.cshtml new file mode 100644 index 000000000..fd3026d74 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Index.cshtml @@ -0,0 +1,87 @@ +@model BaGet.Identity.Application.Models.Policies.ScanningViewModel +@{ + ViewData["Title"] = "Vulnerability scanning"; +} + +
+

Vulnerability scanning

+ + +
+ @if (!Model.Options.Enabled) + { + + } + else + { +

+ NuGet, npm and Maven artifacts: @(string.IsNullOrWhiteSpace(Model.Options.OsvOfflinePath) ? "OSV.dev (" + Model.Options.OsvUrl + ")" : "an offline copy of the OSV data (" + Model.Options.OsvOfflinePath + ")").
+ Container images: @(Model.TrivyConfigured ? "Trivy" : "not scanned (Trivy is not configured: set Scanning:TrivyPath and Scanning:TrivyRegistryHost)").
+ Scan on deploy: @(Model.Options.ScanOnDeploy ? "yes" : "no"); rescan every @(Model.Options.RescanInterval > TimeSpan.Zero ? Model.Options.RescanInterval.ToString() : "- (never, only on demand)"). +

+ } +

+ Advisory data comes from OSV.dev and is licensed per source (mostly CC-BY 4.0, such as the GitHub Advisory Database); every advisory in the pages links to its source. Container image findings come from Trivy. The options are in the server settings. +

+
+ +
+

Repositories

+ + + + + + @foreach (var row in Model.Repositories) + { + + + + @if (!row.Summary.Engine.Available) + { + + } + else + { + + + + + + + } + + + } + +
RepositoryFormatArtifactsCriticalHighModerateLowNot scannedPolicy
@row.Repository.Name@row.Repository.Format (@row.Repository.Kind)@row.Summary.Engine.Reason@row.Summary.Artifacts@row.Summary.BySeverity[3]@row.Summary.BySeverity[2]@row.Summary.BySeverity[1]@row.Summary.BySeverity[0]@row.Summary.Unscanned + @if (row.Policy.From == null) + { + none + } + else + { + @:@row.Policy.From @row.Policy.Name + } +
+
+ +
+

Projects

+ @if (Model.Projects.Count == 0) + { +

There are no projects. A project groups repositories and can give them one policy.

+ } + else + { +
    + @foreach (var project in Model.Projects) + { +
  • @project.Project.Name @(project.HasPolicy ? "(policy set)" : "(no policy)")
  • + } +
+ } +
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Project.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Project.cshtml new file mode 100644 index 000000000..73657d9fe --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Project.cshtml @@ -0,0 +1,41 @@ +@model BaGet.Identity.Application.Models.Policies.ScanProjectViewModel +@{ + ViewData["Title"] = "Scanning policy of " + Model.Name; +} + +
+

Scanning policy project @Model.Name

+ + +

Back to scanning | The project

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + +

This policy applies to the repositories of the project that have no scanning policy of their own:

+ @if (Model.Project!.Repositories.Count == 0) + { +

The project has no repositories.

+ } + else + { +
    + @foreach (var repository in Model.Project.Repositories) + { +
  • @repository
  • + } +
+ } + +
+ + + +

Saving asks for your password again. A policy with everything off removes it.

+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Repository.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Repository.cshtml new file mode 100644 index 000000000..11bd77a82 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminScanning/Repository.cshtml @@ -0,0 +1,135 @@ +@model BaGet.Identity.Application.Models.Policies.ScanRepositoryViewModel +@{ + ViewData["Title"] = "Vulnerabilities of " + Model.Name; + var summary = Model.Summary!; + string LabelOf(int severity) => severity switch { 3 => "label-danger", 2 => "label-warning", 1 => "label-info", _ => "label-default" }; +} + +
+

Vulnerabilities @Model.Name

+ + +

Back to scanning

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + + @if (!summary.Engine.Available) + { + + } + else + { +

Scanner: @summary.Engine.Engine.

+ } + +
+

Summary

+ + + + + + + + + + + + + +
ArtifactsCriticalHighModerateLowCleanNot scanned
@summary.Artifacts@summary.BySeverity[3]@summary.BySeverity[2]@summary.BySeverity[1]@summary.BySeverity[0]@summary.Clean@summary.Unscanned@(summary.Failed > 0 ? " (" + summary.Failed + " failed)" : "")
+ + @if (summary.Engine.Available) + { +
+ +
+ } + @if (Model.Job != null) + { +

+ @Model.Job.State + started @Model.Job.Started.ToString("u")@(Model.Job.Actor != null ? " by " + Model.Job.Actor : "")@(Model.Job.Finished != null ? ", finished " + Model.Job.Finished.Value.ToString("u") : ""). + @Model.Job.Message +

+ } +
+ +
+

Versions with findings

+
+ + + +
+ + @if (Model.Findings.Count == 0) + { +

No scanned version has a finding@(Model.MinSeverity > 0 ? " at this severity" : "").

+ } + else + { + + + + @foreach (var result in Model.Findings) + { + var url = Model.PackageUrl(result); + + + + + + + + + } + +
ArtifactVersionWorstFindingsScanned
@result.Name@(result.Version!.Length > 24 ? result.Version.Substring(0, 24) + "…" : result.Version)@BaGet.Core.ScanSeverities.Name(result.Highest)@result.FindingCount@result.ScannedAt?.ToString("u") (@result.Scanner)@if (url != null) { Open }
+

+ @if (Model.PageNumber > 1) + { + Previous + } + @if (Model.HasMore) + { + Next + } +

+ } +
+ +
+

Policy

+ @if (Model.Effective.From == null) + { +

No policy applies: findings are shown, nothing is blocked.

+ } + else if (Model.Effective.From == BaGet.Core.ScanPolicyScope.Project) + { +

The policy of the project @Model.Effective.Name applies. A policy saved here replaces it for this repository.

+ } + else + { +

This repository has its own policy@(Model.Own?.ModifiedBy != null ? " (saved by " + Model.Own.ModifiedBy + ")" : "").

+ } + +
+ + + +

Saving asks for your password again. A policy with everything off removes it. The thresholds are Low, Moderate, High and Critical as the advisory source rates them (an unrated finding counts as Moderate).

+
+
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminSettings/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminSettings/Index.cshtml new file mode 100644 index 000000000..0a6f469b9 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminSettings/Index.cshtml @@ -0,0 +1,478 @@ +@model BaGet.Identity.Application.Models.Settings.AdminSettingsViewModel +@{ + ViewData["Title"] = "Server settings"; +} + +
+

Server settings

+ +

Saved to @Model.OverridesPath. Environment variables and command-line arguments override saved values.

+ + @if (Model.LoadError != null) + { + + } + @if (Model.Message != null) + { + + } + @if (Model.PendingRestart.Count > 0) + { + + } + + @if (Model.CopyStatus.Phase != BaGet.Core.DatabaseCopyPhase.Idle) + { + var copy = Model.CopyStatus; +
+ Database copy: @copy.Phase +
@copy.Message
+
@(copy.Phase == BaGet.Core.DatabaseCopyPhase.Copying ? $"{copy.Table}: {copy.TableRowsCopied} of {copy.TableRowsTotal} rows; {copy.RowsCopied} of {copy.RowsTotal} in all." : "")
+
    @foreach (var e in copy.Errors) {
  • @e
  • }
+
Restart BaGet now to use the new database. Until then every write is refused.
+
+ } + +
+ +
+ @foreach (var s in Model.Sections) + { + var title = s.Key.Length == 0 ? "General" : s.Key; + var formId = Model.SectionId(s.Key); + + @if (string.Equals(s.Key, "Serilog", StringComparison.OrdinalIgnoreCase)) + { + + } + @if (string.Equals(s.Key, "Accounts", StringComparison.OrdinalIgnoreCase)) + { + + } + } +
+
+
+ +@section Scripts { + + + +} diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Delete.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Delete.cshtml new file mode 100644 index 000000000..0a2cd26d3 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Delete.cshtml @@ -0,0 +1,70 @@ +@model BaGet.Identity.Application.Models.Users.DeleteUserViewModel +@{ + ViewData["Title"] = "Delete " + Model.Name; +} + +
+

Delete @Model.Name

+ + + @if (Model.Error != null) + { + + } + +

What goes

+
    +
  • @Model.Preview?.ApiKeys API key(s).
  • +
  • Ownership of @Model.Preview?.DirectPackageIds.Count package ID(s)@(Model.Preview?.DirectPackageIds.Count > 0 ? ": " + string.Join(", ", Model.Preview.DirectPackageIds) : "").
  • + @foreach (var organization in Model.Preview?.Organizations ?? []) + { +
  • Organization @organization.Name: @organization.Outcome
  • + } +
+ + @if (Model.LastAdministrator) + { + + } + else + { +
+ @if (Model.Preview?.SoleOwnedPackages.Count > 0) + { +

Packages only @Model.Name owns

+

@string.Join(", ", Model.Preview.SoleOwnedPackages.Select(p => p.Label))

+
+ +
+
+ +
+ } + +

Confirm

+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + Cancel + + } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Detail.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Detail.cshtml new file mode 100644 index 000000000..2c1874b1f --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Detail.cshtml @@ -0,0 +1,189 @@ +@model BaGet.Identity.Application.Models.Users.UserDetailViewModel +@{ + ViewData["Title"] = Model.Account?.UserName ?? "User"; + var userUrl = Url.Content("~/admin/users/" + Uri.EscapeDataString(Model.Account?.UserName ?? string.Empty)); +} + +
+

@Model.Account?.UserName

+ + +

Back to users

+ + @if (Model.Message != null) + { + + } + @if (Model.Error != null) + { + + } + + @* Each section is independent: add another by adding a block with its own user-section-* id. *@ +
+

Account

+ + + + + + +
Email@(Model.Account?.Email ?? "None")
Created@Model.Account?.Created.ToString("yyyy-MM-dd")
Role@(Model.Account?.IsAdministrator == true ? "Administrator" : "User")
Status@(Model.Account?.PendingApproval == true ? "Awaiting approval: cannot sign in" : "Active")
Packages@Model.OwnedPackageIds owned (list)
+ @if (Model.Account?.PendingApproval == true) + { +
+ @if (Model.HasPassword) + { +
+ + + Approving asks for your password again. +
+ } + else + { + + } + + + } +
+ +
+

Organizations

+ @if (Model.Organizations.Count == 0) + { +

@Model.Account?.UserName belongs to no organization.

+ } + else + { + + } +
+ +
+

API keys

+ @if (Model.Keys.Count == 0) + { +

@Model.Account?.UserName has no API keys.

+ } + else + { +
+ + + + + + @foreach (var key in Model.Keys) + { + + + + + + + + + + } + +
DescriptionScopesPackagesRepositoriesCreatedExpires
@key.Description@string.Join(", ", key.Scopes)@key.PackageGlobPattern@key.Repositories@key.Created.ToString("yyyy-MM-dd")@(key.Expires?.ToString("yyyy-MM-dd") ?? "Never")
+ + @if (Model.HasPassword) + { +
+ + + Revoking asks for your password again. +
+ } + else + { + + } + + } +
+ + @if (Model.ModelAvailable) + { +
+

Groups

+ @if (Model.Groups.Count == 0) + { +

@Model.Account?.UserName is in no group (besides the implicit Everyone and Authenticated).

+ } + else + { +
+ + + @foreach (var group in Model.Groups) + { + + + + + } + +
@group
+ + + } + +
+ + + + +
+ +
+

Projects

+ @if (Model.ProjectRoles.Count == 0) + { +

@Model.Account?.UserName has no role in any project.

+ } + else + { + + + @foreach (var role in Model.ProjectRoles) + { + + + + + + } + +
@role.Project@role.Role@role.Via
+ } +
+ +
+

Effective permissions

+

+ What @Model.Account?.UserName may do in each repository, and the permission targets or project roles that say so. + Changing an existing package ID also needs ownership. +

+
+ + +
+ @foreach (var row in Model.Access) + { +
+

@row.Repository.Name

+ +
+ } +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Index.cshtml new file mode 100644 index 000000000..bbb903f42 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Index.cshtml @@ -0,0 +1,186 @@ +@model BaGet.Identity.Application.Models.Users.UsersViewModel +@{ + ViewData["Title"] = "Users"; +} + +
+

Users

+ + + @if (Model.Message != null) + { + + } + @if (Model.GeneratedPassword != null) + { + + } + @if (Model.Error != null) + { + + } + + @if (Model.PendingCount > 0) + { + + } + +
+ + +
+ +
+ + + + + + + + + @foreach (var user in Model.Users) + { + + + + + + + + + } + +
UserEmailCreatedRole
@user.UserName@user.Email@user.Created.ToString("yyyy-MM-dd") + @if (user.IsAdministrator) + { + Administrator + } + @if (user.PendingApproval) + { + Awaiting approval + } + + @if (user.PendingApproval) + { + + } + @if (user.IsAdministrator) + { + + } + else + { + + } + @if (Model.CanAct(user)) + { + Packages + + + + + Delete + } +
+ + @if (Model.Users.Count == 0) + { +

No users match.

+ } + +

Confirm

+
+ + + Sets and confirms this address for the user, as account reset-password --email does: a user with no address cannot sign in while SMTP is configured. +
+

Every action here, creating a user included, asks for your password again.

+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + +
+

Create a user

+
+
+ + +
+
+ + +
+
+ + + Leave blank to generate one, shown once. +
+ @if (Model.CanInvite) + { +
+ +
+ } +
+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + + @if (Model.PageCount > 1) + { +
    + @if (Model.PageNumber > 1) + { + + } +
  • Page @Model.PageNumber of @Model.PageCount
  • + @if (Model.PageNumber < Model.PageCount) + { + + } +
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Packages.cshtml b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Packages.cshtml new file mode 100644 index 000000000..45b7f79fe --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/AdminUsers/Packages.cshtml @@ -0,0 +1,37 @@ +@using BaGet.Identity.Extensions +@model BaGet.Identity.Application.Models.Packages.UserPackagesViewModel +@{ + ViewData["Title"] = $"Packages of {Model.Name}"; +} + +
+

Packages of @Model.Name

+ + +

Back to users

+ + @if (Model.Packages.Count == 0) + { +

@Model.Name does not own any package.

+ } + else + { + + + + + + @foreach (var row in Model.Packages) + { + + + + + + + + } + +
PackageLatest versionDownloadsOwners
@row.Package.Id@(row.Package.LatestVersion ?? "None")@row.Package.Downloads.ToString("N0")@string.Join(", ", row.Owners)Manage
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/ContactOwners/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/ContactOwners/Index.cshtml new file mode 100644 index 000000000..abbff4464 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/ContactOwners/Index.cshtml @@ -0,0 +1,53 @@ +@using BaGet.Identity.Extensions +@model BaGet.Identity.Application.Models.Packages.ContactOwnersViewModel +@{ + ViewData["Title"] = $"Contact the owners of {Model.PackageId}"; +} + +
+

Contact the owners of @Model.PackageId

+ + + @if (Model.Sent) + { + +

Back to @Model.PackageId

+ } + else + { +

+ The owners will receive your message by email with your address as the reply address. + Their addresses are not shown to you. +

+ + @if (Model.Error != null) + { + + } + + @if (!Model.SenderHasEmail) + { + + } + else + { +
+
+
+ + + +
+
+ +
+ +
+ } + } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/DockerManage/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/DockerManage/Index.cshtml new file mode 100644 index 000000000..69eba8b70 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/DockerManage/Index.cshtml @@ -0,0 +1,102 @@ +@model BaGet.Identity.Application.Models.Packages.DockerManageViewModel +@{ + ViewData["Title"] = "Manage " + Model.Image; + ViewData["HideSearchBar"] = true; +} + +@if (Model.Info == null) +{ + @* A refused write (read-only mode) shows its message even where there is nothing to list. *@ + @if (Model.Message != null) + { +
+ } + + return; +} + +@{ + var info = Model.Info; +} + +
+

Manage @info.Name

+ + + @if (Model.Message != null) + { + + } + +

+ Deleting needs the Delete permission on the image and your password (type it in the danger zone below first). A deleted + manifest cannot be pulled any more; its layers stay until no manifest of the repository needs them and they are pruned. +

+ +

Tags

+ + + + @foreach (var tag in info.Tags) + { + + + + + + } + @if (info.Tags.Count == 0) + { + + } + +
TagManifest
@tag.Name@tag.Digest.Substring(0, 19)... + +
No tag.
+ +

Manifests

+ + + + @foreach (var manifest in info.Manifests) + { + + + + + + + + } + +
DigestTypePlatformTags
@manifest.Digest.Substring(0, 19)...@(manifest.IsIndex ? "index" : "image")@(manifest.Platform ?? "")@string.Join(", ", manifest.Tags) + +
+ +

Unused layers

+

@info.UnreferencedBlobs layer@(info.UnreferencedBlobs == 1 ? "" : "s") of this image are used by no manifest. Those uploaded more than an hour ago can be removed.

+ +

Danger zone

+
+

Deleting removes content for good. Confirm it is you.

+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + + +
diff --git a/src/BaGet.Identity.FrontEnd/Views/MavenManage/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/MavenManage/Index.cshtml new file mode 100644 index 000000000..8a6a44629 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/MavenManage/Index.cshtml @@ -0,0 +1,145 @@ +@model BaGet.Identity.Application.Models.Packages.MavenManageViewModel +@{ + ViewData["Title"] = "Manage " + Model.Name; + ViewData["HideSearchBar"] = true; +} + +@if (Model.Info == null) +{ + @* A refused write (read-only mode) shows its message even where there is nothing to list. *@ + @if (Model.Message != null) + { +
+ } + + return; +} + +@{ + var info = Model.Info; + var selected = Model.Selected; +} + +
+

Manage @info.GroupId:@info.ArtifactId

+ + + @if (Model.Message != null) + { + + } + + @if (Model.ActingAsAdministrator) + { +

You are not an owner of this artifact; you manage it as an administrator. Your changes are logged.

+ } + +

Owners

+ + + @foreach (var owner in Model.Owners) + { + + + + + } + @if (Model.Owners.Count == 0) + { + + } + +
@owner.OwnerName +
+ + +
+
No owner: only an administrator may change this artifact.
+
+ + +
+ +

Versions

+

+ Deleting needs the Delete permission and ownership. A deleted version's files are removed for good; a release number can be deployed again. + Confirm with your password in the danger zone below first. +

+ + + + @foreach (var version in info.Versions) + { + + + + + + + + } + +
VersionStoredFilesBuilds
@version.Version @(version.IsSnapshot ? "(snapshot)" : "")@version.Modified.ToString("yyyy-MM-dd HH:mm") UTC@version.FileCount@(version.IsSnapshot ? version.Builds.ToString() : "") + Files + +
+ + @if (selected != null) + { +

Files of @selected.Summary.Version

+ + + + @foreach (var file in selected.Files) + { + + + + + + + } + +
FileSizeSHA-1
@file.FileName@file.Size.ToString("N0") bytes@file.Sha1 + +
+ + @if (selected.Summary.IsSnapshot) + { +

Clean up snapshot builds

+

@selected.Summary.Builds timestamped build@(selected.Summary.Builds == 1 ? "" : "s") stored. Older builds beyond the number kept are deleted with all their files.

+
+ + + @if (Model.HasPassword) + { + + } + +
+ } + } + +

Danger zone

+
+

Deleting removes files for good. Confirm it is you.

+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + +
diff --git a/src/BaGet.Identity.FrontEnd/Views/NpmManage/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/NpmManage/Index.cshtml new file mode 100644 index 000000000..72a9fee5d --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/NpmManage/Index.cshtml @@ -0,0 +1,159 @@ +@model BaGet.Identity.Application.Models.Packages.NpmManageViewModel +@{ + ViewData["Title"] = "Manage " + Model.Id; + ViewData["HideSearchBar"] = true; +} + +@if (Model.Package == null) +{ + @* A refused write (read-only mode) shows its message even where there is nothing to list. *@ + @if (Model.Message != null) + { +
+ } + + return; +} + +@{ + var package = Model.Package; + var window = Model.UnpublishWindow; +} + +
+

Manage @package.Name

+ + + @if (Model.Message != null) + { + + } + + @if (Model.ActingAsAdministrator) + { +

You are not an owner of this package; you manage it as an administrator. Your changes are logged.

+ } + +

Owners

+ + + @foreach (var owner in Model.Owners) + { + + + + + } + @if (Model.Owners.Count == 0) + { + + } + +
@owner.OwnerName +
+ + +
+
No owner: only an administrator may change this package.
+
+ + +
+ +

Dist-tags

+ + + + @foreach (var tag in package.DistTags.OrderBy(t => t.Key, StringComparer.Ordinal)) + { + + + + + + } + +
TagVersion
@tag.Key@tag.Value +
+ + +
+
+
+ + + +
+ +

Versions

+

+ @if (window > TimeSpan.Zero) + { + The owner may unpublish a version within @window.TotalHours.ToString("0.##") hours of publishing it; later, unpublishing needs the Delete permission. + } + else + { + Unpublishing needs the Delete permission. + } + An unpublished version's tarball is deleted and its number can be published again. +

+ + + + @foreach (var version in package.Versions.Reverse()) + { + + + + + + + } + +
VersionPublishedDeprecation
@version.Version@version.Published.ToString("yyyy-MM-dd HH:mm") UTC + @if (version.Deprecated != null) + { + Deprecated @version.Deprecated +
+ + +
+ } + else + { +
+ + + +
+ } +
+ +
+ +

Danger zone

+
+

Unpublishing deletes tarballs for good. Confirm it is you.

+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + + +
diff --git a/src/BaGet.Identity.FrontEnd/Views/PackageManage/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/PackageManage/Index.cshtml new file mode 100644 index 000000000..bf74877de --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/PackageManage/Index.cshtml @@ -0,0 +1,322 @@ +@using BaGet.Identity.Extensions +@model BaGet.Identity.Models.Packages.ManageViewModel +@{ + ViewData["Title"] = $"Manage {Model.Id}"; +} + +
+

Manage @Model.Id

+ + + @if (Model.Message != null) + { + + } + + @if (Model.ActingAsAdministrator) + { + + } + + @if (Model.IsReadOnlyMode) + { + @* The buttons stay on the page but do nothing: every handler here is refused while + the server is read-only, exactly as the push and metadata endpoints are. *@ + + } + + @if (Model.HasValidation) + { +

+ Validation status of the submissions +

+ } + +

Owners

+ + + @foreach (var owner in Model.Owners) + { + + + + + } + +
@owner.OwnerName@(owner.IsVerified ? " (verified)" : "") +
+ + +
+
+
+ + +
+ +

+ This ID is @(Model.IsVerified ? "verified" : "not verified"). + @if (Model.IsAdministrator) + { +

+ + +
+ } + else + { + Only an administrator can change this. + } +

+ +

Versions

+

+ Upload new version +

+

+ @Model.DeleteLabel: @Model.DeleteCaption + @if (!Model.DeletionIsPermanent) + { + It is the same operation as the Unlist button beside each version. + } +

+ + + + @foreach (var package in Model.Versions) + { + var version = package.NormalizedVersionString; + + + + + + + + + } + +
VersionDownloadsListedDeprecation
@version@package.Downloads.ToString("N0") + @(package.Listed ? "Yes" : "No") +
+ + +
+
+ @if (package.Deprecation != null) + { + @string.Join(", ", package.Deprecation.Reasons ?? Array.Empty()) +
+ + +
+ } +
+
+ + @foreach (var reason in PackageDeprecation.KnownReasons) + { + + } + + + + +
+
+ @* Labelled from the configured behaviour: on a server that unlists, + this button must not claim to delete. *@ +
+ + +
+ @if (Model.IsAdministrator && !Model.DeletionIsPermanent) + { + @* The server only unlists; an administrator may still remove the version. + The password is in the danger zone's form, which this button submits. *@ + + } +
+ +

Vulnerabilities

+

+ Advisories listed in the registration metadata, which NuGet clients use to warn about a version + (low, moderate, high or critical). The version range is optional. +

+ + + + @foreach (var package in Model.Versions) + { + var version = package.NormalizedVersionString; + foreach (var vulnerability in package.Vulnerabilities ?? new List()) + { + + + + + + + + } + } + +
VersionAdvisorySeverityRange
@version@vulnerability.AdvisoryUrl@(vulnerability.Severity >= 0 && vulnerability.Severity < Model.SeverityNames.Count ? Model.SeverityNames[vulnerability.Severity] : vulnerability.Severity.ToString())@vulnerability.VersionRange + @if (vulnerability.Source == null) + { +
+ + + +
+ } + else + { + found by the @vulnerability.Source scan + } +
+
+ + + + + +
+ +

Symbols

+ @if (!Model.SymbolsSupported) + { +

+ The configured database cannot record which package version symbols belong to, so they cannot be listed or deleted here. +

+ } + else + { +

+ PDBs from symbol packages (.snupkg) indexed since this list was introduced. Symbols are stored by file + and key, not by package, so earlier ones are still served but cannot be listed or deleted here. +

+ @if (Model.Symbols.Count == 0) + { +

No symbols are recorded for any version.

+ } + else + { + + + + @foreach (var package in Model.Versions) + { + var version = package.NormalizedVersionString; + if (!Model.Symbols.TryGetValue(package.Version.ToNormalizedString(), out var pdbs)) continue; + + + + + + } + +
VersionPDBs
@version + @foreach (var pdb in pdbs) + { +
@pdb.FileName @pdb.Key
+ } +
+
+ + +
+
+ } + } + +

Abuse reports

+ @if (Model.Reports.Count == 0) + { +

There are no open reports.

+ } + else + { + + + + @foreach (var report in Model.Reports) + { + + + + + + + + } + +
VersionReasonDetailsReporter
@report.PackageVersion@report.Reason@report.Details@report.ReporterEmail +
+ + +
+
+ } + + @if (Model.IsAdministrator) + { +
+

Danger zone

+
+

+ Deleting permanently removes the database rows and the files from storage, whatever + the server's deletion setting says. It cannot be undone. Deleting every version also + removes the owners, so the ID can be claimed again. +

+
+ @if (Model.HasPassword) + { +
+ + +
+ } + else + { + + } + + +
+
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/Profile/Profile.cshtml b/src/BaGet.Identity.FrontEnd/Views/Profile/Profile.cshtml new file mode 100644 index 000000000..9e174f41b --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/Profile/Profile.cshtml @@ -0,0 +1,47 @@ +@using BaGet.Identity.Extensions +@model BaGet.Identity.Application.Models.Account.ProfileViewModel +@{ + ViewData["Title"] = Model.Name; +} + +
+

@Model.Name

+ + + @if (Model.IsOrganization) + { +

Organization with @Model.Members.Count member@(Model.Members.Count == 1 ? "" : "s"): + @foreach (var member in Model.Members) + { + @member + } +

+ } + + @if (Model.IsCurrentUser) + { +

API keys · Organizations

+ } + +

Packages

+ @if (Model.Packages.Count == 0) + { +

No packages.

+ } + else + { + + + + @foreach (var package in Model.Packages) + { + + + + + + } + +
PackageDownloads
@package.Id@package.Downloads.ToString("N0")@if (Model.IsCurrentUser || Model.IsOrganization) { Manage }
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/ScanArtifact/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/ScanArtifact/Index.cshtml new file mode 100644 index 000000000..4a2f7ebef --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/ScanArtifact/Index.cshtml @@ -0,0 +1,50 @@ +@model BaGet.Identity.Application.Models.Policies.ScanViewModel +@{ + ViewData["Title"] = "Scan " + Model.Name; +} + +
+

Vulnerability scan @Model.Name @Model.Version

+ + + @if (Model.Message != null) + { + + } + + @if (Model.Engine is { Available: false }) + { + + } + + @if (Model.Result != null) + { +

+ @if (Model.Result.ScannedAt != null) + { + Last scanned @Model.Result.ScannedAt.Value.ToString("u") by @Model.Result.Scanner: @Model.Result.FindingCount finding(s). + } + else + { + Never scanned successfully. + } + @if (Model.Result.Error != null) + { + The last attempt failed: @Model.Result.Error + } +

+ + } + + @if (Model.Engine is not { Available: false }) + { +
+ + + + +
+ } + +

Back

+
diff --git a/src/BaGet.Identity.FrontEnd/Views/ValidationStatusPage/Index.cshtml b/src/BaGet.Identity.FrontEnd/Views/ValidationStatusPage/Index.cshtml new file mode 100644 index 000000000..dbeb42723 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/ValidationStatusPage/Index.cshtml @@ -0,0 +1,35 @@ +@using BaGet.Identity.Extensions +@model BaGet.Identity.Application.Models.Operations.ValidationStatusViewModel +@{ + ViewData["Title"] = $"Validation of {Model.Id}"; +} + +
+

Validation of @Model.Id

+ + +

+ The newest submission of each version: it is Available once every step succeeded, Quarantined + when one failed (an administrator then retries, releases or rejects it), and Validating until then. + Back to managing @Model.Id +

+ + @foreach (var submission in Model.Submissions) + { +

@submission.Version @submission.Status

+ + + + @foreach (var step in submission.Steps) + { + + + + + + + } + +
StepStateMessageCompleted
@step.Type@step.State@step.Message@(step.Completed?.ToString("u"))
+ } +
diff --git a/src/BaGet.Identity.FrontEnd/Views/_ViewImports.cshtml b/src/BaGet.Identity.FrontEnd/Views/_ViewImports.cshtml new file mode 100644 index 000000000..082247e26 --- /dev/null +++ b/src/BaGet.Identity.FrontEnd/Views/_ViewImports.cshtml @@ -0,0 +1,12 @@ +@using BaGet.Core +@using BaGet.Identity.Application.Links +@using BaGet.Identity.Application.Models.Account +@using BaGet.Identity.Application.Models.Operations +@using BaGet.Identity.Application.Models.Packages +@using BaGet.Identity.Application.Models.Policies +@using BaGet.Identity.Application.Models.Settings +@using BaGet.Identity.Application.Models.Shared +@using BaGet.Identity.Application.Models.Users +@using BaGet.Identity.Application.UseCases.Access +@namespace BaGet.Identity.Views +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/src/BaGet.Protocol/BaGet.Protocol.csproj b/src/BaGet.Protocol/BaGet.Protocol.csproj index 5711a54bb..dee45eb4a 100644 --- a/src/BaGet.Protocol/BaGet.Protocol.csproj +++ b/src/BaGet.Protocol/BaGet.Protocol.csproj @@ -1,17 +1,23 @@ - netstandard2.0 - + net10.0 + latest NuGet;Protocol Libraries to interact with NuGet server APIs. + enable + - + + + + + diff --git a/src/BaGet.Protocol/Catalog/CatalogClient.cs b/src/BaGet.Protocol/Catalog/CatalogClient.cs index f87089d95..a563cdf4d 100644 --- a/src/BaGet.Protocol/Catalog/CatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/CatalogClient.cs @@ -3,46 +3,53 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class CatalogClient : ICatalogClient { - private class CatalogClient : ICatalogClient - { - private readonly NuGetClientFactory _clientfactory; + private readonly NuGetClientFactory _clientfactory; - public CatalogClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public CatalogClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task GetIndexAsync(CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetIndexAsync(CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetIndexAsync(cancellationToken); - } + #pragma warning disable CS8602 + return await client?.GetIndexAsync(cancellationToken); + #pragma warning restore CS8602 + } - public async Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetPageAsync(string? pageUrl, CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetPageAsync(pageUrl, cancellationToken); - } + #pragma warning disable CS8602 + return await client?.GetPageAsync(pageUrl, cancellationToken); + #pragma warning restore CS8602 + } - public async Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetPackageDetailsLeafAsync(string? leafUrl, CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetPackageDetailsLeafAsync(leafUrl, cancellationToken); - } + #pragma warning disable CS8602 + return await client?.GetPackageDetailsLeafAsync(leafUrl, cancellationToken); + #pragma warning restore CS8602 + } - public async Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetPackageDeleteLeafAsync(string? leafUrl, CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetPackageDeleteLeafAsync(leafUrl, cancellationToken); - } + #pragma warning disable CS8602 + return await client?.GetPackageDeleteLeafAsync(leafUrl, cancellationToken); + #pragma warning restore CS8602 } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/CatalogProcessor.cs b/src/BaGet.Protocol/Catalog/CatalogProcessor.cs index 13c5cc274..c73ee725e 100644 --- a/src/BaGet.Protocol/Catalog/CatalogProcessor.cs +++ b/src/BaGet.Protocol/Catalog/CatalogProcessor.cs @@ -4,198 +4,197 @@ using BaGet.Protocol.Models; using Microsoft.Extensions.Logging; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// Processes catalog leafs in chronological order. +/// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessor.cs +/// +public class CatalogProcessor { + private readonly ICatalogLeafProcessor _leafProcessor; + private readonly ICatalogClient _client; + private readonly ICursor _cursor; + private readonly CatalogProcessorOptions _options; + private readonly ILogger _logger; + /// - /// Processes catalog leafs in chronological order. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessor.cs + /// Create a processor to discover and download catalog leafs. Leafs are processed + /// by the . /// - public class CatalogProcessor + /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. + /// The client to interact with the catalog resource. + /// The leaf processor. + /// The options to configure catalog processing. + /// The logger used for telemetry. + public CatalogProcessor( + ICursor cursor, + ICatalogClient client, + ICatalogLeafProcessor leafProcessor, + CatalogProcessorOptions options, + ILogger logger) { - private readonly ICatalogLeafProcessor _leafProcessor; - private readonly ICatalogClient _client; - private readonly ICursor _cursor; - private readonly CatalogProcessorOptions _options; - private readonly ILogger _logger; - - /// - /// Create a processor to discover and download catalog leafs. Leafs are processed - /// by the . - /// - /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. - /// The client to interact with the catalog resource. - /// The leaf processor. - /// The options to configure catalog processing. - /// The logger used for telemetry. - public CatalogProcessor( - ICursor cursor, - ICatalogClient client, - ICatalogLeafProcessor leafProcessor, - CatalogProcessorOptions options, - ILogger logger) - { - _leafProcessor = leafProcessor ?? throw new ArgumentNullException(nameof(leafProcessor)); - _client = client ?? throw new ArgumentNullException(nameof(client)); - _cursor = cursor ?? throw new ArgumentNullException(nameof(cursor)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + _leafProcessor = leafProcessor ?? throw new ArgumentNullException(nameof(leafProcessor)); + _client = client ?? throw new ArgumentNullException(nameof(client)); + _cursor = cursor ?? throw new ArgumentNullException(nameof(cursor)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - /// - /// Discovers and downloads all of the catalog leafs after the current cursor value and before the maximum - /// commit timestamp found in the settings. Each catalog leaf is passed to the catalog leaf processor in - /// chronological order. After a commit is completed, its commit timestamp is written to the cursor, i.e. when - /// transitioning from commit timestamp A to B, A is written to the cursor so that it never is processed again. - /// - /// A token to cancel the task. - /// True if all of the catalog leaves found were processed successfully. - public async Task ProcessAsync(CancellationToken cancellationToken = default) - { - var minCommitTimestamp = await GetMinCommitTimestamp(cancellationToken); - _logger.LogInformation( - "Using time bounds {min:O} (exclusive) to {max:O} (inclusive).", - minCommitTimestamp, - _options.MaxCommitTimestamp); + /// + /// Discovers and downloads all of the catalog leafs after the current cursor value and before the maximum + /// commit timestamp found in the settings. Each catalog leaf is passed to the catalog leaf processor in + /// chronological order. After a commit is completed, its commit timestamp is written to the cursor, i.e. when + /// transitioning from commit timestamp A to B, A is written to the cursor so that it never is processed again. + /// + /// A token to cancel the task. + /// True if all of the catalog leaves found were processed successfully. + public async Task ProcessAsync(CancellationToken cancellationToken = default) + { + var minCommitTimestamp = await GetMinCommitTimestamp(cancellationToken); + _logger.LogInformation( + "Using time bounds {min:O} (exclusive) to {max:O} (inclusive).", + minCommitTimestamp, + _options.MaxCommitTimestamp); - return await ProcessIndexAsync(minCommitTimestamp, cancellationToken); - } + return await ProcessIndexAsync(minCommitTimestamp, cancellationToken); + } - private async Task ProcessIndexAsync(DateTimeOffset minCommitTimestamp, CancellationToken cancellationToken) + private async Task ProcessIndexAsync(DateTimeOffset minCommitTimestamp, CancellationToken cancellationToken) + { + var index = await _client.GetIndexAsync(cancellationToken); + + var pageItems = index.GetPagesInBounds( + minCommitTimestamp, + _options.MaxCommitTimestamp); + _logger.LogInformation( + "{pages} pages were in the time bounds, out of {totalPages}.", + pageItems.Count, + index.Items?.Count); + + var success = true; + for (var i = 0; i < pageItems.Count; i++) { - var index = await _client.GetIndexAsync(cancellationToken); - - var pageItems = index.GetPagesInBounds( - minCommitTimestamp, - _options.MaxCommitTimestamp); - _logger.LogInformation( - "{pages} pages were in the time bounds, out of {totalPages}.", - pageItems.Count, - index.Items.Count); - - var success = true; - for (var i = 0; i < pageItems.Count; i++) + success = await ProcessPageAsync(minCommitTimestamp, pageItems[i], cancellationToken); + if (!success) { - success = await ProcessPageAsync(minCommitTimestamp, pageItems[i], cancellationToken); - if (!success) - { - _logger.LogWarning( - "{unprocessedPages} out of {pages} pages were left incomplete due to a processing failure.", - pageItems.Count - i, - pageItems.Count); - break; - } + _logger.LogWarning( + "{unprocessedPages} out of {pages} pages were left incomplete due to a processing failure.", + pageItems.Count - i, + pageItems.Count); + break; } - - return success; } - private async Task ProcessPageAsync( - DateTimeOffset minCommitTimestamp, - CatalogPageItem pageItem, - CancellationToken cancellationToken) + return success; + } + + private async Task ProcessPageAsync( + DateTimeOffset minCommitTimestamp, + CatalogPageItem pageItem, + CancellationToken cancellationToken) + { + var page = await _client.GetPageAsync(pageItem.CatalogPageUrl, cancellationToken); + + var leafItems = page.GetLeavesInBounds( + minCommitTimestamp, + _options.MaxCommitTimestamp, + _options.ExcludeRedundantLeaves); + _logger.LogInformation( + "On page {page}, {leaves} out of {totalLeaves} were in the time bounds.", + pageItem.CatalogPageUrl, + leafItems.Count, + page.Items?.Count); + + DateTimeOffset? newCursor = null; + var success = true; + for (var i = 0; i < leafItems.Count; i++) { - var page = await _client.GetPageAsync(pageItem.CatalogPageUrl, cancellationToken); - - var leafItems = page.GetLeavesInBounds( - minCommitTimestamp, - _options.MaxCommitTimestamp, - _options.ExcludeRedundantLeaves); - _logger.LogInformation( - "On page {page}, {leaves} out of {totalLeaves} were in the time bounds.", - pageItem.CatalogPageUrl, - leafItems.Count, - page.Items.Count); - - DateTimeOffset? newCursor = null; - var success = true; - for (var i = 0; i < leafItems.Count; i++) + var leafItem = leafItems[i]; + + if (newCursor.HasValue && newCursor.Value != leafItem.CommitTimestamp) { - var leafItem = leafItems[i]; - - if (newCursor.HasValue && newCursor.Value != leafItem.CommitTimestamp) - { - await _cursor.SetAsync(newCursor.Value, cancellationToken); - } - - newCursor = leafItem.CommitTimestamp; - - success = await ProcessLeafAsync(leafItem, cancellationToken); - if (!success) - { - _logger.LogWarning( - "{unprocessedLeaves} out of {leaves} leaves were left incomplete due to a processing failure.", - leafItems.Count - i, - leafItems.Count); - break; - } + await _cursor.SetAsync(newCursor.Value, cancellationToken); } - if (newCursor.HasValue && success) + newCursor = leafItem.CommitTimestamp; + + success = await ProcessLeafAsync(leafItem, cancellationToken); + if (!success) { - await _cursor.SetAsync(newCursor.Value); + _logger.LogWarning( + "{unprocessedLeaves} out of {leaves} leaves were left incomplete due to a processing failure.", + leafItems.Count - i, + leafItems.Count); + break; } + } - return success; + if (newCursor.HasValue && success) + { + await _cursor.SetAsync(newCursor.Value); } - private async Task ProcessLeafAsync(CatalogLeafItem leafItem, CancellationToken cancellationToken) + return success; + } + + private async Task ProcessLeafAsync(CatalogLeafItem leafItem, CancellationToken cancellationToken) + { + bool success; + try { - bool success; - try + if (leafItem.IsPackageDelete()) { - if (leafItem.IsPackageDelete()) - { - var packageDelete = await _client.GetPackageDeleteLeafAsync(leafItem.CatalogLeafUrl); - success = await _leafProcessor.ProcessPackageDeleteAsync(packageDelete, cancellationToken); - } - else if (leafItem.IsPackageDetails()) - { - var packageDetails = await _client.GetPackageDetailsLeafAsync(leafItem.CatalogLeafUrl); - success = await _leafProcessor.ProcessPackageDetailsAsync(packageDetails, cancellationToken); - } - else - { - throw new NotSupportedException($"The catalog leaf type '{leafItem.Type}' is not supported."); - } + var packageDelete = await _client.GetPackageDeleteLeafAsync(leafItem.CatalogLeafUrl); + success = await _leafProcessor.ProcessPackageDeleteAsync(packageDelete, cancellationToken); } - catch (Exception exception) + else if (leafItem.IsPackageDetails()) { - _logger.LogError( - 0, - exception, - "An exception was thrown while processing leaf {leafUrl}.", - leafItem.CatalogLeafUrl); - success = false; + var packageDetails = await _client.GetPackageDetailsLeafAsync(leafItem.CatalogLeafUrl); + success = await _leafProcessor.ProcessPackageDetailsAsync(packageDetails, cancellationToken); } - - if (!success) + else { - _logger.LogWarning( - "Failed to process leaf {leafUrl} ({packageId} {packageVersion}, {leafType}).", - leafItem.CatalogLeafUrl, - leafItem.PackageId, - leafItem.PackageVersion, - leafItem.Type); + throw new NotSupportedException($"The catalog leaf type '{leafItem.Type}' is not supported."); } - - return success; + } + catch (Exception exception) + { + _logger.LogError( + 0, + exception, + "An exception was thrown while processing leaf {leafUrl}.", + leafItem.CatalogLeafUrl); + success = false; } - private async Task GetMinCommitTimestamp(CancellationToken cancellationToken) + if (!success) { - var minCommitTimestamp = await _cursor.GetAsync(cancellationToken); + _logger.LogWarning( + "Failed to process leaf {leafUrl} ({packageId} {packageVersion}, {leafType}).", + leafItem.CatalogLeafUrl, + leafItem.PackageId, + leafItem.PackageVersion, + leafItem.Type); + } - minCommitTimestamp = minCommitTimestamp - ?? _options.DefaultMinCommitTimestamp - ?? _options.MinCommitTimestamp; + return success; + } - if (minCommitTimestamp.Value < _options.MinCommitTimestamp) - { - minCommitTimestamp = _options.MinCommitTimestamp; - } + private async Task GetMinCommitTimestamp(CancellationToken cancellationToken) + { + var minCommitTimestamp = await _cursor.GetAsync(cancellationToken); + + minCommitTimestamp = minCommitTimestamp + ?? _options.DefaultMinCommitTimestamp + ?? _options.MinCommitTimestamp; - return minCommitTimestamp.Value; + if (minCommitTimestamp.Value < _options.MinCommitTimestamp) + { + minCommitTimestamp = _options.MinCommitTimestamp; } + + return minCommitTimestamp.Value; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs b/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs index 1b9bd5cc1..0617a01db 100644 --- a/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs +++ b/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs @@ -1,36 +1,35 @@ using System; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// The options to configure . +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessorSettings.cs +/// +public class CatalogProcessorOptions { /// - /// The options to configure . - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessorSettings.cs + /// The minimum commit timestamp to use when no cursor value has been saved. /// - public class CatalogProcessorOptions - { - /// - /// The minimum commit timestamp to use when no cursor value has been saved. - /// - public DateTimeOffset? DefaultMinCommitTimestamp { get; set; } + public DateTimeOffset? DefaultMinCommitTimestamp { get; set; } - /// - /// The absolute minimum (exclusive) commit timestamp to process in the catalog. - /// Use this to filter out catalog items that are "too old". - /// Set this to to process all catalog items. - /// - public DateTimeOffset MinCommitTimestamp { get; set; } + /// + /// The absolute minimum (exclusive) commit timestamp to process in the catalog. + /// Use this to filter out catalog items that are "too old". + /// Set this to to process all catalog items. + /// + public DateTimeOffset MinCommitTimestamp { get; set; } - /// - /// The absolute maximum (inclusive) commit timestamp to process in the catalog. - /// Use this to filter out catalog items that are "too new". - /// Set this to to process all catalog items. - /// - public DateTimeOffset MaxCommitTimestamp { get; set; } + /// + /// The absolute maximum (inclusive) commit timestamp to process in the catalog. + /// Use this to filter out catalog items that are "too new". + /// Set this to to process all catalog items. + /// + public DateTimeOffset MaxCommitTimestamp { get; set; } - /// - /// If multiple catalog leaves are found in a page concerning the same package ID and version, only the latest - /// is processed. - /// - public bool ExcludeRedundantLeaves { get; set; } - } -} + /// + /// If multiple catalog leaves are found in a page concerning the same package ID and version, only the latest + /// is processed. + /// + public bool ExcludeRedundantLeaves { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/FileCursor.cs b/src/BaGet.Protocol/Catalog/FileCursor.cs index 9be09c2c9..ce3ae4737 100644 --- a/src/BaGet.Protocol/Catalog/FileCursor.cs +++ b/src/BaGet.Protocol/Catalog/FileCursor.cs @@ -6,54 +6,53 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// A cursor implementation which stores the cursor in local file. The cursor value is written to the file as +/// a JSON object. +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/FileCursor.cs +/// +public class FileCursor : ICursor { - /// - /// A cursor implementation which stores the cursor in local file. The cursor value is written to the file as - /// a JSON object. - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/FileCursor.cs - /// - public class FileCursor : ICursor - { - private readonly string _path; - private readonly ILogger _logger; + private readonly string _path; + private readonly ILogger _logger; - public FileCursor(string path, ILogger logger) - { - _path = path ?? throw new ArgumentNullException(nameof(path)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public FileCursor(string path, ILogger logger) + { + _path = path ?? throw new ArgumentNullException(nameof(path)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task GetAsync(CancellationToken cancellationToken) + public async Task GetAsync(CancellationToken cancellationToken) + { + try { - try - { - using (var file = File.OpenRead(_path)) - { - var data = await JsonSerializer.DeserializeAsync(file, options: null, cancellationToken); - _logger.LogDebug("Read cursor value {cursor:O} from {path}.", data.Value, _path); - return data.Value; - } - } - catch (Exception e) when (e is FileNotFoundException || e is JsonException) + using (var file = File.OpenRead(_path)) { - return null; + var data = await JsonSerializer.DeserializeAsync(file, options: null, cancellationToken); + _logger.LogDebug("Read cursor value {cursor:O} from {path}.", data?.Value, _path); + return data?.Value; } } - - public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken) + catch (Exception e) when (e is FileNotFoundException || e is JsonException) { - var data = new Data { Value = value }; - var jsonString = JsonSerializer.Serialize(data); - File.WriteAllText(_path, jsonString); - _logger.LogDebug("Wrote cursor value {cursor:O} to {path}.", data.Value, _path); - return Task.CompletedTask; + return null; } + } - private class Data - { - [JsonPropertyName("value")] - public DateTimeOffset Value { get; set; } - } + public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken) + { + var data = new Data { Value = value }; + var jsonString = JsonSerializer.Serialize(data); + File.WriteAllText(_path, jsonString); + _logger.LogDebug("Wrote cursor value {cursor:O} to {path}.", data.Value, _path); + return Task.CompletedTask; + } + + private class Data + { + [JsonPropertyName("value")] + public DateTimeOffset Value { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/ICatalogClient.cs b/src/BaGet.Protocol/Catalog/ICatalogClient.cs index 65dbb4604..8b1a7d8d3 100644 --- a/src/BaGet.Protocol/Catalog/ICatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/ICatalogClient.cs @@ -2,55 +2,54 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The Catalog client, used to discover package events. +/// You can use this resource to query for all published packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource +/// +public interface ICatalogClient { /// - /// The Catalog client, used to discover package events. - /// You can use this resource to query for all published packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource + /// Get the entry point for the catalog resource. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index /// - public interface ICatalogClient - { - /// - /// Get the entry point for the catalog resource. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index - /// - /// A token to cancel the task. - /// The catalog index. - Task GetIndexAsync(CancellationToken cancellationToken = default); + /// A token to cancel the task. + /// The catalog index. + Task GetIndexAsync(CancellationToken cancellationToken = default); - /// - /// Get a single catalog page, used to discover catalog leafs. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page - /// - /// The URL of the page, from the . - /// A token to cancel the task. - /// A catalog page. - Task GetPageAsync( - string pageUrl, - CancellationToken cancellationToken = default); + /// + /// Get a single catalog page, used to discover catalog leafs. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page + /// + /// The URL of the page, from the . + /// A token to cancel the task. + /// A catalog page. + Task GetPageAsync( + string? pageUrl, + CancellationToken cancellationToken = default); - /// - /// Get a single catalog leaf, representing a package deletion event. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - /// The URL of the leaf, from a . - /// A token to cancel the task. - /// A catalog leaf. - Task GetPackageDeleteLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default); + /// + /// Get a single catalog leaf, representing a package deletion event. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// + /// The URL of the leaf, from a . + /// A token to cancel the task. + /// A catalog leaf. + Task GetPackageDeleteLeafAsync( + string? leafUrl, + CancellationToken cancellationToken = default); - /// - /// Get a single catalog leaf, representing a package creation or update event. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - /// The URL of the leaf, from a . - /// A token to cancel the task. - /// A catalog leaf. - Task GetPackageDetailsLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default); - } -} + /// + /// Get a single catalog leaf, representing a package creation or update event. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// + /// The URL of the leaf, from a . + /// A token to cancel the task. + /// A catalog leaf. + Task GetPackageDetailsLeafAsync( + string? leafUrl, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs b/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs index c45641a72..ca4875d34 100644 --- a/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs +++ b/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs @@ -2,37 +2,36 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// An interface which allows custom processing of catalog leaves. This interface should be implemented when the +/// catalog leaf documents need to be downloaded and processed in chronological order. +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Protocol.Catalog/ICatalogLeafProcessor.cs +/// +public interface ICatalogLeafProcessor { /// - /// An interface which allows custom processing of catalog leaves. This interface should be implemented when the - /// catalog leaf documents need to be downloaded and processed in chronological order. - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Protocol.Catalog/ICatalogLeafProcessor.cs + /// Process a catalog leaf containing package details. This method should return false or throw an exception + /// if the catalog leaf cannot be processed. In this case, the will stop + /// processing items. Note that the same package ID/version combination can be passed to this multiple times, + /// for example due to an edit in the package metadata or due to a transient error and retry on the part of the + /// . /// - public interface ICatalogLeafProcessor - { - /// - /// Process a catalog leaf containing package details. This method should return false or throw an exception - /// if the catalog leaf cannot be processed. In this case, the will stop - /// processing items. Note that the same package ID/version combination can be passed to this multiple times, - /// for example due to an edit in the package metadata or due to a transient error and retry on the part of the - /// . - /// - /// The leaf document. - /// A token to cancel the task. - /// True, if the leaf was successfully processed. False, otherwise. - Task ProcessPackageDetailsAsync(PackageDetailsCatalogLeaf leaf, CancellationToken cancellationToken = default); + /// The leaf document. + /// A token to cancel the task. + /// True, if the leaf was successfully processed. False, otherwise. + Task ProcessPackageDetailsAsync(PackageDetailsCatalogLeaf leaf, CancellationToken cancellationToken = default); - /// - /// Process a catalog leaf containing a package delete. This method should return false or throw an exception - /// if the catalog leaf cannot be processed. In this case, the will stop - /// processing items. Note that the same package ID/version combination can be passed to this multiple times, - /// for example due to a package being deleted again due to a transient error and retry on the part of the - /// . - /// - /// The leaf document. - /// A token to cancel the task. - /// True, if the leaf was successfully processed. False, otherwise. - Task ProcessPackageDeleteAsync(PackageDeleteCatalogLeaf leaf, CancellationToken cancellationToken = default); - } -} + /// + /// Process a catalog leaf containing a package delete. This method should return false or throw an exception + /// if the catalog leaf cannot be processed. In this case, the will stop + /// processing items. Note that the same package ID/version combination can be passed to this multiple times, + /// for example due to a package being deleted again due to a transient error and retry on the part of the + /// . + /// + /// The leaf document. + /// A token to cancel the task. + /// True, if the leaf was successfully processed. False, otherwise. + Task ProcessPackageDeleteAsync(PackageDeleteCatalogLeaf leaf, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/ICursor.cs b/src/BaGet.Protocol/Catalog/ICursor.cs index a564f8c59..f30eceffa 100644 --- a/src/BaGet.Protocol/Catalog/ICursor.cs +++ b/src/BaGet.Protocol/Catalog/ICursor.cs @@ -2,29 +2,28 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// The NuGet Catalog resource is an append-only data structure indexed by time. +/// The tracks up to what point in the catalog has been successfully +/// processed. The value is a catalog commit timestamp. +/// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#cursor +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/ICursor.cs +/// +public interface ICursor { /// - /// The NuGet Catalog resource is an append-only data structure indexed by time. - /// The tracks up to what point in the catalog has been successfully - /// processed. The value is a catalog commit timestamp. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#cursor - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/ICursor.cs + /// Get the value of the cursor. /// - public interface ICursor - { - /// - /// Get the value of the cursor. - /// - /// A token to cancel the task. - /// The cursor value. Null if the cursor has no value yet. - Task GetAsync(CancellationToken cancellationToken = default); + /// A token to cancel the task. + /// The cursor value. Null if the cursor has no value yet. + Task GetAsync(CancellationToken cancellationToken = default); - /// - /// Set the value of the cursor. - /// - /// The new cursor value. - /// A token to cancel the task. - Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default); - } -} + /// + /// Set the value of the cursor. + /// + /// The new cursor value. + /// A token to cancel the task. + Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/NullCatalogClient.cs b/src/BaGet.Protocol/Catalog/NullCatalogClient.cs index b77dc15b0..4c0cbbe1b 100644 --- a/src/BaGet.Protocol/Catalog/NullCatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/NullCatalogClient.cs @@ -4,33 +4,32 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +public class NullCatalogClient : ICatalogClient { - public class NullCatalogClient : ICatalogClient + public Task GetIndexAsync(CancellationToken cancellationToken = default) { - public Task GetIndexAsync(CancellationToken cancellationToken = default) + return Task.FromResult(new CatalogIndex { - return Task.FromResult(new CatalogIndex - { - CommitTimestamp = DateTimeOffset.MinValue, - Count = 0, - Items = new List() - }); - } + CommitTimestamp = DateTimeOffset.MinValue, + Count = 0, + Items = new List() + }); + } - public Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) - { - throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog pages."); - } + public Task GetPageAsync(string? pageUrl, CancellationToken cancellationToken = default) + { + throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog pages."); + } - public Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); - } + public Task GetPackageDeleteLeafAsync(string? leafUrl, CancellationToken cancellationToken = default) + { + throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); + } - public Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); - } + public Task GetPackageDetailsLeafAsync(string? leafUrl, CancellationToken cancellationToken = default) + { + throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/NullCursor.cs b/src/BaGet.Protocol/Catalog/NullCursor.cs index 8af2f2f57..91b03530c 100644 --- a/src/BaGet.Protocol/Catalog/NullCursor.cs +++ b/src/BaGet.Protocol/Catalog/NullCursor.cs @@ -2,23 +2,22 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// A cursor that does not persist any state. Use this with a +/// to process all leafs each time +/// is called. +/// +public class NullCursor : ICursor { - /// - /// A cursor that does not persist any state. Use this with a - /// to process all leafs each time - /// is called. - /// - public class NullCursor : ICursor + public Task GetAsync(CancellationToken cancellationToken = default) { - public Task GetAsync(CancellationToken cancellationToken = default) - { - return Task.FromResult(null); - } + return Task.FromResult(null); + } - public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default) + { + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/RawCatalogClient.cs b/src/BaGet.Protocol/Catalog/RawCatalogClient.cs index d773e3654..782e3c5d5 100644 --- a/src/BaGet.Protocol/Catalog/RawCatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/RawCatalogClient.cs @@ -5,60 +5,59 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +public class RawCatalogClient : ICatalogClient { - public class RawCatalogClient : ICatalogClient + private readonly HttpClient _httpClient; + private readonly string _catalogUrl; + + public RawCatalogClient(HttpClient? httpClient, string catalogUrl) { - private readonly HttpClient _httpClient; - private readonly string _catalogUrl; + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _catalogUrl = catalogUrl ?? throw new ArgumentNullException(nameof(catalogUrl)); + } - public RawCatalogClient(HttpClient httpClient, string catalogUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _catalogUrl = catalogUrl ?? throw new ArgumentNullException(nameof(catalogUrl)); - } + public async Task GetIndexAsync(CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(_catalogUrl, cancellationToken); + } - public async Task GetIndexAsync(CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(_catalogUrl, cancellationToken); - } + public async Task GetPageAsync(string? pageUrl, CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); + } - public async Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); - } + public async Task GetPackageDeleteLeafAsync(string? leafUrl, CancellationToken cancellationToken = default) + { + return await GetAndValidateLeafAsync( + "PackageDelete", + leafUrl, + cancellationToken); + } - public async Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - return await GetAndValidateLeafAsync( - "PackageDelete", - leafUrl, - cancellationToken); - } + public async Task GetPackageDetailsLeafAsync(string? leafUrl, CancellationToken cancellationToken = default) + { + return await GetAndValidateLeafAsync( + "PackageDetails", + leafUrl, + cancellationToken); + } - public async Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - return await GetAndValidateLeafAsync( - "PackageDetails", - leafUrl, - cancellationToken); - } + private async Task GetAndValidateLeafAsync( + string leafType, + string? leafUrl, + CancellationToken cancellationToken) where TCatalogLeaf : CatalogLeaf + { + var leaf = await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); - private async Task GetAndValidateLeafAsync( - string leafType, - string leafUrl, - CancellationToken cancellationToken) where TCatalogLeaf : CatalogLeaf + if (leaf.Type?.FirstOrDefault() != leafType) { - var leaf = await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); - - if (leaf.Type.FirstOrDefault() != leafType) - { - throw new ArgumentException( - $"The leaf type found in the document does not match the expected '{leafType}' type.", - nameof(leafType)); - } - - return leaf; + throw new ArgumentException( + $"The leaf type found in the document does not match the expected '{leafType}' type.", + nameof(leafType)); } + + return leaf; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs b/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs index 9514cb5d5..cf0708d1e 100644 --- a/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs +++ b/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs @@ -2,56 +2,55 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// This is an internal API that may be changed or removed without notice in any release. +/// +public class PackageDependencyRangeJsonConverter : JsonConverter { - /// - /// This is an internal API that may be changed or removed without notice in any release. - /// - public class PackageDependencyRangeJsonConverter : JsonConverter + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + if (reader.TokenType == JsonTokenType.String) { - if (reader.TokenType == JsonTokenType.String) - { - return reader.GetString(); - } + return reader.GetString(); + } + + // There are some quirky packages with arrays of dependency version ranges. + // In this case, we take the first element. + // Example: https://api.nuget.org/v3/catalog0/data/2016.02.21.11.06.01/dingu.generic.repo.ef7.1.0.0-beta2.json + if (reader.TokenType != JsonTokenType.StartArray) + { + throw new JsonException(); + } + + reader.Read(); + if (reader.TokenType != JsonTokenType.String) + { + throw new JsonException(); + } + + var result = reader.GetString(); - // There are some quirky packages with arrays of dependency version ranges. - // In this case, we take the first element. - // Example: https://api.nuget.org/v3/catalog0/data/2016.02.21.11.06.01/dingu.generic.repo.ef7.1.0.0-beta2.json - if (reader.TokenType != JsonTokenType.StartArray) + // Ignore all other strings until we reach the end of the array. + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndArray) { - throw new JsonException(); + break; } - reader.Read(); if (reader.TokenType != JsonTokenType.String) { throw new JsonException(); } - - var result = reader.GetString(); - - // Ignore all other strings until we reach the end of the array. - while (reader.Read()) - { - if (reader.TokenType == JsonTokenType.EndArray) - { - break; - } - - if (reader.TokenType != JsonTokenType.String) - { - throw new JsonException(); - } - } - - return result; } - public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) - { - writer.WriteStringValue(value); - } + return result; + } + + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs b/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs index d4ea42e04..fad3b9b31 100644 --- a/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs +++ b/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs @@ -3,58 +3,61 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// This is an internal API that may be changed or removed without notice in any release. +/// +public class StringOrStringArrayJsonConverter : JsonConverter> { - /// - /// This is an internal API that may be changed or removed without notice in any release. - /// - public class StringOrStringArrayJsonConverter : JsonConverter> + public override IReadOnlyList Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - public override IReadOnlyList Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + // Try to read a single string first. + if (reader.TokenType == JsonTokenType.String) + { + #pragma warning disable CS8604 + return new List { reader.GetString() }; + #pragma warning restore CS8604 + } + + // Try to read an array of strings. + if (reader.TokenType != JsonTokenType.StartArray) + { + throw new JsonException(); + } + + var result = new List(); + + while (reader.Read()) { - // Try to read a single string first. if (reader.TokenType == JsonTokenType.String) { - return new List { reader.GetString() }; + result.Add(reader.GetString()); } - - // Try to read an array of strings. - if (reader.TokenType != JsonTokenType.StartArray) + else if (reader.TokenType == JsonTokenType.EndArray) { - throw new JsonException(); + #pragma warning disable CS8619 + return result; + #pragma warning restore CS8619 } - - var result = new List(); - - while (reader.Read()) + else { - if (reader.TokenType == JsonTokenType.String) - { - result.Add(reader.GetString()); - } - else if (reader.TokenType == JsonTokenType.EndArray) - { - return result; - } - else - { - break; - } + break; } - - throw new JsonException(); } - public override void Write(Utf8JsonWriter writer, IReadOnlyList values, JsonSerializerOptions options) - { - writer.WriteStartArray(); + throw new JsonException(); + } - foreach (var value in values) - { - writer.WriteStringValue(value); - } + public override void Write(Utf8JsonWriter writer, IReadOnlyList values, JsonSerializerOptions options) + { + writer.WriteStartArray(); - writer.WriteEndArray(); + foreach (var value in values) + { + writer.WriteStringValue(value); } + + writer.WriteEndArray(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/EndpointFailover.cs b/src/BaGet.Protocol/EndpointFailover.cs new file mode 100644 index 000000000..7b3013d54 --- /dev/null +++ b/src/BaGet.Protocol/EndpointFailover.cs @@ -0,0 +1,133 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Runtime.ExceptionServices; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Protocol.Internal; + +/// +/// Runs an operation against the endpoints a service index advertises for one resource, +/// moving on to the next endpoint when an endpoint proves unusable. +/// +/// Only a failure of the endpoint itself causes a failover. A response that the server +/// produced is its answer, not a broken endpoint: a 404 means "there is nothing here" and +/// must never be retried elsewhere, or a missing package would be reported as an outage and +/// every request would cost one round trip per endpoint. +/// +internal static class EndpointFailover +{ + /// + /// Run against the first endpoint that can serve it. + /// + /// The client type, one per endpoint. + /// The operation's result. + /// The resource's clients, in the order they should be tried. + /// The operation to run against an endpoint. + /// A token to cancel the task. + /// The result from the first endpoint that answered. + /// + /// Every endpoint failed, and there was more than one. The inner exceptions are each + /// endpoint's failure, in the order the endpoints were tried. + /// + public static async Task ExecuteAsync( + IReadOnlyList? clients, + Func> operation, + CancellationToken cancellationToken) + { + if (clients == null) throw new ArgumentNullException(nameof(clients)); + if (operation == null) throw new ArgumentNullException(nameof(operation)); + + if (clients.Count == 0) + { + throw new InvalidOperationException( + "The service index does not advertise any endpoint for this resource"); + } + + List? failures = null; + + foreach (var client in clients) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + return await operation(client, cancellationToken); + } + catch (Exception exception) when (IsEndpointFailure(exception, cancellationToken)) + { + failures = failures ?? new List(clients.Count); + failures.Add(exception); + } + } + + // Every endpoint failed. A resource with a single endpoint - by far the common case - + // keeps throwing exactly what that endpoint threw, so that existing error handling + // still works. Several endpoints report every failure, as knowing why each endpoint + // was unusable is the only way to tell a local network problem from a server outage. + if (failures?.Count == 1) + { + #pragma warning disable CS8604 + ExceptionDispatchInfo.Capture(failures?[0]).Throw(); + #pragma warning restore CS8604 + } + + #pragma warning disable CS8604 + throw new AggregateException( + $"All {failures?.Count} endpoints for this resource failed", + failures); + #pragma warning restore CS8604 + } + + /// + /// Whether a failure means the endpoint is unusable, so the next endpoint should be tried. + /// + internal static bool IsEndpointFailure(Exception exception, CancellationToken cancellationToken) + { + switch (exception) + { + // A transport failure - an unresolvable host, a refused connection, a TLS error, + // a dropped response - carries no status code: the endpoint never answered. + case HttpRequestException httpException: + return httpException.StatusCode == null + || IsEndpointFailure(httpException.StatusCode.Value); + + // HttpClient reports its own timeout as a cancellation. A cancellation the caller + // asked for is not an endpoint failure and must reach the caller untouched. + case OperationCanceledException _: + return !cancellationToken.IsCancellationRequested; + + case TimeoutException _: + return true; + + // A connection dropped while the response body was being read surfaces as an + // IOException - HttpIOException derives from it - rather than an + // HttpRequestException, because the request itself had already succeeded. + case IOException _: + return true; + + // The endpoint answered with something that is not the resource it advertised. + case JsonException _: + return true; + + default: + return false; + } + } + + private static bool IsEndpointFailure(HttpStatusCode statusCode) + { + var code = (int)statusCode; + + // The endpoint is reachable but cannot serve the request now, which is exactly what a + // second endpoint is for. Every other status - 404 included - is the server's answer. + if (code == (int)HttpStatusCode.RequestTimeout) return true; + if (code == 429 /* Too Many Requests */) return true; + + return code >= 500 && code <= 599; + } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs b/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs index 66f18ffd3..0c484c71f 100644 --- a/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs @@ -5,242 +5,249 @@ using NuGet.Frameworks; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the catalog API. +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ModelExtensions.cs +/// +public static class CatalogModelExtensions { /// - /// These are documented interpretations of values returned by the catalog API. - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ModelExtensions.cs + /// Gets the leaves that lie within the provided commit timestamp bounds. The result is sorted by commit + /// timestamp, then package ID, then package version (SemVer order). /// - public static class CatalogModelExtensions + /// + /// The exclusive lower time bound on . + /// The inclusive upper time bound on . + /// Only show the latest leaf concerning each package. + public static List GetLeavesInBounds( + this CatalogPage catalogPage, + DateTimeOffset minCommitTimestamp, + DateTimeOffset maxCommitTimestamp, + bool excludeRedundantLeaves) { - /// - /// Gets the leaves that lie within the provided commit timestamp bounds. The result is sorted by commit - /// timestamp, then package ID, then package version (SemVer order). - /// - /// - /// The exclusive lower time bound on . - /// The inclusive upper time bound on . - /// Only show the latest leaf concerning each package. - public static List GetLeavesInBounds( - this CatalogPage catalogPage, - DateTimeOffset minCommitTimestamp, - DateTimeOffset maxCommitTimestamp, - bool excludeRedundantLeaves) + #pragma warning disable CS8604 + var leaves = catalogPage + .Items + .Where(x => x.CommitTimestamp > minCommitTimestamp && x.CommitTimestamp <= maxCommitTimestamp) + .OrderBy(x => x.CommitTimestamp); + #pragma warning restore CS8604 + + if (excludeRedundantLeaves) { - var leaves = catalogPage - .Items - .Where(x => x.CommitTimestamp > minCommitTimestamp && x.CommitTimestamp <= maxCommitTimestamp) + leaves = leaves + .GroupBy(x => new + { + PackageId = x.PackageId?.ToLowerInvariant(), + PackageVersion = x.ParsePackageVersion() + }) + .Select(x => x.Last()) .OrderBy(x => x.CommitTimestamp); - - if (excludeRedundantLeaves) - { - leaves = leaves - .GroupBy(x => new - { - PackageId = x.PackageId.ToLowerInvariant(), - PackageVersion = x.ParsePackageVersion() - }) - .Select(x => x.Last()) - .OrderBy(x => x.CommitTimestamp); - } - - return leaves - .ThenBy(x => x.PackageId, StringComparer.OrdinalIgnoreCase) - .ThenBy(x => x.ParsePackageVersion()) - .ToList(); } - /// - /// Gets the pages that may have catalog leaves within the provided commit timestamp bounds. The result is - /// sorted by commit timestamp. - /// - /// The catalog index to fetch pages from. - /// The exclusive lower time bound on . - /// The inclusive upper time bound on . - public static List GetPagesInBounds( - this CatalogIndex catalogIndex, - DateTimeOffset minCommitTimestamp, - DateTimeOffset maxCommitTimestamp) - { - return catalogIndex - .GetPagesInBoundsLazy(minCommitTimestamp, maxCommitTimestamp) - .ToList(); - } + return leaves + .ThenBy(x => x.PackageId, StringComparer.OrdinalIgnoreCase) + .ThenBy(x => x.ParsePackageVersion()) + .ToList(); + } - private static IEnumerable GetPagesInBoundsLazy( - this CatalogIndex catalogIndex, - DateTimeOffset minCommitTimestamp, - DateTimeOffset maxCommitTimestamp) + /// + /// Gets the pages that may have catalog leaves within the provided commit timestamp bounds. The result is + /// sorted by commit timestamp. + /// + /// The catalog index to fetch pages from. + /// The exclusive lower time bound on . + /// The inclusive upper time bound on . + public static List GetPagesInBounds( + this CatalogIndex catalogIndex, + DateTimeOffset minCommitTimestamp, + DateTimeOffset maxCommitTimestamp) + { + return catalogIndex + .GetPagesInBoundsLazy(minCommitTimestamp, maxCommitTimestamp) + .ToList(); + } + + private static IEnumerable GetPagesInBoundsLazy( + this CatalogIndex catalogIndex, + DateTimeOffset minCommitTimestamp, + DateTimeOffset maxCommitTimestamp) + { + // Filter out pages that fall entirely before the minimum commit timestamp and sort the remaining pages by + // commit timestamp. + #pragma warning disable CS8604 + var upperRange = catalogIndex + .Items + .Where(x => x.CommitTimestamp > minCommitTimestamp) + .OrderBy(x => x.CommitTimestamp); + #pragma warning restore CS8604 + + // Take pages from the sorted list until the commit timestamp goes past the maximum commit timestamp. This + // essentially LINQ's TakeWhile plus one more element. + foreach (var page in upperRange) { - // Filter out pages that fall entirely before the minimum commit timestamp and sort the remaining pages by - // commit timestamp. - var upperRange = catalogIndex - .Items - .Where(x => x.CommitTimestamp > minCommitTimestamp) - .OrderBy(x => x.CommitTimestamp); + yield return page; - // Take pages from the sorted list until the commit timestamp goes past the maximum commit timestamp. This - // essentially LINQ's TakeWhile plus one more element. - foreach (var page in upperRange) + if (page.CommitTimestamp > maxCommitTimestamp) { - yield return page; - - if (page.CommitTimestamp > maxCommitTimestamp) - { - break; - } + break; } } + } - /// - /// Parse the package version as a . - /// - /// The catalog leaf. - /// The package version. - public static NuGetVersion ParsePackageVersion(this ICatalogLeafItem leaf) + /// + /// Parse the package version as a . + /// + /// The catalog leaf. + /// The package version. + public static NuGetVersion ParsePackageVersion(this ICatalogLeafItem leaf) + { + #pragma warning disable CS8604 + return NuGetVersion.Parse(leaf.PackageVersion); + #pragma warning restore CS8604 + } + + /// + /// Parse the target framework as a . + /// + /// The package dependency group. + /// The framework. + public static NuGetFramework ParseTargetFramework(this DependencyGroupItem packageDependencyGroup) + { + if (string.IsNullOrEmpty(packageDependencyGroup.TargetFramework)) { - return NuGetVersion.Parse(leaf.PackageVersion); + return NuGetFramework.AnyFramework; } - /// - /// Parse the target framework as a . - /// - /// The package dependency group. - /// The framework. - public static NuGetFramework ParseTargetFramework(this DependencyGroupItem packageDependencyGroup) - { - if (string.IsNullOrEmpty(packageDependencyGroup.TargetFramework)) - { - return NuGetFramework.AnyFramework; - } + return NuGetFramework.Parse(packageDependencyGroup.TargetFramework); + } - return NuGetFramework.Parse(packageDependencyGroup.TargetFramework); + /// + /// Parse the version range as a . + /// + /// The package dependency. + /// The version range. + public static VersionRange ParseRange(this DependencyItem packageDependency) + { + // Server side treats invalid version ranges as empty strings. + // Source: https://github.com/NuGet/NuGet.Services.Metadata/blob/382c214c60993edfd7158bc6d223fafeebbc920c/src/Catalog/Helpers/NuGetVersionUtility.cs#L25-L34 + // Client side treats empty string version ranges as the "all" range. + // Source: https://github.com/NuGet/NuGet.Client/blob/849063018d8ee08625774a2dcd07ab84224dabb9/src/NuGet.Core/NuGet.Protocol/DependencyInfo/RegistrationUtility.cs#L20-L30 + // Example: https://api.nuget.org/v3/catalog0/data/2016.03.14.21.19.28/servicestack.extras.serilog.2.0.1.json + #pragma warning disable CS8604 + if (!VersionRange.TryParse(packageDependency.Range, out var parsed)) + #pragma warning restore CS8604 + { + return VersionRange.All; } - /// - /// Parse the version range as a . - /// - /// The package dependency. - /// The version range. - public static VersionRange ParseRange(this DependencyItem packageDependency) - { - // Server side treats invalid version ranges as empty strings. - // Source: https://github.com/NuGet/NuGet.Services.Metadata/blob/382c214c60993edfd7158bc6d223fafeebbc920c/src/Catalog/Helpers/NuGetVersionUtility.cs#L25-L34 - // Client side treats empty string version ranges as the "all" range. - // Source: https://github.com/NuGet/NuGet.Client/blob/849063018d8ee08625774a2dcd07ab84224dabb9/src/NuGet.Core/NuGet.Protocol/DependencyInfo/RegistrationUtility.cs#L20-L30 - // Example: https://api.nuget.org/v3/catalog0/data/2016.03.14.21.19.28/servicestack.extras.serilog.2.0.1.json - if (!VersionRange.TryParse(packageDependency.Range, out var parsed)) - { - return VersionRange.All; - } + return parsed; + } - return parsed; - } + /// + /// Determines if the provided catalog leaf is a package delete. + /// + /// The catalog leaf. + /// True if the catalog leaf represents a package delete. + public static bool IsPackageDelete(this CatalogLeafItem leaf) + { + return leaf.Type == "nuget:PackageDelete"; + } - /// - /// Determines if the provided catalog leaf is a package delete. - /// - /// The catalog leaf. - /// True if the catalog leaf represents a package delete. - public static bool IsPackageDelete(this CatalogLeafItem leaf) - { - return leaf.Type == "nuget:PackageDelete"; - } + /// + /// Determines if the provided catalog leaf is a package delete. + /// + /// The catalog leaf. + /// True if the catalog leaf represents a package delete. + public static bool IsPackageDelete(this CatalogLeaf leaf) + { + return leaf.Type?.FirstOrDefault() == "PackageDelete"; + } - /// - /// Determines if the provided catalog leaf is a package delete. - /// - /// The catalog leaf. - /// True if the catalog leaf represents a package delete. - public static bool IsPackageDelete(this CatalogLeaf leaf) - { - return leaf.Type.FirstOrDefault() == "PackageDelete"; - } + /// + /// Determines if the provided catalog leaf is contains package details. + /// + /// The catalog leaf. + /// True if the catalog leaf contains package details. + public static bool IsPackageDetails(this CatalogLeafItem leaf) + { + return leaf.Type == "nuget:PackageDetails"; + } - /// - /// Determines if the provided catalog leaf is contains package details. - /// - /// The catalog leaf. - /// True if the catalog leaf contains package details. - public static bool IsPackageDetails(this CatalogLeafItem leaf) - { - return leaf.Type == "nuget:PackageDetails"; - } + /// + /// Determines if the provided catalog leaf is contains package details. + /// + /// The catalog leaf. + /// True if the catalog leaf contains package details. + public static bool IsPackageDetails(this CatalogLeaf leaf) + { + return leaf.Type?.FirstOrDefault() == "PackageDetails"; + } - /// - /// Determines if the provided catalog leaf is contains package details. - /// - /// The catalog leaf. - /// True if the catalog leaf contains package details. - public static bool IsPackageDetails(this CatalogLeaf leaf) + /// + /// Determines if the provided package details leaf represents a listed package. + /// + /// The catalog leaf. + /// True if the package is listed. + public static bool IsListed(this PackageDetailsCatalogLeaf leaf) + { + if (leaf.Listed.HasValue) { - return leaf.Type.FirstOrDefault() == "PackageDetails"; + return leaf.Listed.Value; } - /// - /// Determines if the provided package details leaf represents a listed package. - /// - /// The catalog leaf. - /// True if the package is listed. - public static bool IsListed(this PackageDetailsCatalogLeaf leaf) - { - if (leaf.Listed.HasValue) - { - return leaf.Listed.Value; - } + // A published year of 1900 indicates that this package is unlisted, when the listed property itself is + // not present (legacy behavior). + // Example: https://api.nuget.org/v3/catalog0/data/2015.02.01.06.22.45/antixss.4.0.1.json + return leaf.Published.Year != 1900; + } - // A published year of 1900 indicates that this package is unlisted, when the listed property itself is - // not present (legacy behavior). - // Example: https://api.nuget.org/v3/catalog0/data/2015.02.01.06.22.45/antixss.4.0.1.json - return leaf.Published.Year != 1900; + /// + /// Determines if the provied package details leaf represents a SemVer 2.0.0 package. A package is considered + /// SemVer 2.0.0 if it's version is SemVer 2.0.0 or one of its dependency version ranges is SemVer 2.0.0. + /// + /// The catalog leaf. + /// True if the package is SemVer 2.0.0. + public static bool IsSemVer2(this PackageDetailsCatalogLeaf leaf) + { + var parsedPackageVersion = leaf.ParsePackageVersion(); + if (parsedPackageVersion.IsSemVer2) + { + return true; } - /// - /// Determines if the provied package details leaf represents a SemVer 2.0.0 package. A package is considered - /// SemVer 2.0.0 if it's version is SemVer 2.0.0 or one of its dependency version ranges is SemVer 2.0.0. - /// - /// The catalog leaf. - /// True if the package is SemVer 2.0.0. - public static bool IsSemVer2(this PackageDetailsCatalogLeaf leaf) + if (leaf.VerbatimVersion != null) { - var parsedPackageVersion = leaf.ParsePackageVersion(); - if (parsedPackageVersion.IsSemVer2) + var parsedVerbatimVersion = NuGetVersion.Parse(leaf.VerbatimVersion); + if (parsedVerbatimVersion.IsSemVer2) { return true; } + } - if (leaf.VerbatimVersion != null) + if (leaf.DependencyGroups != null) + { + foreach (var dependencyGroup in leaf.DependencyGroups) { - var parsedVerbatimVersion = NuGetVersion.Parse(leaf.VerbatimVersion); - if (parsedVerbatimVersion.IsSemVer2) + // Example: https://api.nuget.org/v3/catalog0/data/2018.10.28.07.42.42/mvcsitemapprovider.3.3.0-pre1.json + if (dependencyGroup.Dependencies == null) { - return true; + continue; } - } - if (leaf.DependencyGroups != null) - { - foreach (var dependencyGroup in leaf.DependencyGroups) + foreach (var dependency in dependencyGroup.Dependencies) { - // Example: https://api.nuget.org/v3/catalog0/data/2018.10.28.07.42.42/mvcsitemapprovider.3.3.0-pre1.json - if (dependencyGroup.Dependencies == null) + var versionRange = dependency.ParseRange(); + if ((versionRange.MaxVersion != null && versionRange.MaxVersion.IsSemVer2) + || (versionRange.MinVersion != null && versionRange.MinVersion.IsSemVer2)) { - continue; - } - - foreach (var dependency in dependencyGroup.Dependencies) - { - var versionRange = dependency.ParseRange(); - if ((versionRange.MaxVersion != null && versionRange.MaxVersion.IsSemVer2) - || (versionRange.MinVersion != null && versionRange.MinVersion.IsSemVer2)) - { - return true; - } + return true; } } } - - return false; } + + return false; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs b/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs index 95db48fd0..2647616fb 100644 --- a/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs +++ b/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs @@ -4,70 +4,75 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +internal static class HttpClientExtensions { - internal static class HttpClientExtensions + /// + /// Deserialize JSON content. + /// + /// The JSON type to deserialize. + /// The HTTP client that will perform the request. + /// The request URI. + /// A token to cancel the task. + /// The deserialized JSON content + public static async Task GetFromJsonAsync( + this HttpClient httpClient, + string? requestUri, + CancellationToken cancellationToken = default) { - /// - /// Deserialize JSON content. - /// - /// The JSON type to deserialize. - /// The HTTP client that will perform the request. - /// The request URI. - /// A token to cancel the task. - /// The deserialized JSON content - public static async Task GetFromJsonAsync( - this HttpClient httpClient, - string requestUri, - CancellationToken cancellationToken = default) + using (var response = await httpClient.GetAsync( + requestUri, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken)) { - using (var response = await httpClient.GetAsync( - requestUri, - HttpCompletionOption.ResponseHeadersRead, - cancellationToken)) - { - // This is similar to System.Net.Http.Json's implementation, however, - // this does not validate that the response's content type indicates JSON content. - response.EnsureSuccessStatusCode(); + // This is similar to System.Net.Http.Json's implementation, however, + // this does not validate that the response's content type indicates JSON content. + response.EnsureSuccessStatusCode(); - using (var stream = await response.Content.ReadAsStreamAsync()) - { - return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); - } + using (var stream = await response.Content.ReadAsStreamAsync()) + { + #pragma warning disable CS8603 + return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); + #pragma warning restore CS8603 } } + } - /// - /// Deserialize JSON content. If the HTTP response status code is 404, - /// returns the default value. - /// - /// The JSON type to deserialize. - /// The HTTP client that will perform the request. - /// The request URI. - /// A token to cancel the task. - /// The JSON content, or, the default value if the HTTP response status code is 404. - public static async Task GetFromJsonOrDefaultAsync( - this HttpClient httpClient, - string requestUri, - CancellationToken cancellationToken = default) + /// + /// Deserialize JSON content. If the HTTP response status code is 404, + /// returns the default value. + /// + /// The JSON type to deserialize. + /// The HTTP client that will perform the request. + /// The request URI. + /// A token to cancel the task. + /// The JSON content, or, the default value if the HTTP response status code is 404. + public static async Task GetFromJsonOrDefaultAsync( + this HttpClient httpClient, + string requestUri, + CancellationToken cancellationToken = default) + { + using (var response = await httpClient.GetAsync( + requestUri, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken)) { - using (var response = await httpClient.GetAsync( - requestUri, - HttpCompletionOption.ResponseHeadersRead, - cancellationToken)) + if (response.StatusCode == HttpStatusCode.NotFound) { - if (response.StatusCode == HttpStatusCode.NotFound) - { - return default; - } + #pragma warning disable CS8603 + return default; + #pragma warning restore CS8603 + } - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); - using (var stream = await response.Content.ReadAsStreamAsync()) - { - return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); - } + using (var stream = await response.Content.ReadAsStreamAsync()) + { + #pragma warning disable CS8603 + return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); + #pragma warning restore CS8603 } } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs b/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs index 5a17073d8..0efd38764 100644 --- a/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs +++ b/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs @@ -1,35 +1,34 @@ using BaGet.Protocol.Catalog; using Microsoft.Extensions.Logging; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public static class NuGetClientFactoryExtensions { - public static class NuGetClientFactoryExtensions + /// + /// Create a new to discover and download catalog leafs. + /// Leafs are processed by the . + /// + /// The factory used to create NuGet clients. + /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. + /// The leaf processor. + /// The options to configure catalog processing. + /// The logger used for telemetry. + /// The catalog processor. + public static CatalogProcessor CreateCatalogProcessor( + this NuGetClientFactory clientFactory, + ICursor cursor, + ICatalogLeafProcessor leafProcessor, + CatalogProcessorOptions options, + ILogger logger) { - /// - /// Create a new to discover and download catalog leafs. - /// Leafs are processed by the . - /// - /// The factory used to create NuGet clients. - /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. - /// The leaf processor. - /// The options to configure catalog processing. - /// The logger used for telemetry. - /// The catalog processor. - public static CatalogProcessor CreateCatalogProcessor( - this NuGetClientFactory clientFactory, - ICursor cursor, - ICatalogLeafProcessor leafProcessor, - CatalogProcessorOptions options, - ILogger logger) - { - var catalogClient = clientFactory.CreateCatalogClient(); + var catalogClient = clientFactory.CreateCatalogClient(); - return new CatalogProcessor( - cursor, - catalogClient, - leafProcessor, - options, - logger); - } + return new CatalogProcessor( + cursor, + catalogClient, + leafProcessor, + options, + logger); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs b/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs index 0a026cdf9..0c8d97489 100644 --- a/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs @@ -3,24 +3,25 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the Package Content resource. +/// +public static class PackageContentModelExtensions { /// - /// These are documented interpretations of values returned by the Package Content resource. + /// Parse the package versions as s. /// - public static class PackageContentModelExtensions + /// The package versions response. + /// The package versions. + public static IReadOnlyList ParseVersions(this PackageVersionsResponse response) { - /// - /// Parse the package versions as s. - /// - /// The package versions response. - /// The package versions. - public static IReadOnlyList ParseVersions(this PackageVersionsResponse response) - { - return response - .Versions - .Select(NuGetVersion.Parse) - .ToList(); - } + #pragma warning disable CS8604 + return response + .Versions + .Select(NuGetVersion.Parse) + .ToList(); + #pragma warning restore CS8604 } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs b/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs index 65947846b..ef3b7fd0a 100644 --- a/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs @@ -1,59 +1,64 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the +/// Package Metadata resource API. +/// +public static class RegistrationModelExtensions { /// - /// These are documented interpretations of values returned by the - /// Package Metadata resource API. + /// Parse the package version as a . /// - public static class RegistrationModelExtensions + /// The package metadata. + /// The package version. + public static NuGetVersion ParseVersion(this PackageMetadata? package) { - /// - /// Parse the package version as a . - /// - /// The package metadata. - /// The package version. - public static NuGetVersion ParseVersion(this PackageMetadata package) - { - return NuGetVersion.Parse(package.Version); - } + #pragma warning disable CS8604 + return NuGetVersion.Parse(package?.Version); + #pragma warning restore CS8604 + } - /// - /// Determines if the provided package metadata represents a listed package. - /// - /// The package metadata. - /// True if the package is listed. - public static bool IsListed(this PackageMetadata package) + /// + /// Determines if the provided package metadata represents a listed package. + /// + /// The package metadata. + /// True if the package is listed. + public static bool IsListed(this PackageMetadata package) + { + if (package.Listed.HasValue) { - if (package.Listed.HasValue) - { - return package.Listed.Value; - } - - // A published year of 1900 indicates that this package is unlisted, when the listed property itself is - // not present (legacy behavior). - return package.Published.Year != 1900; + return package.Listed.Value; } - /// - /// Parse the registration page's lower version as a . - /// - /// The registration page. - /// The page's lower version. - public static NuGetVersion ParseLower(this RegistrationIndexPage page) - { - return NuGetVersion.Parse(page.Lower); - } + // A published year of 1900 indicates that this package is unlisted, when the listed property itself is + // not present (legacy behavior). + return package.Published.Year != 1900; + } - /// - /// Parse the registration page's upper version as a . - /// - /// The registration page. - /// The page's upper version. - public static NuGetVersion ParseUpper(this RegistrationIndexPage page) - { - return NuGetVersion.Parse(page.Upper); - } + /// + /// Parse the registration page's lower version as a . + /// + /// The registration page. + /// The page's lower version. + public static NuGetVersion ParseLower(this RegistrationIndexPage page) + { + #pragma warning disable CS8604 + return NuGetVersion.Parse(page.Lower); + #pragma warning restore CS8604 + } + + /// + /// Parse the registration page's upper version as a . + /// + /// The registration page. + /// The page's upper version. + public static NuGetVersion ParseUpper(this RegistrationIndexPage page) + { + #pragma warning disable CS8604 + return NuGetVersion.Parse(page.Upper); + #pragma warning restore CS8604 } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs b/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs index e849ea777..023fa7f77 100644 --- a/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs @@ -1,31 +1,34 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the Search resource. +/// +public static class SearchModelExtensions { /// - /// These are documented interpretations of values returned by the Search resource. + /// Parse the search result's version as a . /// - public static class SearchModelExtensions + /// The search result. + /// The search result's version. + public static NuGetVersion ParseVersion(this SearchResult result) { - /// - /// Parse the search result's version as a . - /// - /// The search result. - /// The search result's version. - public static NuGetVersion ParseVersion(this SearchResult result) - { - return NuGetVersion.Parse(result.Version); - } + #pragma warning disable CS8604 + return NuGetVersion.Parse(result.Version); + #pragma warning restore CS8604 + } - /// - /// Parse the search result's version as a . - /// - /// The search result. - /// The search result's version. - public static NuGetVersion ParseVersion(this SearchResultVersion result) - { - return NuGetVersion.Parse(result.Version); - } + /// + /// Parse the search result's version as a . + /// + /// The search result. + /// The search result's version. + public static NuGetVersion ParseVersion(this SearchResultVersion result) + { + #pragma warning disable CS8604 + return NuGetVersion.Parse(result.Version); + #pragma warning restore CS8604 } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs b/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs index 7d0afea2e..1507dc058 100644 --- a/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs @@ -1,81 +1,141 @@ using System; +using System.Collections.Generic; using System.Linq; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the Service Index resource. +/// +public static class ServiceIndexModelExtensions { + // See: https://github.com/NuGet/NuGet.Client/blob/e08358296db5bfa6f7f32d6f4ec8de288f3b0388/src/NuGet.Core/NuGet.Protocol/ServiceTypes.cs + private static readonly string Version200 = "/2.0.0"; + private static readonly string Version300beta = "/3.0.0-beta"; + private static readonly string Version300 = "/3.0.0"; + private static readonly string Version340 = "/3.4.0"; + private static readonly string Version360 = "/3.6.0"; + private static readonly string Version470 = "/4.7.0"; + private static readonly string Version490 = "/4.9.0"; + private static readonly string Version500 = "/5.0.0"; + private static readonly string Version510 = "/5.1.0"; + + private static readonly string[] Catalog = { "Catalog" + Version300 }; + private static readonly string[] SearchQueryService = { "SearchQueryService" + Version340, "SearchQueryService" + Version300beta, "SearchQueryService" }; + private static readonly string[] RegistrationsBaseUrl = { "RegistrationsBaseUrl" + Version360, "RegistrationsBaseUrl" + Version340, "RegistrationsBaseUrl" + Version300beta, "RegistrationsBaseUrl" }; + private static readonly string[] SearchAutocompleteService = { "SearchAutocompleteService", "SearchAutocompleteService" + Version300beta }; + private static readonly string[] ReportAbuse = { "ReportAbuseUriTemplate", "ReportAbuseUriTemplate" + Version300 }; + private static readonly string[] PackageDetailsUriTemplate = { "PackageDetailsUriTemplate" + Version510 }; + private static readonly string[] LegacyGallery = { "LegacyGallery" + Version200 }; + private static readonly string[] PackagePublish = { "PackagePublish" + Version200 }; + private static readonly string[] PackageBaseAddress = { "PackageBaseAddress" + Version300 }; + private static readonly string[] RepositorySignatures = { "RepositorySignatures" + Version500, "RepositorySignatures" + Version490, "RepositorySignatures" + Version470 }; + private static readonly string[] SymbolPackagePublish = { "SymbolPackagePublish" + Version490 }; + + public static string? GetPackageContentResourceUrl(this ServiceIndexResponse? serviceIndex) + { + return serviceIndex.GetRequiredResourceUrl(PackageBaseAddress, nameof(PackageBaseAddress)); + } + + public static string? GetPackageMetadataResourceUrl(this ServiceIndexResponse? serviceIndex) + { + return serviceIndex.GetRequiredResourceUrl(RegistrationsBaseUrl, nameof(RegistrationsBaseUrl)); + } + + public static string? GetSearchQueryResourceUrl(this ServiceIndexResponse? serviceIndex) + { + return serviceIndex.GetRequiredResourceUrl(SearchQueryService, nameof(SearchQueryService)); + } + /// - /// These are documented interpretations of values returned by the Service Index resource. + /// All the Search resource's endpoints, in the order a client should try them. + /// A service index may advertise several endpoints for this resource. /// - public static class ServiceIndexModelExtensions + public static IReadOnlyList GetSearchQueryResourceUrls(this ServiceIndexResponse? serviceIndex) { - // See: https://github.com/NuGet/NuGet.Client/blob/e08358296db5bfa6f7f32d6f4ec8de288f3b0388/src/NuGet.Core/NuGet.Protocol/ServiceTypes.cs - private static readonly string Version200 = "/2.0.0"; - private static readonly string Version300beta = "/3.0.0-beta"; - private static readonly string Version300 = "/3.0.0"; - private static readonly string Version340 = "/3.4.0"; - private static readonly string Version360 = "/3.6.0"; - private static readonly string Version470 = "/4.7.0"; - private static readonly string Version490 = "/4.9.0"; - private static readonly string Version500 = "/5.0.0"; - private static readonly string Version510 = "/5.1.0"; - - private static readonly string[] Catalog = { "Catalog" + Version300 }; - private static readonly string[] SearchQueryService = { "SearchQueryService" + Version340, "SearchQueryService" + Version300beta, "SearchQueryService" }; - private static readonly string[] RegistrationsBaseUrl = { "RegistrationsBaseUrl" + Version360, "RegistrationsBaseUrl" + Version340, "RegistrationsBaseUrl" + Version300beta, "RegistrationsBaseUrl" }; - private static readonly string[] SearchAutocompleteService = { "SearchAutocompleteService", "SearchAutocompleteService" + Version300beta }; - private static readonly string[] ReportAbuse = { "ReportAbuseUriTemplate", "ReportAbuseUriTemplate" + Version300 }; - private static readonly string[] PackageDetailsUriTemplate = { "PackageDetailsUriTemplate" + Version510 }; - private static readonly string[] LegacyGallery = { "LegacyGallery" + Version200 }; - private static readonly string[] PackagePublish = { "PackagePublish" + Version200 }; - private static readonly string[] PackageBaseAddress = { "PackageBaseAddress" + Version300 }; - private static readonly string[] RepositorySignatures = { "RepositorySignatures" + Version500, "RepositorySignatures" + Version490, "RepositorySignatures" + Version470 }; - private static readonly string[] SymbolPackagePublish = { "SymbolPackagePublish" + Version490 }; - - public static string GetPackageContentResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetRequiredResourceUrl(PackageBaseAddress, nameof(PackageBaseAddress)); - } + return serviceIndex.GetRequiredResourceUrls(SearchQueryService, nameof(SearchQueryService)); + } - public static string GetPackageMetadataResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetRequiredResourceUrl(RegistrationsBaseUrl, nameof(RegistrationsBaseUrl)); - } + /// + /// All the Autocomplete resource's endpoints, in the order a client should try them. + /// The list is empty if the service index does not advertise this optional resource. + /// + public static IReadOnlyList GetSearchAutocompleteResourceUrls(this ServiceIndexResponse? serviceIndex) + { + return serviceIndex.GetResourceUrls(SearchAutocompleteService); + } - public static string GetSearchQueryResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetRequiredResourceUrl(SearchQueryService, nameof(SearchQueryService)); - } + public static string? GetCatalogResourceUrl(this ServiceIndexResponse? serviceIndex) + { + return serviceIndex.GetResourceUrl(Catalog); + } - public static string GetCatalogResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetResourceUrl(Catalog); - } + public static string? GetSearchAutocompleteResourceUrl(this ServiceIndexResponse? serviceIndex) + { + return serviceIndex.GetResourceUrl(SearchAutocompleteService); + } + + public static string? GetResourceUrl(this ServiceIndexResponse? serviceIndex, string[] types) + { + return serviceIndex.GetResourceUrls(types).FirstOrDefault(); + } + + /// + /// All the endpoints that the service index advertises for a resource, in the order a + /// client should try them: the most preferred resource type first and, within a type, + /// the order the service index itself used. + /// + /// A URL advertised under several of the resource's type versions is returned once, so + /// that a failover does not retry an endpoint that has already failed. + /// + /// The service index to read. + /// The resource's type identifiers, most preferred first. + /// The resource's endpoints. Empty if the resource is not advertised. + public static IReadOnlyList GetResourceUrls(this ServiceIndexResponse? serviceIndex, string[] types) + { + if (serviceIndex == null) throw new ArgumentNullException(nameof(serviceIndex)); + if (types == null) throw new ArgumentNullException(nameof(types)); - public static string GetSearchAutocompleteResourceUrl(this ServiceIndexResponse serviceIndex) + if (serviceIndex.Resources == null) { - return serviceIndex.GetResourceUrl(SearchAutocompleteService); + return Array.Empty(); } - public static string GetResourceUrl(this ServiceIndexResponse serviceIndex, string[] types) - { - var resource = types.SelectMany(t => serviceIndex.Resources.Where(r => r.Type == t)).FirstOrDefault(); + return types + .SelectMany(type => serviceIndex.Resources.Where(resource => resource.Type == type)) + .Select(resource => resource.ResourceUrl?.Trim('/')) + .Where(resourceUrl => !string.IsNullOrEmpty(resourceUrl)) + .Distinct(StringComparer.Ordinal) + .ToList(); + } - return resource?.ResourceUrl.Trim('/'); - } + public static string? GetRequiredResourceUrl(this ServiceIndexResponse? serviceIndex, string[] types, string resourceName) + { + return serviceIndex.GetRequiredResourceUrls(types, resourceName)[0]; + } - public static string GetRequiredResourceUrl(this ServiceIndexResponse serviceIndex, string[] types, string resourceName) + /// + /// All the endpoints that the service index advertises for a required resource. + /// + /// The service index to read. + /// The resource's type identifiers, most preferred first. + /// The resource's name, used in the error message. + /// The resource's endpoints, in the order a client should try them. + public static IReadOnlyList GetRequiredResourceUrls( + this ServiceIndexResponse? serviceIndex, + string[] types, + string resourceName) + { + // For more information on required resources, + // see: https://docs.microsoft.com/en-us/nuget/api/overview#resources-and-schema + var resourceUrls = serviceIndex.GetResourceUrls(types); + if (resourceUrls.Count == 0) { - // For more information on required resources, - // see: https://docs.microsoft.com/en-us/nuget/api/overview#resources-and-schema - var resourceUrl = serviceIndex.GetResourceUrl(types); - if (string.IsNullOrEmpty(resourceUrl)) - { - throw new InvalidOperationException( - $"The service index does not have a resource named '{resourceName}'"); - } - - return resourceUrl; + throw new InvalidOperationException( + $"The service index does not have a resource named '{resourceName}'"); } + + return resourceUrls; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/AlternatePackage.cs b/src/BaGet.Protocol/Models/AlternatePackage.cs index a5e272adc..bed2dfb49 100644 --- a/src/BaGet.Protocol/Models/AlternatePackage.cs +++ b/src/BaGet.Protocol/Models/AlternatePackage.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The alternate package that should be used instead of a deprecated package. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation +/// +public class AlternatePackage { - /// - /// The alternate package that should be used instead of a deprecated package. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation - /// - public class AlternatePackage - { - [JsonPropertyName("@id")] - public string Url { get; set; } + [JsonPropertyName("@id")] + public string? Url { get; set; } - [JsonPropertyName("@type")] - public string Type { get; set; } + [JsonPropertyName("@type")] + public string? Type { get; set; } - /// - /// The ID of the alternate package. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + /// + /// The ID of the alternate package. + /// + [JsonPropertyName("id")] + public string? Id { get; set; } - /// - /// The allowed version range, or * if any version is allowed. - /// - [JsonPropertyName("range")] - public string Range { get; set; } - } -} + /// + /// The allowed version range, or * if any version is allowed. + /// + [JsonPropertyName("range")] + public string? Range { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/AutocompleteContext.cs b/src/BaGet.Protocol/Models/AutocompleteContext.cs index 96b711c2f..ab3b4c37d 100644 --- a/src/BaGet.Protocol/Models/AutocompleteContext.cs +++ b/src/BaGet.Protocol/Models/AutocompleteContext.cs @@ -1,15 +1,14 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +public class AutocompleteContext { - public class AutocompleteContext + public static readonly AutocompleteContext Default = new() { - public static readonly AutocompleteContext Default = new AutocompleteContext - { - Vocab = "http://schema.nuget.org/schema#" - }; + Vocab = "http://schema.nuget.org/schema#" + }; - [JsonPropertyName("@vocab")] - public string Vocab { get; set; } - } -} + [JsonPropertyName("@vocab")] + public string? Vocab { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/AutocompleteResponse.cs b/src/BaGet.Protocol/Models/AutocompleteResponse.cs index 5522656fe..ee8d3e1f5 100644 --- a/src/BaGet.Protocol/Models/AutocompleteResponse.cs +++ b/src/BaGet.Protocol/Models/AutocompleteResponse.cs @@ -1,28 +1,27 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The package ids that matched the autocomplete query. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids +/// +public class AutocompleteResponse { + [JsonPropertyName("@context")] + public AutocompleteContext? Context { get; set; } + /// - /// The package ids that matched the autocomplete query. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids + /// The total number of matches, disregarding skip and take. /// - public class AutocompleteResponse - { - [JsonPropertyName("@context")] - public AutocompleteContext Context { get; set; } - - /// - /// The total number of matches, disregarding skip and take. - /// - [JsonPropertyName("totalHits")] - public long TotalHits { get; set; } + [JsonPropertyName("totalHits")] + public long TotalHits { get; set; } - /// - /// The package IDs matched by the autocomplete query. - /// - [JsonPropertyName("data")] - public IReadOnlyList Data { get; set; } - } -} + /// + /// The package IDs matched by the autocomplete query. + /// + [JsonPropertyName("data")] + public IReadOnlyList? Data { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogIndex.cs b/src/BaGet.Protocol/Models/CatalogIndex.cs index beeea373e..4a93b2c58 100644 --- a/src/BaGet.Protocol/Models/CatalogIndex.cs +++ b/src/BaGet.Protocol/Models/CatalogIndex.cs @@ -2,34 +2,32 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogIndex.cs +namespace BaGet.Protocol.Models; +// This class is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogIndex.cs +/// +/// The catalog index is the entry point for the catalog resource. +/// Use this to discover catalog pages, which in turn can be used to discover catalog leafs. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index +/// +public class CatalogIndex +{ /// - /// The catalog index is the entry point for the catalog resource. - /// Use this to discover catalog pages, which in turn can be used to discover catalog leafs. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index + /// A timestamp of the most recent commit. /// - public class CatalogIndex - { - /// - /// A timestamp of the most recent commit. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The number of catalog pages in the catalog index. - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of catalog pages in the catalog index. + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// The items used to discover s. - /// - [JsonPropertyName("items")] - public List Items { get; set; } - } -} + /// + /// The items used to discover s. + /// + [JsonPropertyName("items")] + public List? Items { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogLeaf.cs b/src/BaGet.Protocol/Models/CatalogLeaf.cs index f41ce62b9..dd4483e62 100644 --- a/src/BaGet.Protocol/Models/CatalogLeaf.cs +++ b/src/BaGet.Protocol/Models/CatalogLeaf.cs @@ -2,58 +2,56 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; +// This classed is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeaf.cs + +/// +/// A catalog leaf. Represents a single package event. +/// Leafs can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public class CatalogLeaf : ICatalogLeafItem { - // This classed is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeaf.cs + /// + /// The URL to the current catalog leaf. + /// + [JsonPropertyName("@id")] + public string? CatalogLeafUrl { get; set; } + + /// + /// The type of the current catalog leaf. + /// + [JsonPropertyName("@type")] + public IReadOnlyList? Type { get; set; } + + /// + /// The catalog commit ID associated with this catalog item. + /// + [JsonPropertyName("catalog:commitId")] + public string? CommitId { get; set; } + + /// + /// The commit timestamp of this catalog item. + /// + [JsonPropertyName("catalog:commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } + + /// + /// The package ID of the catalog item. + /// + [JsonPropertyName("id")] + public string? PackageId { get; set; } + + /// + /// The published date of the package catalog item. + /// + [JsonPropertyName("published")] + public DateTimeOffset Published { get; set; } /// - /// A catalog leaf. Represents a single package event. - /// Leafs can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// The package version of the catalog item. /// - public class CatalogLeaf : ICatalogLeafItem - { - /// - /// The URL to the current catalog leaf. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } - - /// - /// The type of the current catalog leaf. - /// - [JsonPropertyName("@type")] - public IReadOnlyList Type { get; set; } - - /// - /// The catalog commit ID associated with this catalog item. - /// - [JsonPropertyName("catalog:commitId")] - public string CommitId { get; set; } - - /// - /// The commit timestamp of this catalog item. - /// - [JsonPropertyName("catalog:commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } - - /// - /// The package ID of the catalog item. - /// - [JsonPropertyName("id")] - public string PackageId { get; set; } - - /// - /// The published date of the package catalog item. - /// - [JsonPropertyName("published")] - public DateTimeOffset Published { get; set; } - - /// - /// The package version of the catalog item. - /// - [JsonPropertyName("version")] - public string PackageVersion { get; set; } - } -} + [JsonPropertyName("version")] + public string? PackageVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogLeafItem.cs b/src/BaGet.Protocol/Models/CatalogLeafItem.cs index 36dcb940e..78b900086 100644 --- a/src/BaGet.Protocol/Models/CatalogLeafItem.cs +++ b/src/BaGet.Protocol/Models/CatalogLeafItem.cs @@ -1,45 +1,43 @@ using System; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeafItem.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeafItem.cs +/// +/// An item in a that references a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-item-object-in-a-page +/// +public class CatalogLeafItem : ICatalogLeafItem +{ /// - /// An item in a that references a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-item-object-in-a-page + /// The URL to the current catalog leaf. /// - public class CatalogLeafItem : ICatalogLeafItem - { - /// - /// The URL to the current catalog leaf. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string? CatalogLeafUrl { get; set; } - /// - /// The type of the current catalog leaf. - /// - [JsonPropertyName("@type")] - public string Type { get; set; } + /// + /// The type of the current catalog leaf. + /// + [JsonPropertyName("@type")] + public string? Type { get; set; } - /// - /// The commit timestamp of this catalog item. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + /// + /// The commit timestamp of this catalog item. + /// + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The package ID of the catalog item. - /// - [JsonPropertyName("nuget:id")] - public string PackageId { get; set; } + /// + /// The package ID of the catalog item. + /// + [JsonPropertyName("nuget:id")] + public string? PackageId { get; set; } - /// - /// The package version of the catalog item. - /// - [JsonPropertyName("nuget:version")] - public string PackageVersion { get; set; } - } -} + /// + /// The package version of the catalog item. + /// + [JsonPropertyName("nuget:version")] + public string? PackageVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogPage.cs b/src/BaGet.Protocol/Models/CatalogPage.cs index 65f9e6d3f..6ddf8a51c 100644 --- a/src/BaGet.Protocol/Models/CatalogPage.cs +++ b/src/BaGet.Protocol/Models/CatalogPage.cs @@ -2,40 +2,38 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPage.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPage.cs +/// +/// A catalog page, used to discover catalog leafs. +/// Pages can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page +/// +public class CatalogPage +{ /// - /// A catalog page, used to discover catalog leafs. - /// Pages can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page + /// A unique ID associated with the most recent commit in this page. /// - public class CatalogPage - { - /// - /// A unique ID associated with the most recent commit in this page. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The number of items in the page. - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of items in the page. + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// The items used to discover s. - /// - [JsonPropertyName("items")] - public List Items { get; set; } + /// + /// The items used to discover s. + /// + [JsonPropertyName("items")] + public List? Items { get; set; } - /// - /// The URL to the Catalog Index. - /// - [JsonPropertyName("parent")] - public string CatalogIndexUrl { get; set; } - } -} + /// + /// The URL to the Catalog Index. + /// + [JsonPropertyName("parent")] + public string? CatalogIndexUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogPageItem.cs b/src/BaGet.Protocol/Models/CatalogPageItem.cs index 0240d9e23..19473b0ab 100644 --- a/src/BaGet.Protocol/Models/CatalogPageItem.cs +++ b/src/BaGet.Protocol/Models/CatalogPageItem.cs @@ -1,33 +1,31 @@ using System; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPageItem.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPageItem.cs +/// +/// An item in the that references a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page-object-in-the-index +/// +public class CatalogPageItem +{ /// - /// An item in the that references a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page-object-in-the-index + /// The URL to this item's corresponding . /// - public class CatalogPageItem - { - /// - /// The URL to this item's corresponding . - /// - [JsonPropertyName("@id")] - public string CatalogPageUrl { get; set; } + [JsonPropertyName("@id")] + public string? CatalogPageUrl { get; set; } - /// - /// A timestamp of the most recent commit in this page. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + /// + /// A timestamp of the most recent commit in this page. + /// + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The number of items in the page. - /// - [JsonPropertyName("count")] - public int Count { get; set; } - } -} + /// + /// The number of items in the page. + /// + [JsonPropertyName("count")] + public int Count { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/DependencyGroupItem.cs b/src/BaGet.Protocol/Models/DependencyGroupItem.cs index e9626c053..0dc5ab285 100644 --- a/src/BaGet.Protocol/Models/DependencyGroupItem.cs +++ b/src/BaGet.Protocol/Models/DependencyGroupItem.cs @@ -1,25 +1,24 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The dependencies of the package for a specific target framework. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency-group +/// +public class DependencyGroupItem { /// - /// The dependencies of the package for a specific target framework. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency-group + /// The target framework that these dependencies are applicable to. /// - public class DependencyGroupItem - { - /// - /// The target framework that these dependencies are applicable to. - /// - [JsonPropertyName("targetFramework")] - public string TargetFramework { get; set; } + [JsonPropertyName("targetFramework")] + public string? TargetFramework { get; set; } - /// - /// A list of dependencies. - /// - [JsonPropertyName("dependencies")] - public List Dependencies { get; set; } - } -} + /// + /// A list of dependencies. + /// + [JsonPropertyName("dependencies")] + public List? Dependencies { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/DependencyItem.cs b/src/BaGet.Protocol/Models/DependencyItem.cs index 95af13012..2f37bff90 100644 --- a/src/BaGet.Protocol/Models/DependencyItem.cs +++ b/src/BaGet.Protocol/Models/DependencyItem.cs @@ -1,26 +1,25 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Internal; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// Represents a package dependency. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency +/// +public class DependencyItem { /// - /// Represents a package dependency. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency + /// The ID of the package dependency. /// - public class DependencyItem - { - /// - /// The ID of the package dependency. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + [JsonPropertyName("id")] + public string? Id { get; set; } - /// - /// The allowed version range of the dependency. - /// - [JsonPropertyName("range")] - [JsonConverter(typeof(PackageDependencyRangeJsonConverter))] - public string Range { get; set; } - } -} + /// + /// The allowed version range of the dependency. + /// + [JsonPropertyName("range")] + [JsonConverter(typeof(PackageDependencyRangeJsonConverter))] + public string? Range { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ICatalogLeafItem.cs b/src/BaGet.Protocol/Models/ICatalogLeafItem.cs index 2cd59a37f..5d99eaa48 100644 --- a/src/BaGet.Protocol/Models/ICatalogLeafItem.cs +++ b/src/BaGet.Protocol/Models/ICatalogLeafItem.cs @@ -1,30 +1,28 @@ using System; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ICatalogLeafItem.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ICatalogLeafItem.cs +/// +/// A catalog leaf. Represents a single package event. +/// Leafs can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public interface ICatalogLeafItem +{ /// - /// A catalog leaf. Represents a single package event. - /// Leafs can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// The commit timestamp of this catalog item. /// - public interface ICatalogLeafItem - { - /// - /// The commit timestamp of this catalog item. - /// - DateTimeOffset CommitTimestamp { get; } + DateTimeOffset CommitTimestamp { get; } - /// - /// The package ID of the catalog item. - /// - string PackageId { get; } + /// + /// The package ID of the catalog item. + /// + string? PackageId { get; } - /// - /// The package version of the catalog item. - /// - string PackageVersion { get; } - } -} + /// + /// The package version of the catalog item. + /// + string? PackageVersion { get; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs b/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs index da53173a4..90444cac0 100644 --- a/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs +++ b/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs @@ -1,14 +1,12 @@ -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDeleteCatalogLeaf.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDeleteCatalogLeaf.cs - /// - /// A "package delete" catalog leaf. Represents a single package deletion event. - /// Leafs can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - public class PackageDeleteCatalogLeaf : CatalogLeaf - { - } -} +/// +/// A "package delete" catalog leaf. Represents a single package deletion event. +/// Leafs can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public class PackageDeleteCatalogLeaf : CatalogLeaf +{ +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageDeprecation.cs b/src/BaGet.Protocol/Models/PackageDeprecation.cs index 9445ade2d..0ab42c84a 100644 --- a/src/BaGet.Protocol/Models/PackageDeprecation.cs +++ b/src/BaGet.Protocol/Models/PackageDeprecation.cs @@ -1,38 +1,37 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A package's metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation +/// +public class PackageDeprecation { /// - /// A package's metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation + /// The URL to the document used to produce this object. /// - public class PackageDeprecation - { - /// - /// The URL to the document used to produce this object. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string? CatalogLeafUrl { get; set; } - /// - /// The reasons why the package was deprecated. - /// Deprecation reasons include: "Legacy", "CriticalBugs", and "Other". - /// - [JsonPropertyName("reasons")] - public IReadOnlyList Reasons { get; set; } + /// + /// The reasons why the package was deprecated. + /// Deprecation reasons include: "Legacy", "CriticalBugs", and "Other". + /// + [JsonPropertyName("reasons")] + public IReadOnlyList? Reasons { get; set; } - /// - /// The additional details about this deprecation. - /// - [JsonPropertyName("message")] - public string Message { get; set; } + /// + /// The additional details about this deprecation. + /// + [JsonPropertyName("message")] + public string? Message { get; set; } - /// - /// The alternate package that should be used instead. - /// - [JsonPropertyName("alternatePackage")] - public AlternatePackage AlternatePackage { get; set; } - } -} + /// + /// The alternate package that should be used instead. + /// + [JsonPropertyName("alternatePackage")] + public AlternatePackage? AlternatePackage { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs b/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs index 5e8cf2575..1db234f39 100644 --- a/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs +++ b/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs @@ -2,169 +2,167 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDetailsCatalogLeaf.cs +/// +/// A "package details" catalog leaf. Represents a single package create or update event. +/// s can be discovered from a . +/// +/// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public class PackageDetailsCatalogLeaf : CatalogLeaf { - /// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDetailsCatalogLeaf.cs - - /// - /// A "package details" catalog leaf. Represents a single package create or update event. - /// s can be discovered from a . - /// - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - public class PackageDetailsCatalogLeaf : CatalogLeaf - { - /// - /// The package's authors. - /// - [JsonPropertyName("authors")] - public string Authors { get; set; } - - /// - /// The package's copyright. - /// - [JsonPropertyName("copyright")] - public string Copyright { get; set; } - - /// - /// A timestamp of when the package was first created. Fallback property: . - /// - [JsonPropertyName("created")] - public DateTimeOffset Created { get; set; } - - /// - /// A timestamp of when the package was last edited. - /// - [JsonPropertyName("lastEdited")] - public DateTimeOffset LastEdited { get; set; } - - /// - /// The dependencies of the package, grouped by target framework. - /// - [JsonPropertyName("dependencyGroups")] - public List DependencyGroups { get; set; } - - /// - /// The package's description. - /// - [JsonPropertyName("description")] - public string Description { get; set; } - - /// - /// The URL to the package's icon. - /// - [JsonPropertyName("iconUrl")] - public string IconUrl { get; set; } - - /// - /// Whether or not the package is prerelease. Can be detected from . - /// Note that the NuGet.org catalog had this wrong in some cases. - /// Example: https://api.nuget.org/v3/catalog0/data/2016.03.11.21.02.55/mvid.fody.2.json - /// - [JsonPropertyName("isPrerelease")] - public bool IsPrerelease { get; set; } - - /// - /// The package's language. - /// - [JsonPropertyName("language")] - public string Language { get; set; } - - /// - /// THe URL to the package's license. - /// - [JsonPropertyName("licenseUrl")] - public string LicenseUrl { get; set; } - - /// - /// Whether the pacakge is listed. - /// - [JsonPropertyName("listed")] - public bool? Listed { get; set; } - - /// - /// The minimum NuGet client version needed to use this package. - /// - [JsonPropertyName("minClientVersion")] - public string MinClientVersion { get; set; } - - /// - /// The hash of the package encoded using Base64. - /// Hash algorithm can be detected using . - /// - [JsonPropertyName("packageHash")] - public string PackageHash { get; set; } - - /// - /// The algorithm used to hash . - /// - [JsonPropertyName("packageHashAlgorithm")] - public string PackageHashAlgorithm { get; set; } - - /// - /// The size of the package .nupkg in bytes. - /// - [JsonPropertyName("packageSize")] - public long PackageSize { get; set; } - - /// - /// The URL for the package's home page. - /// - [JsonPropertyName("projectUrl")] - public string ProjectUrl { get; set; } - - /// - /// The package's release notes. - /// - [JsonPropertyName("releaseNotes")] - public string ReleaseNotes { get; set; } - - /// - /// If true, the package requires its license to be accepted. - /// - [JsonPropertyName("requireLicenseAcceptance")] - public bool? RequireLicenseAcceptance { get; set; } - - /// - /// The package's summary. - /// - [JsonPropertyName("summary")] - public string Summary { get; set; } - - /// - /// The package's tags. - /// - [JsonPropertyName("tags")] - public List Tags { get; set; } - - /// - /// The package's title. - /// - [JsonPropertyName("title")] - public string Title { get; set; } - - /// - /// The version string as it's originally found in the .nuspec. - /// - [JsonPropertyName("verbatimVersion")] - public string VerbatimVersion { get; set; } - - /// - /// The package's License Expression. - /// - [JsonPropertyName("licenseExpression")] - public string LicenseExpression { get; set; } - - /// - /// The package's license file. - /// - [JsonPropertyName("licenseFile")] - public string LicenseFile { get; set; } - - /// - /// The package's icon file. - /// - [JsonPropertyName("iconFile")] - public string IconFile { get; set; } - } -} + /// + /// The package's authors. + /// + [JsonPropertyName("authors")] + public string? Authors { get; set; } + + /// + /// The package's copyright. + /// + [JsonPropertyName("copyright")] + public string? Copyright { get; set; } + + /// + /// A timestamp of when the package was first created. Fallback property: . + /// + [JsonPropertyName("created")] + public DateTimeOffset Created { get; set; } + + /// + /// A timestamp of when the package was last edited. + /// + [JsonPropertyName("lastEdited")] + public DateTimeOffset LastEdited { get; set; } + + /// + /// The dependencies of the package, grouped by target framework. + /// + [JsonPropertyName("dependencyGroups")] + public List? DependencyGroups { get; set; } + + /// + /// The package's description. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// The URL to the package's icon. + /// + [JsonPropertyName("iconUrl")] + public string? IconUrl { get; set; } + + /// + /// Whether or not the package is prerelease. Can be detected from . + /// Note that the NuGet.org catalog had this wrong in some cases. + /// Example: https://api.nuget.org/v3/catalog0/data/2016.03.11.21.02.55/mvid.fody.2.json + /// + [JsonPropertyName("isPrerelease")] + public bool IsPrerelease { get; set; } + + /// + /// The package's language. + /// + [JsonPropertyName("language")] + public string? Language { get; set; } + + /// + /// THe URL to the package's license. + /// + [JsonPropertyName("licenseUrl")] + public string? LicenseUrl { get; set; } + + /// + /// Whether the pacakge is listed. + /// + [JsonPropertyName("listed")] + public bool? Listed { get; set; } + + /// + /// The minimum NuGet client version needed to use this package. + /// + [JsonPropertyName("minClientVersion")] + public string? MinClientVersion { get; set; } + + /// + /// The hash of the package encoded using Base64. + /// Hash algorithm can be detected using . + /// + [JsonPropertyName("packageHash")] + public string? PackageHash { get; set; } + + /// + /// The algorithm used to hash . + /// + [JsonPropertyName("packageHashAlgorithm")] + public string? PackageHashAlgorithm { get; set; } + + /// + /// The size of the package .nupkg in bytes. + /// + [JsonPropertyName("packageSize")] + public long PackageSize { get; set; } + + /// + /// The URL for the package's home page. + /// + [JsonPropertyName("projectUrl")] + public string? ProjectUrl { get; set; } + + /// + /// The package's release notes. + /// + [JsonPropertyName("releaseNotes")] + public string? ReleaseNotes { get; set; } + + /// + /// If true, the package requires its license to be accepted. + /// + [JsonPropertyName("requireLicenseAcceptance")] + public bool? RequireLicenseAcceptance { get; set; } + + /// + /// The package's summary. + /// + [JsonPropertyName("summary")] + public string? Summary { get; set; } + + /// + /// The package's tags. + /// + [JsonPropertyName("tags")] + public List? Tags { get; set; } + + /// + /// The package's title. + /// + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// + /// The version string as it's originally found in the .nuspec. + /// + [JsonPropertyName("verbatimVersion")] + public string? VerbatimVersion { get; set; } + + /// + /// The package's License Expression. + /// + [JsonPropertyName("licenseExpression")] + public string? LicenseExpression { get; set; } + + /// + /// The package's license file. + /// + [JsonPropertyName("licenseFile")] + public string? LicenseFile { get; set; } + + /// + /// The package's icon file. + /// + [JsonPropertyName("iconFile")] + public string? IconFile { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageMetadata.cs b/src/BaGet.Protocol/Models/PackageMetadata.cs index 2e9563d17..8cf3d73c5 100644 --- a/src/BaGet.Protocol/Models/PackageMetadata.cs +++ b/src/BaGet.Protocol/Models/PackageMetadata.cs @@ -1,129 +1,134 @@ -using System; +using System; using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A package's metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#catalog-entry +/// +public class PackageMetadata { /// - /// A package's metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#catalog-entry - /// - public class PackageMetadata - { - /// - /// The URL to the document used to produce this object. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } - - /// - /// The ID of the package. - /// - [JsonPropertyName("id")] - public string PackageId { get; set; } - - /// - /// The full NuGet version after normalization, including any SemVer 2.0.0 build metadata. - /// - [JsonPropertyName("version")] - public string Version { get; set; } - - /// - /// The package's authors. - /// - [JsonPropertyName("authors")] - public string Authors { get; set; } - - /// - /// The dependencies of the package, grouped by target framework. - /// - [JsonPropertyName("dependencyGroups")] - public IReadOnlyList DependencyGroups { get; set; } - - /// - /// The deprecation associated with the package, if any. - /// - [JsonPropertyName("deprecation")] - public PackageDeprecation Deprecation { get; set; } - - /// - /// The package's description. - /// - [JsonPropertyName("description")] - public string Description { get; set; } - - /// - /// The URL to the package's icon. - /// - [JsonPropertyName("iconUrl")] - public string IconUrl { get; set; } - - /// - /// The package's language. - /// - [JsonPropertyName("language")] - public string Language { get; set; } - - /// - /// The URL to the package's license. - /// - [JsonPropertyName("licenseUrl")] - public string LicenseUrl { get; set; } - - /// - /// Whether the package is listed in search results. - /// If , the package should be considered as listed. - /// - [JsonPropertyName("listed")] - public bool? Listed { get; set; } - - /// - /// The minimum NuGet client version needed to use this package. - /// - [JsonPropertyName("minClientVersion")] - public string MinClientVersion { get; set; } - - /// - /// The URL to download the package's content. - /// - [JsonPropertyName("packageContent")] - public string PackageContentUrl { get; set; } - - /// - /// The URL for the package's home page. - /// - [JsonPropertyName("projectUrl")] - public string ProjectUrl { get; set; } - - /// - /// The package's publish date. - /// - [JsonPropertyName("published")] - public DateTimeOffset Published { get; set; } - - /// - /// If true, the package requires its license to be accepted. - /// - [JsonPropertyName("requireLicenseAcceptance")] - public bool RequireLicenseAcceptance { get; set; } - - /// - /// The package's summary. - /// - [JsonPropertyName("summary")] - public string Summary { get; set; } - - /// - /// The package's tags. - /// - [JsonPropertyName("tags")] - public IReadOnlyList Tags { get; set; } - - /// - /// The package's title. - /// - [JsonPropertyName("title")] - public string Title { get; set; } - } -} + /// The URL to the document used to produce this object. + /// + [JsonPropertyName("@id")] + public string? CatalogLeafUrl { get; set; } + + /// + /// The ID of the package. + /// + [JsonPropertyName("id")] + public string? PackageId { get; set; } + + /// + /// The full NuGet version after normalization, including any SemVer 2.0.0 build metadata. + /// + [JsonPropertyName("version")] + public string? Version { get; set; } + + /// + /// The package's authors. + /// + [JsonPropertyName("authors")] + public string? Authors { get; set; } + + /// + /// The dependencies of the package, grouped by target framework. + /// + [JsonPropertyName("dependencyGroups")] + public IReadOnlyList? DependencyGroups { get; set; } + + /// + /// The deprecation associated with the package, if any. + /// + [JsonPropertyName("deprecation")] + public PackageDeprecation? Deprecation { get; set; } + + /// + /// The package's description. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// The URL to the package's icon. + /// + [JsonPropertyName("iconUrl")] + public string? IconUrl { get; set; } + + /// + /// The package's language. + /// + [JsonPropertyName("language")] + public string? Language { get; set; } + + /// + /// The URL to the package's license. + /// + [JsonPropertyName("licenseUrl")] + public string? LicenseUrl { get; set; } + + /// + /// Whether the package is listed in search results. + /// If , the package should be considered as listed. + /// + [JsonPropertyName("listed")] + public bool? Listed { get; set; } + + /// + /// The minimum NuGet client version needed to use this package. + /// + [JsonPropertyName("minClientVersion")] + public string? MinClientVersion { get; set; } + + /// + /// The URL to download the package's content. + /// + [JsonPropertyName("packageContent")] + public string? PackageContentUrl { get; set; } + + /// + /// The URL for the package's home page. + /// + [JsonPropertyName("projectUrl")] + public string? ProjectUrl { get; set; } + + /// + /// The package's publish date. + /// + [JsonPropertyName("published")] + public DateTimeOffset Published { get; set; } + + /// + /// If true, the package requires its license to be accepted. + /// + [JsonPropertyName("requireLicenseAcceptance")] + public bool RequireLicenseAcceptance { get; set; } + + /// + /// The package's summary. + /// + [JsonPropertyName("summary")] + public string? Summary { get; set; } + + /// + /// The package's tags. + /// + [JsonPropertyName("tags")] + public IReadOnlyList? Tags { get; set; } + + /// + /// The package's title. + /// + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// + /// The known vulnerabilities affecting this version, or null if there are none. + /// + [JsonPropertyName("vulnerabilities")] + public IReadOnlyList? Vulnerabilities { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageNotFoundException.cs b/src/BaGet.Protocol/Models/PackageNotFoundException.cs index 880c5e71c..8feba1603 100644 --- a/src/BaGet.Protocol/Models/PackageNotFoundException.cs +++ b/src/BaGet.Protocol/Models/PackageNotFoundException.cs @@ -1,33 +1,32 @@ using System; using NuGet.Versioning; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// An exception thrown when a package could not be found on the NuGet server. +/// +public class PackageNotFoundException : Exception { /// - /// An exception thrown when a package could not be found on the NuGet server. + /// Create a new instance of the . /// - public class PackageNotFoundException : Exception + /// The ID of the package that could not be found. + /// The version of the package that could not be found. + public PackageNotFoundException(string? packageId, NuGetVersion packageVersion) + : base($"Could not find package {packageId} {packageVersion}") { - /// - /// Create a new instance of the . - /// - /// The ID of the package that could not be found. - /// The version of the package that could not be found. - public PackageNotFoundException(string packageId, NuGetVersion packageVersion) - : base($"Could not find package {packageId} {packageVersion}") - { - PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); - PackageVersion = packageVersion ?? throw new ArgumentNullException(nameof(packageVersion)); - } + PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); + PackageVersion = packageVersion ?? throw new ArgumentNullException(nameof(packageVersion)); + } - /// - /// The package ID that could not be found. - /// - public string PackageId { get; } + /// + /// The package ID that could not be found. + /// + public string PackageId { get; } - /// - /// The package version that could not be found. - /// - public NuGetVersion PackageVersion { get; } - } -} + /// + /// The package version that could not be found. + /// + public NuGetVersion PackageVersion { get; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageVersionsResponse.cs b/src/BaGet.Protocol/Models/PackageVersionsResponse.cs index 4a8a64f93..604e677bc 100644 --- a/src/BaGet.Protocol/Models/PackageVersionsResponse.cs +++ b/src/BaGet.Protocol/Models/PackageVersionsResponse.cs @@ -1,19 +1,18 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The full list of versions for a single package. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions +/// +public class PackageVersionsResponse { /// - /// The full list of versions for a single package. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions + /// The versions, lowercased and normalized. /// - public class PackageVersionsResponse - { - /// - /// The versions, lowercased and normalized. - /// - [JsonPropertyName("versions")] - public IReadOnlyList Versions { get; set; } - } -} + [JsonPropertyName("versions")] + public IReadOnlyList? Versions { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageVulnerabilityMetadata.cs b/src/BaGet.Protocol/Models/PackageVulnerabilityMetadata.cs new file mode 100644 index 000000000..bf4ed4ca2 --- /dev/null +++ b/src/BaGet.Protocol/Models/PackageVulnerabilityMetadata.cs @@ -0,0 +1,25 @@ +using System.Text.Json.Serialization; + +namespace BaGet.Protocol.Models; + +/// +/// A known vulnerability affecting a package version, as it appears in the package's +/// registration metadata. +/// +/// See https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#vulnerabilities +/// +public class PackageVulnerabilityMetadata +{ + /// + /// The URL of the advisory describing the vulnerability. + /// + [JsonPropertyName("advisoryUrl")] + public string? AdvisoryUrl { get; set; } + + /// + /// The severity: "0" low, "1" moderate, "2" high, "3" critical. A string in the + /// registration metadata, unlike the VulnerabilityInfo resource, which uses a number. + /// + [JsonPropertyName("severity")] + public string? Severity { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ProtocolException.cs b/src/BaGet.Protocol/Models/ProtocolException.cs index 893c89024..7d0b8dc67 100644 --- a/src/BaGet.Protocol/Models/ProtocolException.cs +++ b/src/BaGet.Protocol/Models/ProtocolException.cs @@ -2,52 +2,51 @@ using System.Net; using System.Net.Http; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// An exception that is thrown when an API has returned an unexpected result. +/// +public class ProtocolException : Exception { /// - /// An exception that is thrown when an API has returned an unexpected result. + /// Create a new . /// - public class ProtocolException : Exception + /// The HTTP response message. + /// The HTTP request method. + /// The URI that was requested. + /// The response status code. + /// The HTTP reason phrase. + public ProtocolException( + string message, + HttpMethod method, + string requestUri, + HttpStatusCode statusCode, + string reasonPhrase) : base(message) { - /// - /// Create a new . - /// - /// The HTTP response message. - /// The HTTP request method. - /// The URI that was requested. - /// The response status code. - /// The HTTP reason phrase. - public ProtocolException( - string message, - HttpMethod method, - string requestUri, - HttpStatusCode statusCode, - string reasonPhrase) : base(message) - { - Method = method ?? throw new ArgumentNullException(nameof(method)); - RequestUri = requestUri ?? throw new ArgumentNullException(nameof(requestUri)); - StatusCode = statusCode; - ReasonPhrase = reasonPhrase ?? throw new ArgumentNullException(nameof(reasonPhrase)); - } + Method = method ?? throw new ArgumentNullException(nameof(method)); + RequestUri = requestUri ?? throw new ArgumentNullException(nameof(requestUri)); + StatusCode = statusCode; + ReasonPhrase = reasonPhrase ?? throw new ArgumentNullException(nameof(reasonPhrase)); + } - /// - /// The HTTP response message. - /// - public HttpMethod Method { get; } + /// + /// The HTTP response message. + /// + public HttpMethod Method { get; } - /// - /// The URI that was requested. - /// - public string RequestUri { get; } + /// + /// The URI that was requested. + /// + public string RequestUri { get; } - /// - /// The response status code. - /// - public HttpStatusCode StatusCode { get; } + /// + /// The response status code. + /// + public HttpStatusCode StatusCode { get; } - /// - /// The response reason phrase. - /// - public string ReasonPhrase { get; } - } -} + /// + /// The response reason phrase. + /// + public string ReasonPhrase { get; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationIndexPage.cs b/src/BaGet.Protocol/Models/RegistrationIndexPage.cs index e7190af5c..48879ff9e 100644 --- a/src/BaGet.Protocol/Models/RegistrationIndexPage.cs +++ b/src/BaGet.Protocol/Models/RegistrationIndexPage.cs @@ -1,46 +1,45 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The registration page object found in the registration index. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page-object +/// +public class RegistrationIndexPage { /// - /// The registration page object found in the registration index. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page-object + /// The URL to the registration page. /// - public class RegistrationIndexPage - { - /// - /// The URL to the registration page. - /// - [JsonPropertyName("@id")] - public string RegistrationPageUrl { get; set; } + [JsonPropertyName("@id")] + public string? RegistrationPageUrl { get; set; } - /// - /// The number of registration leafs in the page. - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of registration leafs in the page. + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// if this package's registration is paged. The items can be found - /// by following the page's . - /// - [JsonPropertyName("items")] - public IReadOnlyList ItemsOrNull { get; set; } + /// + /// if this package's registration is paged. The items can be found + /// by following the page's . + /// + [JsonPropertyName("items")] + public IReadOnlyList? ItemsOrNull { get; set; } - /// - /// This page's lowest package version. The version should be lowercased, normalized, - /// and the SemVer 2.0.0 build metadata removed, if any. - /// - [JsonPropertyName("lower")] - public string Lower { get; set; } + /// + /// This page's lowest package version. The version should be lowercased, normalized, + /// and the SemVer 2.0.0 build metadata removed, if any. + /// + [JsonPropertyName("lower")] + public string? Lower { get; set; } - /// - /// This page's highest package version. The version should be lowercased, normalized, - /// and the SemVer 2.0.0 build metadata removed, if any. - /// - [JsonPropertyName("upper")] - public string Upper { get; set; } - } -} + /// + /// This page's highest package version. The version should be lowercased, normalized, + /// and the SemVer 2.0.0 build metadata removed, if any. + /// + [JsonPropertyName("upper")] + public string? Upper { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs b/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs index 91668366a..fbdc53f8b 100644 --- a/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs +++ b/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// An item in the that references a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf-object-in-a-page +/// +public class RegistrationIndexPageItem { /// - /// An item in the that references a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf-object-in-a-page + /// The URL to the registration leaf. /// - public class RegistrationIndexPageItem - { - /// - /// The URL to the registration leaf. - /// - [JsonPropertyName("@id")] - public string RegistrationLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string? RegistrationLeafUrl { get; set; } - /// - /// The catalog entry containing the package metadata. - /// - [JsonPropertyName("catalogEntry")] - public PackageMetadata PackageMetadata { get; set; } + /// + /// The catalog entry containing the package metadata. + /// + [JsonPropertyName("catalogEntry")] + public PackageMetadata? PackageMetadata { get; set; } - /// - /// The URL to the package content (.nupkg) - /// - [JsonPropertyName("packageContent")] - public string PackageContentUrl { get; set; } - } -} + /// + /// The URL to the package content (.nupkg) + /// + [JsonPropertyName("packageContent")] + public string? PackageContentUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs b/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs index 79cf01bac..5f4271903 100644 --- a/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs +++ b/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs @@ -1,45 +1,44 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The metadata for a package and all of its versions. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index +/// +public class RegistrationIndexResponse { - /// - /// The metadata for a package and all of its versions. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index - /// - public class RegistrationIndexResponse + public static readonly IReadOnlyList DefaultType = new List { - public static readonly IReadOnlyList DefaultType = new List - { - "catalog:CatalogRoot", - "PackageRegistration", - "catalog:Permalink" - }; + "catalog:CatalogRoot", + "PackageRegistration", + "catalog:Permalink" + }; - /// - /// The URL to the registration index. - /// - [JsonPropertyName("@id")] - public string RegistrationIndexUrl { get; set; } + /// + /// The URL to the registration index. + /// + [JsonPropertyName("@id")] + public string? RegistrationIndexUrl { get; set; } - /// - /// The registration index's type. - /// - [JsonPropertyName("@type")] - public IReadOnlyList Type { get; set; } + /// + /// The registration index's type. + /// + [JsonPropertyName("@type")] + public IReadOnlyList? Type { get; set; } - /// - /// The number of registration pages. See . - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of registration pages. See . + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// The pages that contain all of the versions of the package, ordered - /// by the package's version. - /// - [JsonPropertyName("items")] - public IReadOnlyList Pages { get; set; } - } -} + /// + /// The pages that contain all of the versions of the package, ordered + /// by the package's version. + /// + [JsonPropertyName("items")] + public IReadOnlyList? Pages { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs b/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs index c95ca7ed1..7bb8ec291 100644 --- a/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs +++ b/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs @@ -2,56 +2,55 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The metadata for a single version of a package. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf +/// +public class RegistrationLeafResponse { + public static readonly IReadOnlyList DefaultType = new List + { + "Package", + "http://schema.nuget.org/catalog#Permalink" + }; + /// - /// The metadata for a single version of a package. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf + /// The URL to the registration leaf. /// - public class RegistrationLeafResponse - { - public static readonly IReadOnlyList DefaultType = new List - { - "Package", - "http://schema.nuget.org/catalog#Permalink" - }; - - /// - /// The URL to the registration leaf. - /// - [JsonPropertyName("@id")] - public string RegistrationLeafUrl { get; set; } - - /// - /// The registration leaf's type. - /// - [JsonPropertyName("@type")] - public IReadOnlyList Type { get; set; } - - /// - /// Whether the package is listed. - /// - [JsonPropertyName("listed")] - public bool Listed { get; set; } - - /// - /// The URL to the package content (.nupkg). - /// - [JsonPropertyName("packageContent")] - public string PackageContentUrl { get; set; } - - /// - /// The date the package was published. On NuGet.org, - /// is set to the year 1900 if the package is unlisted. - /// - [JsonPropertyName("published")] - public DateTimeOffset Published { get; set; } - - /// - /// The URL to the package's registration index. - /// - [JsonPropertyName("registration")] - public string RegistrationIndexUrl { get; set; } - } -} + [JsonPropertyName("@id")] + public string? RegistrationLeafUrl { get; set; } + + /// + /// The registration leaf's type. + /// + [JsonPropertyName("@type")] + public IReadOnlyList? Type { get; set; } + + /// + /// Whether the package is listed. + /// + [JsonPropertyName("listed")] + public bool Listed { get; set; } + + /// + /// The URL to the package content (.nupkg). + /// + [JsonPropertyName("packageContent")] + public string? PackageContentUrl { get; set; } + + /// + /// The date the package was published. On NuGet.org, + /// is set to the year 1900 if the package is unlisted. + /// + [JsonPropertyName("published")] + public DateTimeOffset Published { get; set; } + + /// + /// The URL to the package's registration index. + /// + [JsonPropertyName("registration")] + public string? RegistrationIndexUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationPageResponse.cs b/src/BaGet.Protocol/Models/RegistrationPageResponse.cs index 60ee23d75..c7a4e819c 100644 --- a/src/BaGet.Protocol/Models/RegistrationPageResponse.cs +++ b/src/BaGet.Protocol/Models/RegistrationPageResponse.cs @@ -1,11 +1,10 @@ -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A page of package metadata entries. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page +/// +public class RegistrationPageResponse : RegistrationIndexPage { - /// - /// A page of package metadata entries. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - public class RegistrationPageResponse : RegistrationIndexPage - { - } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchContext.cs b/src/BaGet.Protocol/Models/SearchContext.cs index 6abfb92ea..6c759028b 100644 --- a/src/BaGet.Protocol/Models/SearchContext.cs +++ b/src/BaGet.Protocol/Models/SearchContext.cs @@ -1,22 +1,21 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +public class SearchContext { - public class SearchContext + public static SearchContext Default(string registrationBaseUrl) { - public static SearchContext Default(string registrationBaseUrl) + return new SearchContext { - return new SearchContext - { - Vocab = "http://schema.nuget.org/schema#", - Base = registrationBaseUrl - }; - } + Vocab = "http://schema.nuget.org/schema#", + Base = registrationBaseUrl + }; + } - [JsonPropertyName("@vocab")] - public string Vocab { get; set; } + [JsonPropertyName("@vocab")] + public string? Vocab { get; set; } - [JsonPropertyName("@base")] - public string Base { get; set; } - } -} + [JsonPropertyName("@base")] + public string? Base { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResponse.cs b/src/BaGet.Protocol/Models/SearchResponse.cs index 70fce7393..afc5b1e00 100644 --- a/src/BaGet.Protocol/Models/SearchResponse.cs +++ b/src/BaGet.Protocol/Models/SearchResponse.cs @@ -1,28 +1,27 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The response to a search query. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#response +/// +public class SearchResponse { + [JsonPropertyName("@context")] + public SearchContext? Context { get; set; } + /// - /// The response to a search query. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#response + /// The total number of matches, disregarding skip and take. /// - public class SearchResponse - { - [JsonPropertyName("@context")] - public SearchContext Context { get; set; } - - /// - /// The total number of matches, disregarding skip and take. - /// - [JsonPropertyName("totalHits")] - public long TotalHits { get; set; } + [JsonPropertyName("totalHits")] + public long TotalHits { get; set; } - /// - /// The packages that matched the search query. - /// - [JsonPropertyName("data")] - public IReadOnlyList Data { get; set; } - } -} + /// + /// The packages that matched the search query. + /// + [JsonPropertyName("data")] + public IReadOnlyList? Data { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResult.cs b/src/BaGet.Protocol/Models/SearchResult.cs index fecd9d6b1..25641d6cb 100644 --- a/src/BaGet.Protocol/Models/SearchResult.cs +++ b/src/BaGet.Protocol/Models/SearchResult.cs @@ -2,99 +2,122 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Internal; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A package that matched a search query. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result +/// +public class SearchResult { /// - /// A package that matched a search query. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result - /// - public class SearchResult - { - /// - /// The ID of the matched package. - /// - [JsonPropertyName("id")] - public string PackageId { get; set; } - - /// - /// The latest version of the matched pacakge. This is the full NuGet version after normalization, - /// including any SemVer 2.0.0 build metadata. - /// - [JsonPropertyName("version")] - public string Version { get; set; } - - /// - /// The description of the matched package. - /// - [JsonPropertyName("description")] - public string Description { get; set; } - - /// - /// The authors of the matched package. - /// - [JsonPropertyName("authors")] - [JsonConverter(typeof(StringOrStringArrayJsonConverter))] - public IReadOnlyList Authors { get; set; } - - /// - /// The URL of the matched package's icon. - /// - [JsonPropertyName("iconUrl")] - public string IconUrl { get; set; } - - /// - /// The URL of the matched package's license. - /// - [JsonPropertyName("licenseUrl")] - public string LicenseUrl { get; set; } - - /// - /// The package types defined by the package author. - /// - [JsonPropertyName("packageTypes")] - public IReadOnlyList PackageTypes { get; set; } - - /// - /// The URL of the matched package's homepage. - /// - [JsonPropertyName("projectUrl")] - public string ProjectUrl { get; set; } - - /// - /// The URL for the matched package's registration index. - /// - [JsonPropertyName("registration")] - public string RegistrationIndexUrl { get; set; } - - /// - /// The summary of the matched package. - /// - [JsonPropertyName("summary")] - public string Summary { get; set; } - - /// - /// The tags of the matched package. - /// - [JsonPropertyName("tags")] - public IReadOnlyList Tags { get; set; } - - /// - /// The title of the matched package. - /// - [JsonPropertyName("title")] - public string Title { get; set; } - - /// - /// The total downloads for all versions of the matched package. - /// - [JsonPropertyName("totalDownloads")] - public long TotalDownloads { get; set; } - - /// - /// The versions of the matched package. - /// - [JsonPropertyName("versions")] - public IReadOnlyList Versions { get; set; } - } -} + /// The ID of the matched package. + /// + [JsonPropertyName("id")] + public string? PackageId { get; set; } + + /// + /// The latest version of the matched pacakge. This is the full NuGet version after normalization, + /// including any SemVer 2.0.0 build metadata. + /// + [JsonPropertyName("version")] + public string? Version { get; set; } + + /// + /// The description of the matched package. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// The authors of the matched package. + /// + [JsonPropertyName("authors")] + [JsonConverter(typeof(StringOrStringArrayJsonConverter))] + public IReadOnlyList? Authors { get; set; } + + /// + /// The URL of the matched package's icon. + /// + [JsonPropertyName("iconUrl")] + public string? IconUrl { get; set; } + + /// + /// The URL of the matched package's license. + /// + [JsonPropertyName("licenseUrl")] + public string? LicenseUrl { get; set; } + + /// + /// The package types defined by the package author. + /// + [JsonPropertyName("packageTypes")] + public IReadOnlyList? PackageTypes { get; set; } + + /// + /// The URL of the matched package's homepage. + /// + [JsonPropertyName("projectUrl")] + public string? ProjectUrl { get; set; } + + /// + /// The URL for the matched package's registration index. + /// + [JsonPropertyName("registration")] + public string? RegistrationIndexUrl { get; set; } + + /// + /// The summary of the matched package. + /// + [JsonPropertyName("summary")] + public string? Summary { get; set; } + + /// + /// The tags of the matched package. + /// + [JsonPropertyName("tags")] + public IReadOnlyList? Tags { get; set; } + + /// + /// The title of the matched package. + /// + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// + /// The total downloads for all versions of the matched package. + /// + [JsonPropertyName("totalDownloads")] + public long TotalDownloads { get; set; } + + /// + /// The versions of the matched package. + /// + [JsonPropertyName("versions")] + public IReadOnlyList? Versions { get; set; } + + /// + /// The latest version's deprecation, or null if it is not deprecated. + /// + [JsonPropertyName("deprecation")] + public PackageDeprecation? Deprecation { get; set; } + + /// + /// The latest version's known vulnerabilities, or null if it has none. + /// + [JsonPropertyName("vulnerabilities")] + public IReadOnlyList? Vulnerabilities { get; set; } + + /// + /// The package's owners, or null if it has none. + /// + [JsonPropertyName("owners")] + public IReadOnlyList? Owners { get; set; } + + /// + /// Whether the package ID is reserved for its owners. Null if it has no owners. + /// + [JsonPropertyName("verified")] + public bool? Verified { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResultPackageType.cs b/src/BaGet.Protocol/Models/SearchResultPackageType.cs index aa353b7cc..824fe2868 100644 --- a/src/BaGet.Protocol/Models/SearchResultPackageType.cs +++ b/src/BaGet.Protocol/Models/SearchResultPackageType.cs @@ -1,18 +1,17 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A single package type from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result +/// +public class SearchResultPackageType { /// - /// A single package type from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + /// The name of the package type. /// - public class SearchResultPackageType - { - /// - /// The name of the package type. - /// - [JsonPropertyName("name")] - public string Name { get; set; } - } -} + [JsonPropertyName("name")] + public string? Name { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResultVersion.cs b/src/BaGet.Protocol/Models/SearchResultVersion.cs index a3a2cb237..5771bdb0e 100644 --- a/src/BaGet.Protocol/Models/SearchResultVersion.cs +++ b/src/BaGet.Protocol/Models/SearchResultVersion.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A single version from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result +/// +public class SearchResultVersion { /// - /// A single version from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + /// The registration leaf URL for this single version of the matched package. /// - public class SearchResultVersion - { - /// - /// The registration leaf URL for this single version of the matched package. - /// - [JsonPropertyName("@id")] - public string RegistrationLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string? RegistrationLeafUrl { get; set; } - /// - /// The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata. - /// - [JsonPropertyName("version")] - public string Version { get; set; } + /// + /// The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata. + /// + [JsonPropertyName("version")] + public string? Version { get; set; } - /// - /// The downloads for this single version of the matched package. - /// - [JsonPropertyName("downloads")] - public long Downloads { get; set; } - } -} + /// + /// The downloads for this single version of the matched package. + /// + [JsonPropertyName("downloads")] + public long Downloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ServiceIndexItem.cs b/src/BaGet.Protocol/Models/ServiceIndexItem.cs index 36ba43881..e708cab61 100644 --- a/src/BaGet.Protocol/Models/ServiceIndexItem.cs +++ b/src/BaGet.Protocol/Models/ServiceIndexItem.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A resource in the . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index#resources +/// +public class ServiceIndexItem { /// - /// A resource in the . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index#resources + /// The resource's base URL. /// - public class ServiceIndexItem - { - /// - /// The resource's base URL. - /// - [JsonPropertyName("@id")] - public string ResourceUrl { get; set; } + [JsonPropertyName("@id")] + public string? ResourceUrl { get; set; } - /// - /// The resource's type. - /// - [JsonPropertyName("@type")] - public string Type { get; set; } + /// + /// The resource's type. + /// + [JsonPropertyName("@type")] + public string? Type { get; set; } - /// - /// Human readable comments about the resource. - /// - [JsonPropertyName("comment")] - public string Comment { get; set; } - } -} + /// + /// Human readable comments about the resource. + /// + [JsonPropertyName("comment")] + public string? Comment { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ServiceIndexResponse.cs b/src/BaGet.Protocol/Models/ServiceIndexResponse.cs index 4b0327124..2d928b2a9 100644 --- a/src/BaGet.Protocol/Models/ServiceIndexResponse.cs +++ b/src/BaGet.Protocol/Models/ServiceIndexResponse.cs @@ -1,25 +1,24 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The entry point for a NuGet package source used by the client to discover NuGet APIs. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/overview +/// +public class ServiceIndexResponse { /// - /// The entry point for a NuGet package source used by the client to discover NuGet APIs. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/overview + /// The service index's version. /// - public class ServiceIndexResponse - { - /// - /// The service index's version. - /// - [JsonPropertyName("version")] - public string Version { get; set; } + [JsonPropertyName("version")] + public string? Version { get; set; } - /// - /// The resources declared by this service index. - /// - [JsonPropertyName("resources")] - public IReadOnlyList Resources { get; set; } - } -} + /// + /// The resources declared by this service index. + /// + [JsonPropertyName("resources")] + public IReadOnlyList? Resources { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/NuGetClient.cs b/src/BaGet.Protocol/NuGetClient.cs index ebecab972..f33052ab2 100644 --- a/src/BaGet.Protocol/NuGetClient.cs +++ b/src/BaGet.Protocol/NuGetClient.cs @@ -9,487 +9,541 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The client to interact with a NuGet server. +/// +public class NuGetClient { + private readonly IPackageContentClient? _contentClient; + private readonly IPackageMetadataClient? _metadataClient; + private readonly ISearchClient? _searchClient; + private readonly IAutocompleteClient? _autocompleteClient; + /// - /// The client to interact with a NuGet server. + /// Initializes a new instance of the class + /// for mocking. /// - public class NuGetClient + protected NuGetClient() { - private readonly IPackageContentClient _contentClient; - private readonly IPackageMetadataClient _metadataClient; - private readonly ISearchClient _searchClient; - private readonly IAutocompleteClient _autocompleteClient; - - /// - /// Initializes a new instance of the class - /// for mocking. - /// - protected NuGetClient() - { - } + } - /// - /// Initializes a new instance of the class. - /// - /// - /// The NuGet Service Index resource URL. - /// - /// For NuGet.org, use https://api.nuget.org/v3/index.json - /// - public NuGetClient(string serviceIndexUrl) + /// + /// Initializes a new instance of the class. + /// + /// + /// The NuGet Service Index resource URL. + /// + /// For NuGet.org, use https://api.nuget.org/v3/index.json + /// + public NuGetClient(string? serviceIndexUrl) + { + var httpClient = new HttpClient(new HttpClientHandler { - var httpClient = new HttpClient(new HttpClientHandler - { - AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, - }); + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + }); - var clientFactory = new NuGetClientFactory(httpClient, serviceIndexUrl); + var clientFactory = new NuGetClientFactory(httpClient, serviceIndexUrl); - _contentClient = clientFactory.CreatePackageContentClient(); - _metadataClient = clientFactory.CreatePackageMetadataClient(); - _searchClient = clientFactory.CreateSearchClient(); - _autocompleteClient = clientFactory.CreateAutocompleteClient(); - } + _contentClient = clientFactory.CreatePackageContentClient(); + _metadataClient = clientFactory.CreatePackageMetadataClient(); + _searchClient = clientFactory.CreateSearchClient(); + _autocompleteClient = clientFactory.CreateAutocompleteClient(); + } - /// - /// Initializes a new instance of the class. - /// - /// The factory used to create NuGet clients. - public NuGetClient(NuGetClientFactory clientFactory) - { - if (clientFactory == null) throw new ArgumentNullException(nameof(clientFactory)); + /// + /// Initializes a new instance of the class. + /// + /// The factory used to create NuGet clients. + public NuGetClient(NuGetClientFactory clientFactory) + { + if (clientFactory == null) throw new ArgumentNullException(nameof(clientFactory)); - _contentClient = clientFactory.CreatePackageContentClient(); - _metadataClient = clientFactory.CreatePackageMetadataClient(); - _searchClient = clientFactory.CreateSearchClient(); - _autocompleteClient = clientFactory.CreateAutocompleteClient(); - } + _contentClient = clientFactory.CreatePackageContentClient(); + _metadataClient = clientFactory.CreatePackageMetadataClient(); + _searchClient = clientFactory.CreateSearchClient(); + _autocompleteClient = clientFactory.CreateAutocompleteClient(); + } - /// - /// Check if a package exists. - /// - /// The package ID. - /// A token to cancel the task. - /// Whether the package exists. - public virtual async Task ExistsAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var versions = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + /// + /// Check if a package exists. + /// + /// The package ID. + /// A token to cancel the task. + /// Whether the package exists. + public virtual async Task ExistsAsync( + string packageId, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var versions = await _contentClient?.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + #pragma warning restore CS8602 - return (versions != null && versions.Versions.Any()); - } + #pragma warning disable CS8604 + return (versions != null && versions.Versions.Any()); + #pragma warning restore CS8604 + } + + /// + /// Check if a package exists. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// Whether the package exists. + public virtual async Task ExistsAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var versions = await _contentClient?.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + #pragma warning restore CS8602 - /// - /// Check if a package exists. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// Whether the package exists. - public virtual async Task ExistsAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + if (versions == null) { - var versions = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + return false; + } - if (versions == null) - { - return false; - } + return versions + .ParseVersions() + .Any(v => v == packageVersion); + } - return versions - .ParseVersions() - .Any(v => v == packageVersion); - } + /// + /// Download a package (.nupkg), or throws if the package does not exist. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// The package's content stream. The stream may be unseekable and may be unbuffered. + /// + /// The package could not be found. + /// + public virtual async Task DownloadPackageAsync(string? packageId, NuGetVersion packageVersion, CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var stream = await _contentClient?.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); + #pragma warning restore CS8602 - /// - /// Download a package (.nupkg), or throws if the package does not exist. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// The package's content stream. The stream may be unseekable and may be unbuffered. - /// - /// The package could not be found. - /// - public virtual async Task DownloadPackageAsync(string packageId, NuGetVersion packageVersion, CancellationToken cancellationToken = default) + if (stream == null) { - var stream = await _contentClient.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); + throw new PackageNotFoundException(packageId, packageVersion); + } - if (stream == null) - { - throw new PackageNotFoundException(packageId, packageVersion); - } + return stream; + } - return stream; - } + /// + /// Download a package's manifest (.nuspec), or throws if the package does not exist. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// The package's manifest stream. The stream may not be seekable. + /// + /// The package could not be found. + /// + public virtual async Task DownloadPackageManifestAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var stream = await _contentClient?.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); + #pragma warning restore CS8602 - /// - /// Download a package's manifest (.nuspec), or throws if the package does not exist. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// The package's manifest stream. The stream may not be seekable. - /// - /// The package could not be found. - /// - public virtual async Task DownloadPackageManifestAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + if (stream == null) { - var stream = await _contentClient.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); + throw new PackageNotFoundException(packageId, packageVersion); + } - if (stream == null) - { - throw new PackageNotFoundException(packageId, packageVersion); - } + return stream; + } - return stream; - } + /// + /// Find all versions of a package, excluding unlisted versions. + /// + /// The package ID. + /// A token to cancel the task. + /// The package's listed versions, if any. + public virtual async Task> ListPackageVersionsAsync( + string packageId, + CancellationToken cancellationToken = default) + { + // The registration metadata is read instead of the Autocomplete resource's enumerate + // versions endpoint, even though the latter is cheaper: that endpoint is optional, and + // a server may advertise the Autocomplete resource without supporting it - Sleet, whose + // feed is static files, is the known case. There is no advertised capability that says + // which, so choosing it would mean fingerprinting the server and silently returning an + // empty version list when the guess is wrong. Registration metadata is always present. + var packages = await GetPackageMetadataAsync(packageId, cancellationToken); + + return packages + .Where(p => p.IsListed()) + .Select(p => p.ParseVersion()) + .ToList(); + } - /// - /// Find all versions of a package, excluding unlisted versions. - /// - /// The package ID. - /// A token to cancel the task. - /// The package's listed versions, if any. - public virtual async Task> ListPackageVersionsAsync( - string packageId, - CancellationToken cancellationToken = default) + /// + /// Find all versions of a package. + /// + /// The package ID. + /// Whether to include unlisted versions. + /// A token to cancel the task. + /// The package's versions, or an empty list if the package does not exist. + public virtual async Task> ListPackageVersionsAsync( + string packageId, + bool includeUnlisted, + CancellationToken cancellationToken = default) + { + if (!includeUnlisted) { - // TODO: Use the Autocomplete's enumerate versions endpoint if this is not Sleet. - var packages = await GetPackageMetadataAsync(packageId, cancellationToken); - - return packages - .Where(p => p.IsListed()) - .Select(p => p.ParseVersion()) - .ToList(); + return await ListPackageVersionsAsync(packageId, cancellationToken); } - /// - /// Find all versions of a package. - /// - /// The package ID. - /// Whether to include unlisted versions. - /// A token to cancel the task. - /// The package's versions, or an empty list if the package does not exist. - public virtual async Task> ListPackageVersionsAsync( - string packageId, - bool includeUnlisted, - CancellationToken cancellationToken = default) + #pragma warning disable CS8602 + var response = await _contentClient?.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + #pragma warning restore CS8602 + + if (response == null) { - if (!includeUnlisted) - { - return await ListPackageVersionsAsync(packageId, cancellationToken); - } + return new List(); + } - var response = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + return response.ParseVersions(); + } - if (response == null) - { - return new List(); - } + /// + /// Find the metadata for all versions of a package, including unlisted versions. + /// + /// The package ID. + /// A token to cancel the task. + /// The package's metadata, or an empty list if the package does not exist. + public virtual async Task> GetPackageMetadataAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var result = new List(); - return response.ParseVersions(); - } + #pragma warning disable CS8602 + var registrationIndex = await _metadataClient?.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + #pragma warning restore CS8602 - /// - /// Find the metadata for all versions of a package, including unlisted versions. - /// - /// The package ID. - /// A token to cancel the task. - /// The package's metadata, or an empty list if the package does not exist. - public virtual async Task> GetPackageMetadataAsync( - string packageId, - CancellationToken cancellationToken = default) + if (registrationIndex == null) { - var result = new List(); - - var registrationIndex = await _metadataClient.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + return result; + } - if (registrationIndex == null) + #pragma warning disable CS8602 + foreach (var registrationIndexPage in registrationIndex.Pages) + #pragma warning restore CS8602 + { + // If the package's registration index is too big, it will be split into registration + // pages stored at different URLs. We will need to fetch each page's items individually. + // We can detect this case as the registration index will have "null" items. + var items = registrationIndexPage.ItemsOrNull; + if (items == null) { - return result; - } + #pragma warning disable CS8602 + var externalRegistrationPage = await _metadataClient?.GetRegistrationPageAsync( + registrationIndexPage.RegistrationPageUrl, + cancellationToken); + #pragma warning restore CS8602 - foreach (var registrationIndexPage in registrationIndex.Pages) - { - // If the package's registration index is too big, it will be split into registration - // pages stored at different URLs. We will need to fetch each page's items individually. - // We can detect this case as the registration index will have "null" items. - var items = registrationIndexPage.ItemsOrNull; - if (items == null) - { - var externalRegistrationPage = await _metadataClient.GetRegistrationPageAsync( - registrationIndexPage.RegistrationPageUrl, - cancellationToken); - - // Skip malformed external pages. - if (externalRegistrationPage?.ItemsOrNull == null) continue; - - items = externalRegistrationPage.ItemsOrNull; - } - - result.AddRange(items.Select(i => i.PackageMetadata)); + // Skip malformed external pages. + if (externalRegistrationPage?.ItemsOrNull == null) continue; + + items = externalRegistrationPage.ItemsOrNull; } - return result; + #pragma warning disable CS8620 + result.AddRange(items.Select(i => i.PackageMetadata)); + #pragma warning restore CS8620 } - /// - /// Find the metadata for a single version of a package, or throws if the package does not exist. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// The package's metadata. - /// - /// The package could not be found. - /// - public virtual async Task GetPackageMetadataAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + return result; + } + + /// + /// Find the metadata for a single version of a package, or throws if the package does not exist. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// The package's metadata. + /// + /// The package could not be found. + /// + public virtual async Task GetPackageMetadataAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var registrationIndex = await _metadataClient?.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + #pragma warning restore CS8602 + + if (registrationIndex == null) { - var registrationIndex = await _metadataClient.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + throw new PackageNotFoundException(packageId, packageVersion); + } - if (registrationIndex == null) + #pragma warning disable CS8602 + foreach (var registrationIndexPage in registrationIndex.Pages) + #pragma warning restore CS8602 + { + // Skip pages that do not contain the desired package version. + var pageLowerVersion = registrationIndexPage.ParseLower(); + var pageUpperVersion = registrationIndexPage.ParseUpper(); + + if (pageLowerVersion > packageVersion) continue; + if (pageUpperVersion < packageVersion) continue; + + // If the package's registration index is too big, it will be split into registration + // pages stored at different URLs. We will need to fetch each page's items individually. + // We can detect this case as the registration index will have "null" items. + var items = registrationIndexPage.ItemsOrNull; + if (items == null) { - throw new PackageNotFoundException(packageId, packageVersion); + #pragma warning disable CS8602 + var externalRegistrationPage = await _metadataClient?.GetRegistrationPageAsync( + registrationIndexPage.RegistrationPageUrl, + cancellationToken); + #pragma warning restore CS8602 + + // Skip malformed external pages. + if (externalRegistrationPage?.ItemsOrNull == null) continue; + + items = externalRegistrationPage.ItemsOrNull; } - foreach (var registrationIndexPage in registrationIndex.Pages) + // We've found the registration items that should cover the desired package. + var result = items.SingleOrDefault(i => i.PackageMetadata.ParseVersion() == packageVersion); + if (result == null) { - // Skip pages that do not contain the desired package version. - var pageLowerVersion = registrationIndexPage.ParseLower(); - var pageUpperVersion = registrationIndexPage.ParseUpper(); - - if (pageLowerVersion > packageVersion) continue; - if (pageUpperVersion < packageVersion) continue; - - // If the package's registration index is too big, it will be split into registration - // pages stored at different URLs. We will need to fetch each page's items individually. - // We can detect this case as the registration index will have "null" items. - var items = registrationIndexPage.ItemsOrNull; - if (items == null) - { - var externalRegistrationPage = await _metadataClient.GetRegistrationPageAsync( - registrationIndexPage.RegistrationPageUrl, - cancellationToken); - - // Skip malformed external pages. - if (externalRegistrationPage?.ItemsOrNull == null) continue; - - items = externalRegistrationPage.ItemsOrNull; - } - - // We've found the registration items that should cover the desired package. - var result = items.SingleOrDefault(i => i.PackageMetadata.ParseVersion() == packageVersion); - if (result == null) - { - break; - } - - return result.PackageMetadata; + break; } - // No registration pages contained the desired version. - throw new PackageNotFoundException(packageId, packageVersion); + return result.PackageMetadata; } - /// - /// Search for packages. Includes prerelease packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// A token to cancel the task. - /// The search results, including prerelease packages. - public virtual async Task> SearchAsync( - string query = null, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync(query, cancellationToken: cancellationToken); - - return response.Data; - } + // No registration pages contained the desired version. + throw new PackageNotFoundException(packageId, packageVersion); + } - /// - /// Search for packages. Includes prerelease packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// The number of results to skip. - /// The number of results to include. - /// A token to cancel the task. - /// The search results, including prerelease packages. - public virtual async Task> SearchAsync( - string query, - int skip, - int take, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync( - query, - skip, - take, - includePrerelease: true, - includeSemVer2: true, - cancellationToken: cancellationToken); - - return response.Data; - } + /// + /// Search for packages. Includes prerelease packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// A token to cancel the task. + /// The search results, including prerelease packages. + public virtual async Task?> SearchAsync( + string? query = null, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _searchClient?.SearchAsync(query, cancellationToken: cancellationToken); + #pragma warning restore CS8602 - /// - /// Search for packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The search results. - public virtual async Task> SearchAsync( - string query, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync( - query, - includePrerelease: includePrerelease, - cancellationToken: cancellationToken); + return response.Data; + } - return response.Data; - } + /// + /// Search for packages. Includes prerelease packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// The number of results to skip. + /// The number of results to include. + /// A token to cancel the task. + /// The search results, including prerelease packages. + public virtual async Task?> SearchAsync( + string? query, + int skip, + int take, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _searchClient?.SearchAsync( + query, + skip, + take, + includePrerelease: true, + includeSemVer2: true, + cancellationToken: cancellationToken); + #pragma warning restore CS8602 + + return response.Data; + } - /// - /// Search for packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// The number of results to skip. - /// The number of results to include. - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The search results, including prerelease packages. - public virtual async Task> SearchAsync( - string query, - int skip, - int take, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync( - query, - skip, - take, - includePrerelease, - includeSemVer2: true, - cancellationToken); - - return response.Data; - } + /// + /// Search for packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The search results. + public virtual async Task?> SearchAsync( + string? query, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _searchClient?.SearchAsync( + query, + includePrerelease: includePrerelease, + cancellationToken: cancellationToken); + #pragma warning restore CS8602 + + return response.Data; + } - /// - /// Search for package IDs. Includes prerelease packages. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query = null, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync(query, cancellationToken: cancellationToken); + /// + /// Search for packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// The number of results to skip. + /// The number of results to include. + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The search results, including prerelease packages. + public virtual async Task?> SearchAsync( + string? query, + int skip, + int take, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _searchClient?.SearchAsync( + query, + skip, + take, + includePrerelease, + includeSemVer2: true, + cancellationToken); + #pragma warning restore CS8602 + + return response.Data; + } - return response.Data; - } + /// + /// Search for package IDs. Includes prerelease packages. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task?>? AutocompleteAsync( + string? query = null, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _autocompleteClient?.AutocompleteAsync(query, cancellationToken: cancellationToken); + #pragma warning restore CS8602 - /// - /// Search for package IDs. Includes prerelease packages. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// The number of results to skip. - /// The number of results to include. - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query, - int skip, - int take, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync( - query, - skip, - take, - includePrerelease: true, - includeSemVer2: true, - cancellationToken); - - return response.Data; - } + #pragma warning disable CS8619 + return response.Data; + #pragma warning restore CS8619 + } - /// - /// Search for package IDs. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync( - query, - includePrerelease: includePrerelease, - cancellationToken: cancellationToken); + /// + /// Search for package IDs. Includes prerelease packages. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// The number of results to skip. + /// The number of results to include. + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task?>? AutocompleteAsync( + string? query, + int skip, + int take, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _autocompleteClient?.AutocompleteAsync( + query, + skip, + take, + includePrerelease: true, + includeSemVer2: true, + cancellationToken); + #pragma warning restore CS8602 + + #pragma warning disable CS8619 + return response.Data; + #pragma warning restore CS8619 + } - return response.Data; - } + /// + /// Search for package IDs. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task?>? AutocompleteAsync( + string? query, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _autocompleteClient?.AutocompleteAsync( + query, + includePrerelease: includePrerelease, + cancellationToken: cancellationToken); + #pragma warning restore CS8602 + + #pragma warning disable CS8619 + return response.Data; + #pragma warning restore CS8619 + } - /// - /// Search for package IDs. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// The number of results to skip. - /// The number of results to include. - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query, - int skip, - int take, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync( - query, - skip, - take, - includePrerelease, - includeSemVer2: true, - cancellationToken); - - return response.Data; - } + /// + /// Search for package IDs. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// The number of results to skip. + /// The number of results to include. + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task?>? AutocompleteAsync( + string? query, + int skip, + int take, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + #pragma warning disable CS8602 + var response = await _autocompleteClient?.AutocompleteAsync( + query, + skip, + take, + includePrerelease, + includeSemVer2: true, + cancellationToken); + #pragma warning restore CS8602 + + #pragma warning disable CS8619 + return response.Data; + #pragma warning restore CS8619 } } diff --git a/src/BaGet.Protocol/NuGetClientFactory.cs b/src/BaGet.Protocol/NuGetClientFactory.cs index 452c322f1..f059123c6 100644 --- a/src/BaGet.Protocol/NuGetClientFactory.cs +++ b/src/BaGet.Protocol/NuGetClientFactory.cs @@ -1,211 +1,269 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using BaGet.Protocol.Internal; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The creates clients to interact with a NuGet server. +/// Use this for advanced scenarios. For most scenarios, consider using instead. +/// +public partial class NuGetClientFactory { /// - /// The creates clients to interact with a NuGet server. - /// Use this for advanced scenarios. For most scenarios, consider using instead. + /// How long a service index response is reused before it is fetched again. A long-lived + /// factory therefore picks up resources the server adds, moves or removes, without + /// re-fetching the index on every request. NuGet's own client caches the service index + /// for the same reason and for the same duration; see NuGet.Protocol's + /// ServiceIndexResourceV3Provider.MaxCacheDuration. + /// + internal static readonly TimeSpan DefaultServiceIndexCacheDuration = TimeSpan.FromMinutes(40); + + private readonly HttpClient? _httpClient; + private readonly string? _serviceIndexUrl; + + private readonly TimeSpan _serviceIndexCacheDuration = DefaultServiceIndexCacheDuration; + private readonly Func _clock = () => DateTimeOffset.UtcNow; + + private readonly SemaphoreSlim? _mutex; + private volatile NuGetClients? _clients; + + /// + /// Initializes a new instance of the class + /// for mocking. + /// + protected NuGetClientFactory() + { + } + + /// + /// Initializes a new instance of the class. /// - public partial class NuGetClientFactory + /// The client used for HTTP requests. + /// + /// The NuGet Service Index resource URL. + /// + /// For NuGet.org, use https://api.nuget.org/v3/index.json + /// + public NuGetClientFactory(HttpClient? httpClient, string? serviceIndexUrl) { - private readonly HttpClient _httpClient; - private readonly string _serviceIndexUrl; + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); - private readonly SemaphoreSlim _mutex; - private NuGetClients _clients; + _mutex = new SemaphoreSlim(1, 1); + _clients = null; + } - /// - /// Initializes a new instance of the class - /// for mocking. - /// - protected NuGetClientFactory() + /// + /// Initializes a new instance of the class with a + /// service index cache duration and a clock of its own, so that the expiry can be tested. + /// + internal NuGetClientFactory( + HttpClient httpClient, + string serviceIndexUrl, + TimeSpan serviceIndexCacheDuration, + Func clock) + : this(httpClient, serviceIndexUrl) + { + if (serviceIndexCacheDuration < TimeSpan.Zero) { + throw new ArgumentOutOfRangeException(nameof(serviceIndexCacheDuration)); } - /// - /// Initializes a new instance of the class. - /// - /// The client used for HTTP requests. - /// - /// The NuGet Service Index resource URL. - /// - /// For NuGet.org, use https://api.nuget.org/v3/index.json - /// - public NuGetClientFactory(HttpClient httpClient, string serviceIndexUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); + _serviceIndexCacheDuration = serviceIndexCacheDuration; + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + } - _mutex = new SemaphoreSlim(1, 1); - _clients = null; - } + /// + /// Create a client to interact with the NuGet Service Index resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// + /// A client to interact with the NuGet Service Index resource. + public virtual IServiceIndexClient CreateServiceIndexClient() + { + return new ServiceIndexClient(this); + } - /// - /// Create a client to interact with the NuGet Service Index resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index - /// - /// A client to interact with the NuGet Service Index resource. - public virtual IServiceIndexClient CreateServiceIndexClient() - { - return new ServiceIndexClient(this); - } + /// + /// Create a client to interact with the NuGet Package Content resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// + /// A client to interact with the NuGet Package Content resource. + public virtual IPackageContentClient CreatePackageContentClient() + { + return new PackageContentClient(this); + } - /// - /// Create a client to interact with the NuGet Package Content resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource - /// - /// A client to interact with the NuGet Package Content resource. - public virtual IPackageContentClient CreatePackageContentClient() - { - return new PackageContentClient(this); - } + /// + /// Create a client to interact with the NuGet Package Metadata resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// + /// A client to interact with the NuGet Package Metadata resource. + public virtual IPackageMetadataClient CreatePackageMetadataClient() + { + return new PackageMetadataClient(this); + } - /// - /// Create a client to interact with the NuGet Package Metadata resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource - /// - /// A client to interact with the NuGet Package Metadata resource. - public virtual IPackageMetadataClient CreatePackageMetadataClient() - { - return new PackageMetadataClient(this); - } + /// + /// Create a client to interact with the NuGet Search resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// + /// A client to interact with the NuGet Search resource. + public virtual ISearchClient CreateSearchClient() + { + return new SearchClient(this); + } - /// - /// Create a client to interact with the NuGet Search resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource - /// - /// A client to interact with the NuGet Search resource. - public virtual ISearchClient CreateSearchClient() - { - return new SearchClient(this); - } + /// + /// Create a client to interact with the NuGet Autocomplete resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource + /// + /// A client to interact with the NuGet Autocomplete resource. + public virtual IAutocompleteClient CreateAutocompleteClient() + { + return new AutocompleteClient(this); + } - /// - /// Create a client to interact with the NuGet Autocomplete resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource - /// - /// A client to interact with the NuGet Autocomplete resource. - public virtual IAutocompleteClient CreateAutocompleteClient() - { - return new AutocompleteClient(this); - } + /// + /// Create a client to interact with the NuGet catalog resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource + /// + /// A client to interact with the Catalog resource. + public virtual ICatalogClient CreateCatalogClient() + { + return new CatalogClient(this); + } - /// - /// Create a client to interact with the NuGet catalog resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource - /// - /// A client to interact with the Catalog resource. - public virtual ICatalogClient CreateCatalogClient() - { - return new CatalogClient(this); - } + private Task GetServiceIndexAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.ServiceIndex, cancellationToken); + } - private Task GetServiceIndexAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.ServiceIndex, cancellationToken); - } + private Task GetPackageContentClientAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.PackageContentClient, cancellationToken); + } - private Task GetPackageContentClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.PackageContentClient, cancellationToken); - } + private Task GetPackageMetadataClientAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.PackageMetadataClient, cancellationToken); + } - private Task GetPackageMetadataClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.PackageMetadataClient, cancellationToken); - } + private Task?> GetSearchClientsAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.SearchClients, cancellationToken); + } - private Task GetSearchClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.SearchClient, cancellationToken); - } + private Task?> GetAutocompleteClientsAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.AutocompleteClients, cancellationToken); + } - private Task GetAutocompleteClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.AutocompleteClient, cancellationToken); - } + private Task GetCatalogClientAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.CatalogClient, cancellationToken); + } - private Task GetCatalogClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.CatalogClient, cancellationToken); - } + private async Task GetAsync(Func clientFactory, CancellationToken cancellationToken) + { + var clients = _clients; - private async Task GetAsync(Func clientFactory, CancellationToken cancellationToken) + if (clients == null || _clock() >= clients.ExpiresAt) { - if (_clients == null) - { - await _mutex.WaitAsync(cancellationToken); + #pragma warning disable CS8602 + await _mutex?.WaitAsync(cancellationToken); + #pragma warning restore CS8602 - try - { - if (_clients == null) - { - var serviceIndexClient = new RawServiceIndexClient(_httpClient, _serviceIndexUrl); - - var serviceIndex = await serviceIndexClient.GetAsync(cancellationToken); - - var contentResourceUrl = serviceIndex.GetPackageContentResourceUrl(); - var metadataResourceUrl = serviceIndex.GetPackageMetadataResourceUrl(); - var catalogResourceUrl = serviceIndex.GetCatalogResourceUrl(); - var searchResourceUrl = serviceIndex.GetSearchQueryResourceUrl(); - var autocompleteResourceUrl = serviceIndex.GetSearchAutocompleteResourceUrl(); - - // Create clients for required resources. - var contentClient = new RawPackageContentClient(_httpClient, contentResourceUrl); - var metadataClient = new RawPackageMetadataClient(_httpClient, metadataResourceUrl); - var searchClient = new RawSearchClient(_httpClient, searchResourceUrl); - - // Create clients for optional resources. - var catalogClient = catalogResourceUrl == null - ? new NullCatalogClient() as ICatalogClient - : new RawCatalogClient(_httpClient, catalogResourceUrl); - var autocompleteClient = autocompleteResourceUrl == null - ? new NullAutocompleteClient() as IAutocompleteClient - : new RawAutocompleteClient(_httpClient, autocompleteResourceUrl); - - _clients = new NuGetClients - { - ServiceIndex = serviceIndex, - - PackageContentClient = contentClient, - PackageMetadataClient = metadataClient, - SearchClient = searchClient, - AutocompleteClient = autocompleteClient, - CatalogClient = catalogClient, - }; - } - } - finally + try + { + // Another caller may have refreshed the service index while this one waited. + if (_clients == null || _clock() >= _clients.ExpiresAt) { - _mutex.Release(); + _clients = await BuildClientsAsync(cancellationToken); } - } - // TODO: This should periodically refresh the service index response. - return clientFactory(_clients); + clients = _clients; + } + finally + { + _mutex?.Release(); + } } - private class NuGetClients + return clientFactory(clients); + } + + private async Task BuildClientsAsync(CancellationToken cancellationToken) + { + var serviceIndexClient = new RawServiceIndexClient(_httpClient, _serviceIndexUrl); + + var serviceIndex = await serviceIndexClient.GetAsync(cancellationToken); + + var contentResourceUrl = serviceIndex.GetPackageContentResourceUrl(); + var metadataResourceUrl = serviceIndex.GetPackageMetadataResourceUrl(); + var catalogResourceUrl = serviceIndex.GetCatalogResourceUrl(); + + // The service index may advertise several endpoints for the search and autocomplete + // resources. Keep one client per endpoint, in the order they should be tried. + var searchResourceUrls = serviceIndex.GetSearchQueryResourceUrls(); + var autocompleteResourceUrls = serviceIndex.GetSearchAutocompleteResourceUrls(); + + // Create clients for required resources. + var contentClient = new RawPackageContentClient(_httpClient, contentResourceUrl); + var metadataClient = new RawPackageMetadataClient(_httpClient, metadataResourceUrl); + var searchClients = searchResourceUrls + .Select(url => (ISearchClient)new RawSearchClient(_httpClient, url)) + .ToList(); + + // Create clients for optional resources. + var catalogClient = catalogResourceUrl == null + ? new NullCatalogClient() as ICatalogClient + : new RawCatalogClient(_httpClient, catalogResourceUrl); + var autocompleteClients = autocompleteResourceUrls.Count == 0 + ? new List { new NullAutocompleteClient() } + : autocompleteResourceUrls + .Select(url => (IAutocompleteClient)new RawAutocompleteClient(_httpClient, url)) + .ToList(); + + return new NuGetClients { - public ServiceIndexResponse ServiceIndex { get; set; } + ServiceIndex = serviceIndex, + ExpiresAt = _clock() + _serviceIndexCacheDuration, - public IPackageContentClient PackageContentClient { get; set; } - public IPackageMetadataClient PackageMetadataClient { get; set; } - public ISearchClient SearchClient { get; set; } - public IAutocompleteClient AutocompleteClient { get; set; } - public ICatalogClient CatalogClient { get; set; } - } + PackageContentClient = contentClient, + PackageMetadataClient = metadataClient, + SearchClients = searchClients, + AutocompleteClients = autocompleteClients, + CatalogClient = catalogClient, + }; + } + + private class NuGetClients + { + public ServiceIndexResponse? ServiceIndex { get; set; } + + /// + /// When these clients stop being used, and the service index is fetched again. + /// It lives on the snapshot so that reading it needs no synchronization. + /// + public DateTimeOffset ExpiresAt { get; set; } + + public IPackageContentClient? PackageContentClient { get; set; } + public IPackageMetadataClient? PackageMetadataClient { get; set; } + public IReadOnlyList? SearchClients { get; set; } + public IReadOnlyList? AutocompleteClients { get; set; } + public ICatalogClient? CatalogClient { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs b/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs index 33422254c..a5b8e044b 100644 --- a/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs +++ b/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs @@ -4,54 +4,53 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The Package Content resource, used to download NuGet packages and to fetch other metadata. +/// +/// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource +/// +public interface IPackageContentClient { /// - /// The Package Content resource, used to download NuGet packages and to fetch other metadata. - /// - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// Get a package's versions, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions /// - public interface IPackageContentClient - { - /// - /// Get a package's versions, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions - /// - /// The package ID. - /// A token to cancel the task. - /// The package's versions, or null if the package does not exist. - Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken = default); + /// The package ID. + /// A token to cancel the task. + /// The package's versions, or null if the package does not exist. + Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken = default); - /// - /// Download a package, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg - /// - /// The package ID. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's content stream, or null if the package does not exist. The stream may not be seekable. - /// - Task DownloadPackageOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default); + /// + /// Download a package, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg + /// + /// The package ID. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's content stream, or null if the package does not exist. The stream may not be seekable. + /// + Task DownloadPackageOrNullAsync( + string? packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default); - /// - /// Download a package's manifest (nuspec), or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. - /// - Task DownloadPackageManifestOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default); - } -} + /// + /// Download a package's manifest (nuspec), or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. + /// + Task DownloadPackageManifestOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageContent/PackageContentClient.cs b/src/BaGet.Protocol/PackageContent/PackageContentClient.cs index a42c00fd2..f684b1b70 100644 --- a/src/BaGet.Protocol/PackageContent/PackageContentClient.cs +++ b/src/BaGet.Protocol/PackageContent/PackageContentClient.cs @@ -5,47 +5,52 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class PackageContentClient : IPackageContentClient { - private class PackageContentClient : IPackageContentClient + private readonly NuGetClientFactory _clientfactory; + + public PackageContentClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } + + public async Task DownloadPackageOrNullAsync( + string? packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); + + #pragma warning disable CS8602 + return await client?.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); + #pragma warning restore CS8602 + } + + public async Task DownloadPackageManifestOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) { - private readonly NuGetClientFactory _clientfactory; - - public PackageContentClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } - - public async Task DownloadPackageOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); - - return await client.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); - } - - public async Task DownloadPackageManifestOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); - - return await client.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); - } - - public async Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); - - return await client.GetPackageVersionsOrNullAsync(packageId, cancellationToken); - } + var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); + + #pragma warning disable CS8602 + return await client?.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); + #pragma warning restore CS8602 + } + + public async Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); + + #pragma warning disable CS8602 + return await client?.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + #pragma warning restore CS8602 } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs b/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs index 1d172844f..7d01e2eca 100644 --- a/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs +++ b/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs @@ -7,79 +7,102 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client to interact with an upstream source's Package Content resource. +/// +public class RawPackageContentClient : IPackageContentClient { + private readonly HttpClient _httpClient; + private readonly string _packageContentUrl; + /// - /// The client to interact with an upstream source's Package Content resource. + /// Create a new Package Content client. /// - public class RawPackageContentClient : IPackageContentClient + /// The HTTP client used to send requests. + /// The NuGet Server's package content URL. + public RawPackageContentClient(HttpClient? httpClient, string? packageContentUrl) + { + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _packageContentUrl = packageContentUrl?.TrimEnd('/') + ?? throw new ArgumentNullException(nameof(packageContentUrl)); + } + + /// + public async Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var id = packageId.ToLowerInvariant(); + var url = $"{_packageContentUrl}/{id}/index.json"; + + return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); + } + + /// + public async Task DownloadPackageOrNullAsync( + string? packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) { - private readonly HttpClient _httpClient; - private readonly string _packageContentUrl; + var id = packageId?.ToLowerInvariant(); + var version = packageVersion.ToNormalizedString().ToLowerInvariant(); - /// - /// Create a new Package Content client. - /// - /// The HTTP client used to send requests. - /// The NuGet Server's package content URL. - public RawPackageContentClient(HttpClient httpClient, string packageContentUrl) + // The response will be disposed when the returned content stream is disposed. + var url = $"{_packageContentUrl}/{id}/{version}/{id}.{version}.nupkg"; + var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + + if (response.StatusCode == HttpStatusCode.NotFound) { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _packageContentUrl = packageContentUrl?.TrimEnd('/') - ?? throw new ArgumentNullException(nameof(packageContentUrl)); + response.Dispose(); + return null; } - /// - public async Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) + try { - var id = packageId.ToLowerInvariant(); - var url = $"{_packageContentUrl}/{id}/index.json"; - - return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); + // Any other failure (401, 403, 429, 5xx) is an error, never the package's content. + response.EnsureSuccessStatusCode(); } - - /// - public async Task DownloadPackageOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + catch { - var id = packageId.ToLowerInvariant(); - var version = packageVersion.ToNormalizedString().ToLowerInvariant(); + response.Dispose(); + throw; + } - // The response will be disposed when the returned content stream is disposed. - var url = $"{_packageContentUrl}/{id}/{version}/{id}.{version}.nupkg"; - var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + return await response.Content.ReadAsStreamAsync(); + } - if (response.StatusCode == HttpStatusCode.NotFound) - { - return null; - } + /// + public async Task DownloadPackageManifestOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var id = packageId.ToLowerInvariant(); + var version = packageVersion.ToNormalizedString().ToLowerInvariant(); - return await response.Content.ReadAsStreamAsync(); - } + // The response will be disposed when the returned content stream is disposed. + var url = $"{_packageContentUrl}/{id}/{version}/{id}.nuspec"; + var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); - /// - public async Task DownloadPackageManifestOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + if (response.StatusCode == HttpStatusCode.NotFound) { - var id = packageId.ToLowerInvariant(); - var version = packageVersion.ToNormalizedString().ToLowerInvariant(); - - // The response will be disposed when the returned content stream is disposed. - var url = $"{_packageContentUrl}/{id}/{version}/{id}.nuspec"; - var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); - - if (response.StatusCode == HttpStatusCode.NotFound) - { - return null; - } + response.Dispose(); + return null; + } - return await response.Content.ReadAsStreamAsync(); + try + { + // Any other failure (401, 403, 429, 5xx) is an error, never the package's content. + response.EnsureSuccessStatusCode(); } + catch + { + response.Dispose(); + throw; + } + + return await response.Content.ReadAsStreamAsync(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs b/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs index fb3e06f86..e09513246 100644 --- a/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs +++ b/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs @@ -2,43 +2,42 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The Package Metadata client, used to fetch packages' metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource +/// +public interface IPackageMetadataClient { /// - /// The Package Metadata client, used to fetch packages' metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// Attempt to get a package's registration index, if it exists. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page /// - public interface IPackageMetadataClient - { - /// - /// Attempt to get a package's registration index, if it exists. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The package's ID. - /// A token to cancel the task. - /// The package's registration index, or null if the package does not exist - Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); + /// The package's ID. + /// A token to cancel the task. + /// The package's registration index, or null if the package does not exist + Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); - /// - /// Get a page that was linked from the package's registration index. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The URL of the page, from the . - /// A token to cancel the task. - /// The registration index page. - Task GetRegistrationPageAsync( - string pageUrl, - CancellationToken cancellationToken = default); + /// + /// Get a page that was linked from the package's registration index. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page + /// + /// The URL of the page, from the . + /// A token to cancel the task. + /// The registration index page. + Task GetRegistrationPageAsync( + string? pageUrl, + CancellationToken cancellationToken = default); - /// - /// Get the metadata for a single package version. - /// - /// The URL of the leaf, from the . - /// A token to cancel the task. - /// The registration leaf. - Task GetRegistrationLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default); - } -} + /// + /// Get the metadata for a single package version. + /// + /// The URL of the leaf, from the . + /// A token to cancel the task. + /// The registration leaf. + Task GetRegistrationLeafAsync( + string leafUrl, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs b/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs index 9d338bc23..846c12c61 100644 --- a/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs +++ b/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs @@ -3,45 +3,50 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class PackageMetadataClient : IPackageMetadataClient { - private class PackageMetadataClient : IPackageMetadataClient + private readonly NuGetClientFactory _clientfactory; + + public PackageMetadataClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } + + public async Task GetRegistrationIndexOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); + + #pragma warning disable CS8602 + return await client?.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + #pragma warning restore CS8602 + } + + public async Task GetRegistrationPageAsync( + string? pageUrl, + CancellationToken cancellationToken = default) { - private readonly NuGetClientFactory _clientfactory; - - public PackageMetadataClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } - - public async Task GetRegistrationIndexOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); - - return await client.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); - } - - public async Task GetRegistrationPageAsync( - string pageUrl, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); - - return await client.GetRegistrationPageAsync(pageUrl, cancellationToken); - } - - public async Task GetRegistrationLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); - - return await client.GetRegistrationLeafAsync(leafUrl, cancellationToken); - } + var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); + + #pragma warning disable CS8602 + return await client?.GetRegistrationPageAsync(pageUrl, cancellationToken); + #pragma warning restore CS8602 + } + + public async Task GetRegistrationLeafAsync( + string leafUrl, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); + + #pragma warning disable CS8602 + return await client?.GetRegistrationLeafAsync(leafUrl, cancellationToken); + #pragma warning restore CS8602 } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs b/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs index 75f7071f9..af1babee4 100644 --- a/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs +++ b/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs @@ -4,51 +4,50 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client to interact with an upstream source's Package Metadata resource. +/// +public class RawPackageMetadataClient : IPackageMetadataClient { + private readonly HttpClient _httpClient; + private readonly string _packageMetadataUrl; + /// - /// The client to interact with an upstream source's Package Metadata resource. + /// Create a new Package Metadata client. /// - public class RawPackageMetadataClient : IPackageMetadataClient + /// The HTTP client used to send requests. + /// The NuGet server's registration resource URL. + public RawPackageMetadataClient(HttpClient? httpClient, string? registrationBaseUrl) { - private readonly HttpClient _httpClient; - private readonly string _packageMetadataUrl; - - /// - /// Create a new Package Metadata client. - /// - /// The HTTP client used to send requests. - /// The NuGet server's registration resource URL. - public RawPackageMetadataClient(HttpClient httpClient, string registrationBaseUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _packageMetadataUrl = registrationBaseUrl ?? throw new ArgumentNullException(nameof(registrationBaseUrl)); - } + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _packageMetadataUrl = registrationBaseUrl ?? throw new ArgumentNullException(nameof(registrationBaseUrl)); + } - /// - public async Task GetRegistrationIndexOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var url = $"{_packageMetadataUrl}/{packageId.ToLowerInvariant()}/index.json"; + /// + public async Task GetRegistrationIndexOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var url = $"{_packageMetadataUrl}/{packageId.ToLowerInvariant()}/index.json"; - return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); - } + return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); + } - /// - public async Task GetRegistrationPageAsync( - string pageUrl, - CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); - } + /// + public async Task GetRegistrationPageAsync( + string? pageUrl, + CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); + } - /// - public async Task GetRegistrationLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); - } + /// + public async Task GetRegistrationLeafAsync( + string? leafUrl, + CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/README.md b/src/BaGet.Protocol/README.md new file mode 100644 index 000000000..4423b98c6 --- /dev/null +++ b/src/BaGet.Protocol/README.md @@ -0,0 +1,123 @@ +# Extension.BaGet.Protocol + +BaGet Extension's SDK to interact with the [NuGet protocol](https://learn.microsoft.com/nuget/api/overview). +Standalone: it does not depend on the rest of BaGet. + +[Documentation](https://pieroviano.github.io/BaGet/advanced/sdk/) | [Samples](https://github.com/pieroviano/BaGet/tree/main/samples) | [Source](https://github.com/pieroviano/BaGet) + +## Getting started + +### Install the package + +```powershell +dotnet add package Extension.BaGet.Protocol +``` + +## Examples + +### List Package Versions + +Find all versions of the `Newtonsoft.Json` package: + +```csharp +NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + +IReadOnlyList versions = await client.ListPackageVersionsAsync("Newtonsoft.Json"); + +foreach (NuGetVersion version in versions) +{ + Console.WriteLine($"Found version: {version}"); +} +``` + +### Download a package + +```csharp +NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + +string packageId = "Newtonsoft.Json"; +NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + +using (Stream packageStream = await client.DownloadPackageAsync(packageId, packageVersion)) +{ + Console.WriteLine($"Downloaded package {packageId} {packageVersion}"); +} +``` + +### Find Package Metadata + +```csharp +NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + +// Find the metadata for all versions of a package. +IReadOnlyList items = await client.GetPackageMetadataAsync("Newtonsoft.Json"); +if (!items.Any()) +{ + Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); + return; +} + +foreach (var metadata in items) +{ + Console.WriteLine($"Version: {metadata.Version}"); + Console.WriteLine($"Listed: {metadata.Listed}"); + Console.WriteLine($"Tags: {metadata.Tags}"); + Console.WriteLine($"Description: {metadata.Description}"); +} + +// Or, find the metadata for a single version of a package. +string packageId = "Newtonsoft.Json"; +NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + +PackageMetadata? metadata = await client.GetPackageMetadataAsync(packageId, packageVersion); +if (metadata == null) return; // the version does not exist + +Console.WriteLine($"Listed: {metadata.Listed}"); +Console.WriteLine($"Tags: {metadata.Tags}"); +Console.WriteLine($"Description: {metadata.Description}"); +``` + +### Search for packages + +Search for "json" packages: + +```csharp +NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); +IReadOnlyList? results = await client.SearchAsync("json"); + +foreach (SearchResult result in results ?? []) +{ + Console.WriteLine($"Found package {result.PackageId} {result.Version}"); +} +``` + +### Read a catalog + +A mirror follows a server's [catalog](https://learn.microsoft.com/nuget/api/catalog-resource) with +`CatalogProcessor`, which hands each new leaf to an `ICatalogLeafProcessor` you implement and +remembers how far it got in an `ICursor`: + +```csharp +var httpClient = new HttpClient(); +var factory = new NuGetClientFactory(httpClient, "https://api.nuget.org/v3/index.json"); + +var processor = new CatalogProcessor( + new FileCursor("cursor.json", loggerFactory.CreateLogger()), + factory.CreateCatalogClient(), + new MyLeafProcessor(), + new CatalogProcessorOptions + { + DefaultMinCommitTimestamp = DateTimeOffset.MinValue, + MaxCommitTimestamp = DateTimeOffset.MaxValue, + }, + loggerFactory.CreateLogger()); + +await processor.ProcessAsync(); +``` + +### Multiple search endpoints + +When a server's service index lists several endpoints for search or autocomplete, as nuget.org's +does, the client tries them in order and moves to the next on a network failure, a timeout, a 408, +a 429, a 5xx or an unreadable response. Any other status, such as a 404, is the server's answer and +is returned as is. The service index is re-read after 40 minutes. diff --git a/src/BaGet.Protocol/Search/AutocompleteClient.cs b/src/BaGet.Protocol/Search/AutocompleteClient.cs index de2c1c438..405877a1d 100644 --- a/src/BaGet.Protocol/Search/AutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/AutocompleteClient.cs @@ -1,48 +1,54 @@ using System; using System.Threading; using System.Threading.Tasks; +using BaGet.Protocol.Internal; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class AutocompleteClient : IAutocompleteClient { - private class AutocompleteClient : IAutocompleteClient - { - private readonly NuGetClientFactory _clientfactory; + private readonly NuGetClientFactory _clientfactory; - public AutocompleteClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public AutocompleteClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task AutocompleteAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - // TODO: Support search failover. - // See: https://github.com/loic-sharma/BaGet/issues/314 - var client = await _clientfactory.GetAutocompleteClientAsync(cancellationToken); + public async Task AutocompleteAsync( + string? query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + // The service index may advertise several autocomplete endpoints. Try them in order. + // See: https://github.com/loic-sharma/BaGet/issues/314 + var clients = await _clientfactory.GetAutocompleteClientsAsync(cancellationToken); - return await client.AutocompleteAsync(query, skip, take, includePrerelease, includeSemVer2, cancellationToken); - } + return await EndpointFailover.ExecuteAsync( + clients, + (client, token) => client.AutocompleteAsync(query, skip, take, includePrerelease, includeSemVer2, token), + cancellationToken); + } - public async Task ListPackageVersionsAsync( - string packageId, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - // TODO: Support search failover. - // See: https://github.com/loic-sharma/BaGet/issues/314 - var client = await _clientfactory.GetAutocompleteClientAsync(cancellationToken); + public async Task ListPackageVersionsAsync( + string packageId, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + // The service index may advertise several autocomplete endpoints. Try them in order. + // See: https://github.com/loic-sharma/BaGet/issues/314 + var clients = await _clientfactory.GetAutocompleteClientsAsync(cancellationToken); - return await client.ListPackageVersionsAsync(packageId, includePrerelease, includeSemVer2, cancellationToken); - } + return await EndpointFailover.ExecuteAsync( + clients, + (client, token) => client.ListPackageVersionsAsync(packageId, includePrerelease, includeSemVer2, token), + cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/IAutocompleteClient.cs b/src/BaGet.Protocol/Search/IAutocompleteClient.cs index 5afbb4a5d..3f1da4c7f 100644 --- a/src/BaGet.Protocol/Search/IAutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/IAutocompleteClient.cs @@ -2,47 +2,46 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource +/// +public interface IAutocompleteClient { /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource + /// Perform an autocomplete query on package IDs. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids /// - public interface IAutocompleteClient - { - /// - /// Perform an autocomplete query on package IDs. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids - /// - /// The autocomplete query. - /// How many results to skip. - /// How many results to return. - /// Whether pre-release packages should be returned. - /// Whether packages that require SemVer 2.0.0 compatibility should be returned. - /// A token to cancel the task. - /// The autocomplete response. - Task AutocompleteAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default); + /// The autocomplete query. + /// How many results to skip. + /// How many results to return. + /// Whether pre-release packages should be returned. + /// Whether packages that require SemVer 2.0.0 compatibility should be returned. + /// A token to cancel the task. + /// The autocomplete response. + Task AutocompleteAsync( + string? query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default); - /// - /// Enumerate listed package versions. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions - /// - /// The package ID. - /// Whether pre-release packages should be returned. - /// Whether packages that require SemVer 2.0.0 compatibility should be returned. - /// A token to cancel the task. - /// The package versions that matched the request. - Task ListPackageVersionsAsync( - string packageId, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default); - } -} + /// + /// Enumerate listed package versions. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions + /// + /// The package ID. + /// Whether pre-release packages should be returned. + /// Whether packages that require SemVer 2.0.0 compatibility should be returned. + /// A token to cancel the task. + /// The package versions that matched the request. + Task ListPackageVersionsAsync( + string packageId, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/ISearchClient.cs b/src/BaGet.Protocol/Search/ISearchClient.cs index 6b21029b0..8aba8b952 100644 --- a/src/BaGet.Protocol/Search/ISearchClient.cs +++ b/src/BaGet.Protocol/Search/ISearchClient.cs @@ -2,32 +2,31 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource +/// +public interface ISearchClient { /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// Perform a search query. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages /// - public interface ISearchClient - { - /// - /// Perform a search query. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages - /// - /// The search query. - /// How many results to skip. - /// How many results to return. - /// Whether pre-release packages should be returned. - /// Whether packages that require SemVer 2.0.0 compatibility should be returned. - /// A token to cancel the task. - /// The search response. - Task SearchAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default); - } -} + /// The search query. + /// How many results to skip. + /// How many results to return. + /// Whether pre-release packages should be returned. + /// Whether packages that require SemVer 2.0.0 compatibility should be returned. + /// A token to cancel the task. + /// The search response. + Task SearchAsync( + string? query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/NullAutocompleteClient.cs b/src/BaGet.Protocol/Search/NullAutocompleteClient.cs index 326193880..e3ca08a17 100644 --- a/src/BaGet.Protocol/Search/NullAutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/NullAutocompleteClient.cs @@ -3,26 +3,25 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +public class NullAutocompleteClient : IAutocompleteClient { - public class NullAutocompleteClient : IAutocompleteClient + public Task AutocompleteAsync(string? query = null, int skip = 0, int take = 20, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) { - public Task AutocompleteAsync(string query = null, int skip = 0, int take = 20, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) + return Task.FromResult(new AutocompleteResponse { - return Task.FromResult(new AutocompleteResponse - { - TotalHits = 0, - Data = new List() - }); - } + TotalHits = 0, + Data = new List() + }); + } - public Task ListPackageVersionsAsync(string packageId, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) + public Task ListPackageVersionsAsync(string packageId, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) + { + return Task.FromResult(new AutocompleteResponse { - return Task.FromResult(new AutocompleteResponse - { - TotalHits = 0, - Data = new List() - }); - } + TotalHits = 0, + Data = new List() + }); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/RawAutocompleteClient.cs b/src/BaGet.Protocol/Search/RawAutocompleteClient.cs index 26f63be00..093ecc752 100644 --- a/src/BaGet.Protocol/Search/RawAutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/RawAutocompleteClient.cs @@ -4,65 +4,64 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource +/// +public class RawAutocompleteClient : IAutocompleteClient { + private readonly HttpClient _httpClient; + private readonly string _autocompleteUrl; + /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource + /// Create a new Search client. /// - public class RawAutocompleteClient : IAutocompleteClient + /// The HTTP client used to send requests. + /// The NuGet server's autocomplete URL. + public RawAutocompleteClient(HttpClient? httpClient, string? autocompleteUrl) { - private readonly HttpClient _httpClient; - private readonly string _autocompleteUrl; - - /// - /// Create a new Search client. - /// - /// The HTTP client used to send requests. - /// The NuGet server's autocomplete URL. - public RawAutocompleteClient(HttpClient httpClient, string autocompleteUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _autocompleteUrl = autocompleteUrl ?? throw new ArgumentNullException(nameof(autocompleteUrl)); - } + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _autocompleteUrl = autocompleteUrl ?? throw new ArgumentNullException(nameof(autocompleteUrl)); + } - public async Task AutocompleteAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - var url = RawSearchClient.AddSearchQueryString( - _autocompleteUrl, - query, - skip, - take, - includePrerelease, - includeSemVer2, - "q"); + public async Task AutocompleteAsync( + string? query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + var url = RawSearchClient.AddSearchQueryString( + _autocompleteUrl, + query, + skip, + take, + includePrerelease, + includeSemVer2, + "q"); - return await _httpClient.GetFromJsonAsync(url, cancellationToken); - } + return await _httpClient.GetFromJsonAsync(url, cancellationToken); + } - public async Task ListPackageVersionsAsync( - string packageId, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - var url = RawSearchClient.AddSearchQueryString( - _autocompleteUrl, - packageId, - skip: null, - take: null, - includePrerelease, - includeSemVer2, - "id"); + public async Task ListPackageVersionsAsync( + string? packageId, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + var url = RawSearchClient.AddSearchQueryString( + _autocompleteUrl, + packageId, + skip: null, + take: null, + includePrerelease, + includeSemVer2, + "id"); - return await _httpClient.GetFromJsonAsync(url, cancellationToken); - } + return await _httpClient.GetFromJsonAsync(url, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/RawSearchClient.cs b/src/BaGet.Protocol/Search/RawSearchClient.cs index 914b08b41..9aa153e19 100644 --- a/src/BaGet.Protocol/Search/RawSearchClient.cs +++ b/src/BaGet.Protocol/Search/RawSearchClient.cs @@ -6,85 +6,86 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource +/// +public class RawSearchClient : ISearchClient { + private readonly HttpClient _httpClient; + private readonly string _searchUrl; + /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// Create a new Search client. /// - public class RawSearchClient : ISearchClient + /// The HTTP client used to send requests. + /// The NuGet server's search URL. + public RawSearchClient(HttpClient? httpClient, string? searchUrl) { - private readonly HttpClient _httpClient; - private readonly string _searchUrl; - - /// - /// Create a new Search client. - /// - /// The HTTP client used to send requests. - /// The NuGet server's search URL. - public RawSearchClient(HttpClient httpClient, string searchUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _searchUrl = searchUrl ?? throw new ArgumentNullException(nameof(searchUrl)); - } - - public async Task SearchAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - var url = AddSearchQueryString(_searchUrl, query, skip, take, includePrerelease, includeSemVer2, "q"); + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _searchUrl = searchUrl ?? throw new ArgumentNullException(nameof(searchUrl)); + } - return await _httpClient.GetFromJsonAsync(url, cancellationToken); - } + public async Task SearchAsync( + string? query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + var url = AddSearchQueryString(_searchUrl, query, skip, take, includePrerelease, includeSemVer2, "q"); - internal static string AddSearchQueryString( - string uri, - string query, - int? skip, - int? take, - bool includePrerelease, - bool includeSemVer2, - string queryParamName) - { - var queryString = new Dictionary(); + return await _httpClient.GetFromJsonAsync(url, cancellationToken); + } - if (skip.HasValue && skip.Value > 0) queryString["skip"] = skip.ToString(); - if (take.HasValue) queryString["take"] = take.ToString(); - if (includePrerelease) queryString["prerelease"] = true.ToString(); - if (includeSemVer2) queryString["semVerLevel"] = "2.0.0"; + internal static string AddSearchQueryString( + string uri, + string? query, + int? skip, + int? take, + bool includePrerelease, + bool includeSemVer2, + string queryParamName) + { + var queryString = new Dictionary(); - if (!string.IsNullOrEmpty(query)) - { - queryString[queryParamName] = query; - } + #pragma warning disable CS8601 + if (skip.HasValue && skip.Value > 0) queryString["skip"] = skip.ToString(); + if (take.HasValue) queryString["take"] = take.ToString(); + #pragma warning restore CS8601 + if (includePrerelease) queryString["prerelease"] = true.ToString(); + if (includeSemVer2) queryString["semVerLevel"] = "2.0.0"; - return AddQueryString(uri, queryString); + if (!string.IsNullOrEmpty(query)) + { + queryString[queryParamName] = query; } - // See: https://github.com/aspnet/AspNetCore/blob/8c02467b4a218df3b1b0a69bceb50f5b64f482b1/src/Http/WebUtilities/src/QueryHelpers.cs#L63 - private static string AddQueryString(string uri, Dictionary queryString) - { - if (uri.IndexOf('#') != -1) throw new InvalidOperationException("URL anchors are not supported"); - if (uri.IndexOf('?') != -1) throw new InvalidOperationException("Adding query strings to URL with query strings is not supported"); + return AddQueryString(uri, queryString); + } - var builder = new StringBuilder(uri); - var hasQuery = false; + // See: https://github.com/aspnet/AspNetCore/blob/8c02467b4a218df3b1b0a69bceb50f5b64f482b1/src/Http/WebUtilities/src/QueryHelpers.cs#L63 + private static string AddQueryString(string uri, Dictionary queryString) + { + if (uri.IndexOf('#') != -1) throw new InvalidOperationException("URL anchors are not supported"); + if (uri.IndexOf('?') != -1) throw new InvalidOperationException("Adding query strings to URL with query strings is not supported"); - foreach (var parameter in queryString) - { - builder.Append(hasQuery ? '&' : '?'); - builder.Append(Uri.EscapeDataString(parameter.Key)); - builder.Append('='); - builder.Append(Uri.EscapeDataString(parameter.Value)); - hasQuery = true; - } + var builder = new StringBuilder(uri); + var hasQuery = false; - return builder.ToString(); + foreach (var parameter in queryString) + { + builder.Append(hasQuery ? '&' : '?'); + builder.Append(Uri.EscapeDataString(parameter.Key)); + builder.Append('='); + builder.Append(Uri.EscapeDataString(parameter.Value)); + hasQuery = true; } + + return builder.ToString(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/SearchClient.cs b/src/BaGet.Protocol/Search/SearchClient.cs index b6bca0d94..e37cd0eb3 100644 --- a/src/BaGet.Protocol/Search/SearchClient.cs +++ b/src/BaGet.Protocol/Search/SearchClient.cs @@ -1,35 +1,38 @@ using System; using System.Threading; using System.Threading.Tasks; +using BaGet.Protocol.Internal; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class SearchClient : ISearchClient { - private class SearchClient : ISearchClient - { - private readonly NuGetClientFactory _clientfactory; + private readonly NuGetClientFactory _clientfactory; - public SearchClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public SearchClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task SearchAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - // TODO: Support search failover. - // See: https://github.com/loic-sharma/BaGet/issues/314 - var client = await _clientfactory.GetSearchClientAsync(cancellationToken); + public async Task SearchAsync( + string? query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + // The service index may advertise several search endpoints. Try them in order. + // See: https://github.com/loic-sharma/BaGet/issues/314 + var clients = await _clientfactory.GetSearchClientsAsync(cancellationToken); - return await client.SearchAsync(query, skip, take, includePrerelease, includeSemVer2); - } + return await EndpointFailover.ExecuteAsync( + clients, + (client, token) => client.SearchAsync(query, skip, take, includePrerelease, includeSemVer2, token), + cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs b/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs index 73fc2cfbc..927fba890 100644 --- a/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs +++ b/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs @@ -2,20 +2,19 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The NuGet Service Index client, used to discover other resources. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index +/// +public interface IServiceIndexClient { /// - /// The NuGet Service Index client, used to discover other resources. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// Get the resources available on this package feed. + /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources /// - public interface IServiceIndexClient - { - /// - /// Get the resources available on this package feed. - /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources - /// - /// The resources available on this package feed. - Task GetAsync(CancellationToken cancellationToken = default); - } -} + /// The resources available on this package feed. + Task GetAsync(CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs b/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs index 70d85669c..969b0a6fb 100644 --- a/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs +++ b/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs @@ -4,35 +4,34 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The NuGet Service Index client, used to discover other resources. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index +/// +public class RawServiceIndexClient : IServiceIndexClient { + private readonly HttpClient _httpClient; + private readonly string _serviceIndexUrl; + /// - /// The NuGet Service Index client, used to discover other resources. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// Create a service index for the upstream source. /// - public class RawServiceIndexClient : IServiceIndexClient + /// The HTTP client used to send requests. + /// The NuGet server's service index URL. + public RawServiceIndexClient(HttpClient? httpClient, string? serviceIndexUrl) { - private readonly HttpClient _httpClient; - private readonly string _serviceIndexUrl; - - /// - /// Create a service index for the upstream source. - /// - /// The HTTP client used to send requests. - /// The NuGet server's service index URL. - public RawServiceIndexClient(HttpClient httpClient, string serviceIndexUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); - } + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); + } - /// - public async Task GetAsync(CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync( - _serviceIndexUrl, - cancellationToken); - } + /// + public async Task GetAsync(CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync( + _serviceIndexUrl, + cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs b/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs index a429b60f6..08bd80392 100644 --- a/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs +++ b/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs @@ -3,23 +3,22 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class ServiceIndexClient : IServiceIndexClient { - private class ServiceIndexClient : IServiceIndexClient - { - private readonly NuGetClientFactory _clientFactory; + private readonly NuGetClientFactory _clientFactory; - public ServiceIndexClient(NuGetClientFactory clientFactory) - { - _clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public ServiceIndexClient(NuGetClientFactory clientFactory) + { + _clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task GetAsync(CancellationToken cancellationToken = default) - { - return await _clientFactory.GetServiceIndexAsync(cancellationToken); - } + public async Task GetAsync(CancellationToken cancellationToken = default) + { + return await _clientFactory.GetServiceIndexAsync(cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/readme.md b/src/BaGet.Protocol/readme.md deleted file mode 100644 index 1d40f04a3..000000000 --- a/src/BaGet.Protocol/readme.md +++ /dev/null @@ -1,92 +0,0 @@ -# BaGet.Protocol - -[![Build Status](https://sharml.visualstudio.com/BaGet/_apis/build/status/loic-sharma.BaGet)](https://sharml.visualstudio.com/BaGet/_build/latest?definitionId=2) [![Join the chat at https://gitter.im/BaGetServer/community](https://badges.gitter.im/BaGetServer/community.svg)](https://gitter.im/BaGetServer/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Nuget](https://img.shields.io/nuget/dt/BaGet.Protocol)](https://www.nuget.org/packages/BaGet.Protocol) - -BaGet's SDK to interact with the [NuGet protocol](https://docs.microsoft.com/en-us/nuget/api/overview). - -[Package (NuGet)](https://www.nuget.org/packages/BaGet.Protocol) | [Documentation](https://loic-sharma.github.io/BaGet/advanced/sdk/) | [Samples](https://github.com/loic-sharma/BaGet/tree/master/samples) - -## Getting started - -### Install the package - -```powershell -dotnet add package BaGet.Protocol -``` - -## Examples - -### List Package Versions - -Find all versions of the `Newtonsoft.Json` package: - -```csharp -NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - -IReadOnlyList> versions = await client.ListPackageVersionsAsync("Newtonsoft.Json"); - -foreach (NuGetVersion version in versions) -{ - Console.WriteLine($"Found version: {version}"); -} -``` - -### Download a package - -```csharp -NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - -string packageId = "Newtonsoft.Json"; -NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - -using (Stream packageStream = await client.DownloadPackageAsync(packageId, packageVersion)) -{ - Console.WriteLine($"Downloaded package {packageId} {packageVersion}"); -} -``` - -### Find Package Metadata - -```csharp -NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - -// Find the metadata for all versions of a package. -IReadOnlyList items = await client.GetPackageMetadataAsync("Newtonsoft.Json"); -if (!items.Any()) -{ - Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); - return; -} - -foreach (var metadata in items) -{ - Console.WriteLine($"Version: {metadata.Version}"); - Console.WriteLine($"Listed: {metadata.Listed}"); - Console.WriteLine($"Tags: {metadata.Tags}"); - Console.WriteLine($"Description: {metadata.Description}"); -} - -// Or, find the metadata for a single version of a package. -string packageId = "Newtonsoft.Json" -NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - -PackageMetadata metadata = await client.GetPackageMetadataAsync(packageId, packageVersion); - -Console.WriteLine($"Listed: {metadata.Listed}"); -Console.WriteLine($"Tags: {metadata.Tags}"); -Console.WriteLine($"Description: {metadata.Description}"); -``` - -### Search for packages - -Search for "json" packages: - -```csharp -NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); -IReadOnlyList results = await client.SearchAsync("json"); - -foreach (SearchResult result in results) -{ - Console.WriteLine($"Found package {result.PackageId} {searchResult.Version}"); -} -``` diff --git a/src/BaGet.Validation/BaGet.Validation.csproj b/src/BaGet.Validation/BaGet.Validation.csproj new file mode 100644 index 000000000..ee3c8eebb --- /dev/null +++ b/src/BaGet.Validation/BaGet.Validation.csproj @@ -0,0 +1,29 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's validation pipeline: pushed packages are validated, and optionally repository signed, before they are served. + BaGet.Validation + enable + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Validation/Controllers/Protocols/RepositorySignaturesController.cs b/src/BaGet.Validation/Controllers/Protocols/RepositorySignaturesController.cs new file mode 100644 index 000000000..1582f3604 --- /dev/null +++ b/src/BaGet.Validation/Controllers/Protocols/RepositorySignaturesController.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using BaGet.Core; +using Microsoft.AspNetCore.Mvc; +using BaGet.Validation.Models; +using BaGet.Validation.Signing; + +namespace BaGet.Validation.Controllers.Protocols; + +/// +/// The RepositorySignatures/5.0.0 resource, and each submission's validation status. +/// +public class RepositorySignaturesController : Controller +{ + // The OID the protocol keys a SHA-256 fingerprint by. + internal const string Sha256Oid = "2.16.840.1.101.3.4.2.1"; + + private readonly RepositorySigner _signer; + private readonly IUrlGenerator _url; + + public RepositorySignaturesController(RepositorySigner signer, IUrlGenerator url) + { + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } + + [HttpGet] + public IActionResult Index() + { + using var certificate = _signer.GetPublicCertificateOrNull(); + if (certificate == null) return NotFound(); + + var fingerprint = Fingerprint(certificate.RawData); + + return Json(new RepositorySignaturesResponse + { + // Packages pushed before signing was configured, and mirrored ones, are not + // repository signed, so a client must not insist that every package is. + AllRepositorySigned = false, + SigningCertificates = new[] + { + new RepositorySigningCertificate + { + Fingerprints = new Dictionary { [Sha256Oid] = fingerprint }, + Subject = certificate.Subject, + Issuer = certificate.Issuer, + NotBefore = certificate.NotBefore.ToUniversalTime(), + NotAfter = certificate.NotAfter.ToUniversalTime(), + ContentUrl = _url.GetRepositorySigningCertificateUrl(fingerprint), + }, + }, + }); + } + + [HttpGet] + public IActionResult Certificate(string fingerprint) + { + using var certificate = _signer.GetPublicCertificateOrNull(); + if (certificate == null || !string.Equals(Fingerprint(certificate.RawData), fingerprint, StringComparison.OrdinalIgnoreCase)) + { + return NotFound(); + } + + return File(certificate.RawData, "application/pkix-cert"); + } + + internal static string Fingerprint(byte[] certificate) + => Convert.ToHexString(SHA256.HashData(certificate)).ToLowerInvariant(); +} diff --git a/src/BaGet.Validation/Controllers/Protocols/ValidationStatusController.cs b/src/BaGet.Validation/Controllers/Protocols/ValidationStatusController.cs new file mode 100644 index 000000000..2bf759f42 --- /dev/null +++ b/src/BaGet.Validation/Controllers/Protocols/ValidationStatusController.cs @@ -0,0 +1,79 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; +using BaGet.Validation.Models; + +namespace BaGet.Validation.Controllers.Protocols; + +/// +/// A package version's validation, for its owners: whether it is pending, available +/// or quarantined, and why. +/// +public class ValidationStatusController : Controller +{ + private readonly IContext _context; + private readonly Core.IAuthenticationService _authentication; + private readonly IPackageAuthorizationService _authorization; + + public ValidationStatusController( + IContext context, + Core.IAuthenticationService authentication, + IPackageAuthorizationService authorization) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + } + + [HttpGet] + public async Task Get(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) return NotFound(); + + var principal = await _authentication.AuthenticatePrincipalAsync(Request.Headers["X-NuGet-ApiKey"], cancellationToken); + if (principal == null) return Unauthorized(); + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, id, cancellationToken) + && !await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) + { + return StatusCode(403); + } + + if (_context is NullContext) return NotFound(); + + var lowerId = id.ToLowerInvariant(); + var normalized = nugetVersion.ToNormalizedString(); + #pragma warning disable CS8602, CS8604 + var steps = await _context.PackageValidations + .AsNoTracking() + .Where(v => v.PackageId.ToLower() == lowerId && v.PackageVersion == normalized) + .OrderByDescending(v => v.Key) + .ToListAsync(cancellationToken); + #pragma warning restore CS8602, CS8604 + + if (steps.Count == 0) return NotFound(); + + // The newest submission is the one that matters. + var latest = steps[0].SubmissionId; + var submission = steps.Where(s => s.SubmissionId == latest).OrderBy(s => s.Key).ToList(); + var index = submission.Single(s => s.Type == PackageValidation.IndexType); + + return Json(new ValidationStatusResponse + { + SubmissionId = latest, + Status = index.State switch + { + PackageValidationState.Succeeded => "Available", + PackageValidationState.Failed => "Quarantined", + _ => "Validating", + }, + Steps = submission + .Select(s => new ValidationStep { Type = s.Type, State = s.State.ToString(), Message = s.Message }) + .ToList(), + }); + } +} diff --git a/src/BaGet.Validation/Extensions/ValidationServiceCollectionExtensions.cs b/src/BaGet.Validation/Extensions/ValidationServiceCollectionExtensions.cs new file mode 100644 index 000000000..b096eadac --- /dev/null +++ b/src/BaGet.Validation/Extensions/ValidationServiceCollectionExtensions.cs @@ -0,0 +1,34 @@ +using BaGet.Core; +using BaGet.Validation.Services; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using BaGet.Validation.Pipeline; +using BaGet.Validation.Queue; +using BaGet.Validation.Signing; + +namespace BaGet.Validation.Extensions; + +public static class ValidationServiceCollectionExtensions +{ + /// + /// Always registered; whether a push is validated is read from "Validation:Enabled" + /// on every push, so with it off the only difference is an idle worker. + /// + public static IServiceCollection AddBaGetValidation(this IServiceCollection services) + { + services.Replace(ServiceDescriptor.Transient()); + + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); + + services.AddHostedService(); + + return services; + } +} \ No newline at end of file diff --git a/src/BaGet.Validation/Models/RepositorySignaturesResponse.cs b/src/BaGet.Validation/Models/RepositorySignaturesResponse.cs new file mode 100644 index 000000000..bff33c570 --- /dev/null +++ b/src/BaGet.Validation/Models/RepositorySignaturesResponse.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; +using BaGet.Validation.Signing; + +namespace BaGet.Validation.Models; + +public class RepositorySignaturesResponse +{ + [JsonPropertyName("allRepositorySigned")] + public bool AllRepositorySigned { get; set; } + + [JsonPropertyName("signingCertificates")] + public IReadOnlyList? SigningCertificates { get; set; } +} diff --git a/src/BaGet.Validation/Models/ValidationStatusResponse.cs b/src/BaGet.Validation/Models/ValidationStatusResponse.cs new file mode 100644 index 000000000..0bfb83650 --- /dev/null +++ b/src/BaGet.Validation/Models/ValidationStatusResponse.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace BaGet.Validation.Models; + +public class ValidationStatusResponse +{ + [JsonPropertyName("submissionId")] + public string? SubmissionId { get; set; } + + /// + /// "Validating", "Available" or "Quarantined". + /// + [JsonPropertyName("status")] + public string? Status { get; set; } + + [JsonPropertyName("steps")] + public IReadOnlyList? Steps { get; set; } +} diff --git a/src/BaGet.Validation/Models/ValidationStep.cs b/src/BaGet.Validation/Models/ValidationStep.cs new file mode 100644 index 000000000..16eb3aff6 --- /dev/null +++ b/src/BaGet.Validation/Models/ValidationStep.cs @@ -0,0 +1,15 @@ +using System.Text.Json.Serialization; + +namespace BaGet.Validation.Models; + +public class ValidationStep +{ + [JsonPropertyName("type")] + public string? Type { get; set; } + + [JsonPropertyName("state")] + public string? State { get; set; } + + [JsonPropertyName("message")] + public string? Message { get; set; } +} diff --git a/src/BaGet.Validation/Pipeline/ActiveRun.cs b/src/BaGet.Validation/Pipeline/ActiveRun.cs new file mode 100644 index 000000000..8503fc9fd --- /dev/null +++ b/src/BaGet.Validation/Pipeline/ActiveRun.cs @@ -0,0 +1,11 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Validation.Pipeline; + +/// A validation this process is running: lets a reject cancel it and wait for its end. +internal sealed class ActiveRun +{ + public CancellationTokenSource Cancel { get; } = new(); + public TaskCompletionSource Finished { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); +} diff --git a/src/BaGet.Validation/Pipeline/IPackageValidator.cs b/src/BaGet.Validation/Pipeline/IPackageValidator.cs new file mode 100644 index 000000000..83ab499f0 --- /dev/null +++ b/src/BaGet.Validation/Pipeline/IPackageValidator.cs @@ -0,0 +1,18 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Validation.Pipeline; + +/// +/// Decides whether a pushed package may be served. Register any number, for example a +/// malware scanner; every one must pass. A validator that throws fails the package. +/// +public interface IPackageValidator +{ + /// + /// Recorded as the validation step's type, so it must be stable and unique. + /// + string Name { get; } + + Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken); +} diff --git a/src/BaGet.Validation/Pipeline/PackageEntriesValidator.cs b/src/BaGet.Validation/Pipeline/PackageEntriesValidator.cs new file mode 100644 index 000000000..0dd4a5f5b --- /dev/null +++ b/src/BaGet.Validation/Pipeline/PackageEntriesValidator.cs @@ -0,0 +1,26 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Validation.Pipeline; + +/// +/// Every entry's path must be safe to extract: none may escape the package's folder. +/// +public class PackageEntriesValidator : IPackageValidator +{ + public string Name => "PackageEntries"; + + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + try + { + await context.Reader.ValidatePackageEntriesAsync(cancellationToken); + + return PackageValidatorResult.Valid; + } + catch (NuGet.Packaging.Core.PackagingException e) + { + return PackageValidatorResult.Invalid(e.Message); + } + } +} diff --git a/src/BaGet.Validation/Pipeline/PackageSignatureValidator.cs b/src/BaGet.Validation/Pipeline/PackageSignatureValidator.cs new file mode 100644 index 000000000..fd0b2632f --- /dev/null +++ b/src/BaGet.Validation/Pipeline/PackageSignatureValidator.cs @@ -0,0 +1,73 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.Options; +using NuGet.Common; +using NuGet.Packaging.Signing; + +namespace BaGet.Validation.Pipeline; + +/// +/// A signed package must have an intact, valid signature; an unsigned one is rejected +/// only when is set. Whether the +/// signing certificate is trusted is not checked: that is the client's policy to apply. +/// +public class PackageSignatureValidator : IPackageValidator +{ + private readonly IOptionsSnapshot _options; + + public PackageSignatureValidator(IOptionsSnapshot options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public string Name => "PackageSignature"; + + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + if (!await context.Reader.IsSignedAsync(cancellationToken)) + { + return _options.Value.RequireSignedPackages + ? PackageValidatorResult.Invalid("The package must be signed.") + : PackageValidatorResult.Valid; + } + + var verifier = new PackageSignatureVerifier(new ISignatureVerificationProvider[] + { + new IntegrityVerificationProvider(), + new SignatureTrustAndValidityVerificationProvider(), + }); + + // Untrusted roots are allowed: a private feed's packages are often signed with + // an internal certificate the server's machine does not trust. + var settings = new SignedPackageVerifierSettings( + allowUnsigned: false, + allowIllegal: false, + allowUntrusted: true, + allowIgnoreTimestamp: true, + allowMultipleTimestamps: true, + allowNoTimestamp: true, + allowUnknownRevocation: true, + reportUnknownRevocation: false, + verificationTarget: VerificationTarget.All, + signaturePlacement: SignaturePlacement.Any, + repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.IfExistsAndIsNecessary, + revocationMode: RevocationMode.Offline); + + var result = await verifier.VerifySignaturesAsync(context.Reader, settings, cancellationToken); + if (result.IsValid) + { + return PackageValidatorResult.Valid; + } + + var errors = result.Results + .SelectMany(r => r.GetErrorIssues()) + .Select(i => $"{i.Code}: {i.Message}") + .ToList(); + + return PackageValidatorResult.Invalid( + errors.Count == 0 ? "The package's signature is invalid." : string.Join(" ", errors)); + } +} \ No newline at end of file diff --git a/src/BaGet.Validation/Pipeline/PackageValidationContext.cs b/src/BaGet.Validation/Pipeline/PackageValidationContext.cs new file mode 100644 index 000000000..f07dbec17 --- /dev/null +++ b/src/BaGet.Validation/Pipeline/PackageValidationContext.cs @@ -0,0 +1,30 @@ +using System.IO; +using NuGet.Packaging; +using NuGet.Versioning; + +namespace BaGet.Validation.Pipeline; + +public sealed class PackageValidationContext +{ + public PackageValidationContext(string packageId, NuGetVersion packageVersion, Stream package, PackageArchiveReader reader) + { + PackageId = packageId; + PackageVersion = packageVersion; + Package = package; + Reader = reader; + } + + public string PackageId { get; } + + public NuGetVersion PackageVersion { get; } + + /// + /// The raw package. Seekable; a validator must not dispose it. + /// + public Stream Package { get; } + + /// + /// A reader over . A validator must not dispose it. + /// + public PackageArchiveReader Reader { get; } +} diff --git a/src/BaGet.Validation/Pipeline/PackageValidationRunner.cs b/src/BaGet.Validation/Pipeline/PackageValidationRunner.cs new file mode 100644 index 000000000..2a485fb14 --- /dev/null +++ b/src/BaGet.Validation/Pipeline/PackageValidationRunner.cs @@ -0,0 +1,376 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Validation.Services; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Packaging; +using BaGet.Validation.Signing; + +namespace BaGet.Validation.Pipeline; + +/// +/// Runs one submission: every validator, then, if all passed, repository signing and +/// indexing. A package that fails stays staged, quarantined, for its owners to inspect. +/// +public class PackageValidationRunner +{ + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IPackageIndexingService _indexer; + private readonly IPackageDatabase _packages; + private readonly IEnumerable _validators; + private readonly RepositorySigner _signer; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly ILogger _logger; + private readonly IRepositoryContext _repository; + private readonly IRepositoryService _repositories; + + // Submissions being validated by this process: a reject cancels the run and waits for it to end. + private static readonly System.Collections.Concurrent.ConcurrentDictionary Running = new(); + + /// + /// Stops this process's validation of the submission, if any, and waits (bounded) until it has ended, so nothing is + /// published after the caller removes the submission. False when it did not end in time. + /// + internal static async Task StopRunAsync(string submissionId, CancellationToken cancellationToken) + { + if (!Running.TryGetValue(submissionId, out var run)) return true; + + run.Cancel.Cancel(); + var finished = await Task.WhenAny(run.Finished.Task, Task.Delay(TimeSpan.FromSeconds(30), cancellationToken)); + + return finished == run.Finished.Task; + } + + public PackageValidationRunner( + IContext context, + IStorageService storage, + IPackageIndexingService indexer, + IPackageDatabase packages, + IEnumerable validators, + RepositorySigner signer, + SystemTime time, + IOptionsSnapshot options, + ILogger logger, + IRepositoryContext repository, + IRepositoryService repositories) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _validators = validators ?? throw new ArgumentNullException(nameof(validators)); + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task?> GetPendingSubmissionIdsAsync(CancellationToken cancellationToken) + { + #pragma warning disable CS8604, CS8619 + // Every repository's: the worker is not tied to one, RunAsync switches to the submission's. + return await _context.PackageValidations + .IgnoreQueryFilters() + .Where(v => v.State == PackageValidationState.Pending) + .Select(v => v.SubmissionId) + .Distinct() + .ToListAsync(cancellationToken); + #pragma warning restore CS8604, CS8619 + } + + public async Task RunAsync(string submissionId, CancellationToken cancellationToken) + { + var run = new ActiveRun(); + Running[submissionId] = run; + try + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, run.Cancel.Token); + try + { + await RunTrackedAsync(submissionId, linked.Token); + } + catch (OperationCanceledException) when (run.Cancel.IsCancellationRequested && !cancellationToken.IsCancellationRequested) + { + _logger.LogInformation("Validation of submission {SubmissionId} was stopped because it is being rejected", submissionId); + } + } + finally + { + Running.TryRemove(submissionId, out _); + run.Finished.TrySetResult(true); + run.Cancel.Dispose(); + } + } + + private async Task RunTrackedAsync(string submissionId, CancellationToken cancellationToken) + { + // Costs nothing without a listener. A submission with nothing pending (already finished) is not a validation. + using var activity = BaGetDiagnostics.Source.StartActivity(BaGetDiagnostics.Spans.PackageValidate); + + try + { + var result = await RunCoreAsync(submissionId, activity, cancellationToken); + if (result == null) + { + activity?.SetTag(BaGetDiagnostics.Tags.Result, "Skipped"); + return; + } + + activity?.SetTag(BaGetDiagnostics.Tags.Result, result); + BaGetDiagnostics.ValidationResults.Add(1, new KeyValuePair(BaGetDiagnostics.Tags.Result, result)); + } + catch (Exception e) + { + BaGetDiagnostics.Fail(activity, e); + BaGetDiagnostics.ValidationResults.Add(1, new KeyValuePair(BaGetDiagnostics.Tags.Result, "error")); + + throw; + } + } + + /// "Succeeded" or "Failed" (quarantined), or null when there was nothing to run. + private async Task RunCoreAsync(string submissionId, Activity? activity, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + // A queued submission names no repository: find it in whichever one it belongs to, then work there, so + // the indexing below lands in that repository. + var steps = await _context.PackageValidations + .IgnoreQueryFilters() + .Where(v => v.SubmissionId == submissionId) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + if (!await UseSubmissionRepositoryAsync(steps, submissionId, cancellationToken)) + { + return null; + } + + var index = steps.SingleOrDefault(s => s.Type == PackageValidation.IndexType); + if (index == null || index.State != PackageValidationState.Pending) + { + return null; + } + + activity?.SetTag(BaGetDiagnostics.Tags.PackageId, index.PackageId); + activity?.SetTag(BaGetDiagnostics.Tags.PackageVersion, index.PackageVersion); + + using var package = new MemoryStream(); + using (var staged = await _storage.GetAsync(ValidatingPackageSubmissionService.StagedPath(_repository.Current, submissionId), cancellationToken)) + { + await staged.CopyToAsync(package, cancellationToken); + } + + package.Position = 0; + + using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) + { + var identity = await reader.GetIdentityAsync(cancellationToken); + var context = new PackageValidationContext(identity.Id, identity.Version, package, reader); + + foreach (var validator in _validators) + { + var step = steps.FirstOrDefault(s => s.Type == validator.Name); + if (step == null || step.State != PackageValidationState.Pending) continue; + + PackageValidatorResult result; + try + { + package.Position = 0; + result = await validator.ValidateAsync(context, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException) && !(e is MaintenanceException)) + { + _logger.LogError(e, "Validator {Validator} failed on submission {SubmissionId}", validator.Name, submissionId); + result = PackageValidatorResult.Invalid($"The {validator.Name} validator failed: {e.Message}"); + } + + Complete(step, result.IsValid, result.Message); + } + } + + // A step whose validator is no longer registered cannot pass. + foreach (var orphan in steps.Where(s => s.State == PackageValidationState.Pending && s != index)) + { + Complete(orphan, succeeded: false, $"The {orphan.Type} validator is no longer registered."); + } + + if (steps.Any(s => s.State == PackageValidationState.Failed)) + { + Complete(index, succeeded: false, "Quarantined: the package failed validation."); + await _context.SaveChangesAsync(cancellationToken); + + _logger.LogWarning("Submission {SubmissionId} failed validation and is quarantined", submissionId); + return "Failed"; + } + + // Rejected (rows gone) while the validators ran, possibly on another node: do not publish what was refused. + #pragma warning disable CS8604 + var stillPending = await _context.PackageValidations + .IgnoreQueryFilters() + .AsNoTracking() + .AnyAsync(v => v.SubmissionId == submissionId && v.Type == PackageValidation.IndexType && v.State == PackageValidationState.Pending, cancellationToken); + #pragma warning restore CS8604 + if (!stillPending) + { + _logger.LogWarning("Submission {SubmissionId} was rejected while it was validated; not indexed", submissionId); + return null; + } + + var indexError = await IndexAsync(package, _options.Value.RepositorySigningServiceIndexUrl, cancellationToken); + Complete(index, indexError == null, indexError); + + if (indexError == null) + { + #pragma warning disable CS8604 + var version = NuGet.Versioning.NuGetVersion.Parse(index.PackageVersion); + #pragma warning restore CS8604 + var indexed = await _packages.FindOrNullAsync(index.PackageId, version, includeUnlisted: true, cancellationToken); + foreach (var step in steps) + { + step.PackageKey = indexed?.Key; + } + } + + await _context.SaveChangesAsync(cancellationToken); + + if (indexError == null) + { + await _storage.DeleteAsync(ValidatingPackageSubmissionService.StagedPath(_repository.Current, submissionId), cancellationToken); + } + + return indexError == null ? "Succeeded" : "Failed"; + } + + /// + /// Switches the scope to the repository a submission belongs to. + /// + /// False when that repository no longer exists. + internal async Task UseSubmissionRepositoryAsync(IReadOnlyList steps, string submissionId, CancellationToken cancellationToken) + { + if (steps.Count > 0 && steps[0].RepositoryKey != _repository.Current.Key) + { + var target = await _repositories.FindAsync(steps[0].RepositoryKey, cancellationToken); + if (target == null) + { + _logger.LogWarning("Submission {SubmissionId} belongs to unknown repository {Key}", submissionId, steps[0].RepositoryKey); + return false; + } + + _repository.Use(target); + } + + return true; + } + + /// + /// Indexes a quarantined submission although validation failed (an administrator's decision; the caller audits + /// it). The validators' failed verdicts stay as they are; only the index step is completed. + /// + /// Null on success, otherwise why it was not released. + /// The gate is closed. + internal async Task ReleaseAsync(string submissionId, string? actor, CancellationToken cancellationToken) + { + #pragma warning disable CS8604 + var steps = await _context.PackageValidations + .IgnoreQueryFilters() + .Where(v => v.SubmissionId == submissionId) + .ToListAsync(cancellationToken); + #pragma warning restore CS8604 + + if (!await UseSubmissionRepositoryAsync(steps, submissionId, cancellationToken)) return "The submission's repository no longer exists."; + + var index = steps.SingleOrDefault(s => s.Type == PackageValidation.IndexType); + if (index == null) return "There is no such submission."; + if (index.State != PackageValidationState.Failed) return "Only a quarantined submission can be released."; + + using var package = new MemoryStream(); + try + { + using var staged = await _storage.GetAsync(ValidatingPackageSubmissionService.StagedPath(_repository.Current, submissionId), cancellationToken); + await staged.CopyToAsync(package, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogWarning(e, "The staged package of submission {SubmissionId} could not be read", submissionId); + return "The staged package is missing."; + } + + package.Position = 0; + var indexError = await IndexAsync(package, _options.Value.RepositorySigningServiceIndexUrl, cancellationToken); + if (indexError != null) return indexError; + + Complete(index, succeeded: true, $"Released by {actor ?? "an administrator"} although validation failed."); + + #pragma warning disable CS8604 + var version = NuGet.Versioning.NuGetVersion.Parse(index.PackageVersion); + #pragma warning restore CS8604 + var indexed = await _packages.FindOrNullAsync(index.PackageId, version, includeUnlisted: true, cancellationToken); + foreach (var step in steps) + { + step.PackageKey = indexed?.Key; + } + + await _context.SaveChangesAsync(cancellationToken); + await _storage.DeleteAsync(ValidatingPackageSubmissionService.StagedPath(_repository.Current, submissionId), cancellationToken); + + return null; + } + + /// Null on success, otherwise why indexing failed. + private async Task IndexAsync(Stream package, string? serviceIndexUrl, CancellationToken cancellationToken) + { + var toIndex = package; + try + { + if (_signer.IsConfigured) + { + // NuGet only accepts a repository signature that names an https source. + if (!Uri.TryCreate(serviceIndexUrl, UriKind.Absolute, out var url) || url.Scheme != Uri.UriSchemeHttps) + { + return "Repository signing needs Validation:RepositorySigningServiceIndexUrl to be an absolute https URL."; + } + + toIndex = await _signer.SignAsync(package, serviceIndexUrl, cancellationToken); + } + + toIndex.Position = 0; + var result = await _indexer.IndexAsync(toIndex, cancellationToken); + + return result == PackageIndexingResult.Success ? null : $"Indexing failed: {result}."; + } + catch (Exception e) when (!(e is OperationCanceledException) && !(e is MaintenanceException)) + { + // A closed maintenance gate is not the package's fault: let it reach the worker, which + // retries later, instead of quarantining the submission. + _logger.LogError(e, "Failed to index a validated package"); + return $"Indexing failed: {e.Message}"; + } + finally + { + if (!ReferenceEquals(toIndex, package)) + { + toIndex.Dispose(); + } + } + } + + private void Complete(PackageValidation step, bool succeeded, string? message) + { + step.State = succeeded ? PackageValidationState.Succeeded : PackageValidationState.Failed; + step.Message = message?.Length > AbstractContext.DefaultMaxStringLength + ? message.Substring(0, AbstractContext.DefaultMaxStringLength) + : message; + step.Completed = _time.UtcNow; + } +} \ No newline at end of file diff --git a/src/BaGet.Validation/Pipeline/PackageValidatorResult.cs b/src/BaGet.Validation/Pipeline/PackageValidatorResult.cs new file mode 100644 index 000000000..b2f74709c --- /dev/null +++ b/src/BaGet.Validation/Pipeline/PackageValidatorResult.cs @@ -0,0 +1,24 @@ +using System; + +namespace BaGet.Validation.Pipeline; + +public sealed class PackageValidatorResult +{ + public static readonly PackageValidatorResult Valid = new(true, null); + + private PackageValidatorResult(bool isValid, string? message) + { + IsValid = isValid; + Message = message; + } + + public bool IsValid { get; } + + /// + /// Why the package is invalid. Shown to the package's owners. + /// + public string? Message { get; } + + public static PackageValidatorResult Invalid(string message) => + new(false, message ?? throw new ArgumentNullException(nameof(message))); +} \ No newline at end of file diff --git a/src/BaGet.Validation/Queue/IValidationQueue.cs b/src/BaGet.Validation/Queue/IValidationQueue.cs new file mode 100644 index 000000000..c1a5c77dd --- /dev/null +++ b/src/BaGet.Validation/Queue/IValidationQueue.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Validation.Queue; + +/// +/// Hands submissions to the validation worker. The submissions themselves are in the +/// database, so a queue only has to say which to run next; the default one is in +/// memory, and on startup the worker re-queues whatever is still pending. +/// +public interface IValidationQueue +{ + ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken); + + IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken); +} diff --git a/src/BaGet.Validation/Queue/InMemoryValidationQueue.cs b/src/BaGet.Validation/Queue/InMemoryValidationQueue.cs new file mode 100644 index 000000000..9747c0eb4 --- /dev/null +++ b/src/BaGet.Validation/Queue/InMemoryValidationQueue.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace BaGet.Validation.Queue; + +public class InMemoryValidationQueue : IValidationQueue +{ + private readonly Channel _channel = Channel.CreateUnbounded( + new UnboundedChannelOptions { SingleReader = true }); + + public ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken) + => _channel.Writer.WriteAsync(submissionId, cancellationToken); + + public IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken) + => _channel.Reader.ReadAllAsync(cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Validation/Queue/ValidationWorker.cs b/src/BaGet.Validation/Queue/ValidationWorker.cs new file mode 100644 index 000000000..a457af4d8 --- /dev/null +++ b/src/BaGet.Validation/Queue/ValidationWorker.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using BaGet.Validation.Pipeline; + +namespace BaGet.Validation.Queue; + +/// +/// Runs queued submissions one at a time. On startup it re-queues every submission still +/// pending, so a restart delays validation but loses nothing. +/// +public class ValidationWorker : BackgroundService +{ + private readonly IServiceScopeFactory _scopes; + private readonly IValidationQueue _queue; + private readonly ILogger _logger; + private readonly IJobLease? _lease; + private readonly ClusterRuntime? _cluster; + + public ValidationWorker(IServiceScopeFactory scopes, IValidationQueue queue, ILogger logger, IJobLease? lease = null, ClusterRuntime? cluster = null) + { + _lease = lease; + _cluster = cluster; + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + // Yield so that host startup does not wait on the database. + await Task.Yield(); + + await RequeuePendingAsync(stoppingToken); + + // A node that died mid-validation leaves its submission pending with nobody to resume it until a restart; in a cluster the + // survivors offer every pending submission again now and then (a submission already done is skipped by the runner). + if (_cluster?.IsEnabled == true) _ = RequeueRegularlyAsync(stoppingToken); + + await foreach (var submissionId in _queue.DequeueAllAsync(stoppingToken)) + { + try + { + // Every node queues the pending submissions when it starts and the one that took a push queues it: only one node validates + // a submission at a time. A node that finds it taken skips it (the holder finishes it, or the periodic requeue offers it again). + await using var held = await _lease.AcquireAsync("validation:" + submissionId, stoppingToken); + if (held == null) continue; + + using var scope = _scopes.CreateScope(); + var runner = scope.ServiceProvider.GetRequiredService(); + + await runner.RunAsync(submissionId, stoppingToken); + _failures.TryRemove(submissionId, out _); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (MaintenanceException e) + { + // The database is read-only for now. The submission is still pending, so try it again + // once the gate may have reopened rather than leaving it until the next start. + _logger.LogWarning("Validation of submission {SubmissionId} postponed: {Reason}", submissionId, e.Reason); + await RetryLaterAsync(submissionId, stoppingToken); + } + catch (Exception e) + { + // Still pending: offered again after a growing delay, a bounded number of times; then it waits for the + // next start, or for an administrator to reject it. + var attempt = _failures.AddOrUpdate(submissionId, 1, (_, n) => n + 1); + if (attempt <= MaxFailureRetries) + { + var delay = TimeSpan.FromTicks(FailureRetryDelay.Ticks << (attempt - 1)); + _logger.LogError(e, "Validation of submission {SubmissionId} failed (attempt {Attempt}); retrying in {Delay}", submissionId, attempt, delay); + _ = RetryLaterAsync(submissionId, delay, stoppingToken); + } + else + { + _failures.TryRemove(submissionId, out _); + _logger.LogError(e, "Validation of submission {SubmissionId} failed {Attempts} times; it stays pending until the next start or an administrator rejects it", submissionId, attempt); + } + } + } + } + + /// How long a submission waits after a maintenance refusal before it is queued again. + internal static TimeSpan MaintenanceRetryDelay { get; set; } = TimeSpan.FromSeconds(30); + + /// The first delay before a failed submission is queued again; it doubles with each failure. + internal static TimeSpan FailureRetryDelay { get; set; } = TimeSpan.FromSeconds(30); + + /// How many times a failed submission is queued again before it is left pending. + internal const int MaxFailureRetries = 5; + + private readonly ConcurrentDictionary _failures = new(); + + private Task RetryLaterAsync(string submissionId, CancellationToken cancellationToken) + => RetryLaterAsync(submissionId, MaintenanceRetryDelay, cancellationToken); + + private async Task RetryLaterAsync(string submissionId, TimeSpan delay, CancellationToken cancellationToken) + { + try + { + await Task.Delay(delay, cancellationToken); + await _queue.EnqueueAsync(submissionId, cancellationToken); + } + catch (OperationCanceledException) + { + // Shutting down: the submission stays pending and is re-queued at the next start. + } + } + + /// How often a cluster node offers the pending submissions again. + internal static TimeSpan ClusterRequeueInterval { get; set; } = TimeSpan.FromMinutes(1); + + private async Task RequeueRegularlyAsync(CancellationToken cancellationToken) + { + try + { + while (!cancellationToken.IsCancellationRequested) + { + await Task.Delay(ClusterRequeueInterval, cancellationToken); + await RequeuePendingAsync(cancellationToken); + } + } + catch (OperationCanceledException) + { + } + } + + private async Task RequeuePendingAsync(CancellationToken cancellationToken) + { + try + { + using var scope = _scopes.CreateScope(); + if (!scope.ServiceProvider.GetRequiredService>().Value.Enabled) return; + if (scope.ServiceProvider.GetRequiredService() is NullContext) return; + + var runner = scope.ServiceProvider.GetRequiredService(); + #pragma warning disable CS8602 + foreach (var submissionId in await runner.GetPendingSubmissionIdsAsync(cancellationToken)) + #pragma warning restore CS8602 + { + await _queue.EnqueueAsync(submissionId, cancellationToken); + } + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // The database may not be migrated yet on a first start. + _logger.LogWarning(e, "Could not re-queue pending validations"); + } + } +} \ No newline at end of file diff --git a/src/BaGet.Validation/README.md b/src/BaGet.Validation/README.md new file mode 100644 index 000000000..e77f5a28e --- /dev/null +++ b/src/BaGet.Validation/README.md @@ -0,0 +1,37 @@ +# Extension.BaGet.Validation + +The validation pipeline of [BaGet Extension](https://pieroviano.github.io/BaGet/): pushed packages are validated, +and optionally repository signed, before they are served. + +```powershell +dotnet add package Extension.BaGet.Validation +``` + +## Usage + +`AddBaGetWebApplication` (`Extension.BaGet.Web`) registers it; standalone: `services.AddBaGetValidation()`. +It is always registered; `Validation:Enabled` is read on every push. + +Administrators retry, release (index anyway, audited) or reject quarantined submissions of any repository at `/admin/validation` (`ValidationAdministration`). + +| Setting | Value | +|---|---| +| `Validation:Enabled` | Off by default. On: a push answers `202 Accepted`, the package appears once every validator passes; a failing package is quarantined | +| `Validation:RequireSignedPackages` | Reject packages without a valid author or repository signature | +| `Validation:RepositorySigningCertificatePath`, `…Password` | PFX that repository-signs every validated package | +| `Validation:RepositorySigningServiceIndexUrl` | This server's public `https` service index URL, recorded in each signature; required for signing | + +| Item | Role | +|---|---| +| `IPackageValidator` | Validation step; built-in `PackageEntriesValidator`, `PackageSignatureValidator`. Register more with `TryAddEnumerable` | +| `IValidationQueue` | Push queue; default `InMemoryValidationQueue` | +| `ValidationWorker` | Hosted service that runs the validators | +| Routes | `v3/package/{id}/{version}/validation` (status), `v3/repository-signatures/index.json` | + +## Layout + +One type per file, namespace = `BaGet.Validation` + folder (`CodeLayoutTests`): `Pipeline` (validators, runner), `Queue`, `Signing`, `Services`, `Models`, `Controllers/Protocols`, `Extensions`. + +## Links + +[Configuration](https://pieroviano.github.io/BaGet/configuration/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Validation/Services/ValidatingPackageSubmissionService.cs b/src/BaGet.Validation/Services/ValidatingPackageSubmissionService.cs new file mode 100644 index 000000000..8667dad97 --- /dev/null +++ b/src/BaGet.Validation/Services/ValidatingPackageSubmissionService.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Packaging; +using BaGet.Validation.Pipeline; +using BaGet.Validation.Queue; + +namespace BaGet.Validation.Services; + +/// +/// With validation on, stages a pushed package and queues it; otherwise indexes it at +/// once, exactly as before. With the closed, a staged push is refused with +/// before anything reaches storage. +/// +public class ValidatingPackageSubmissionService : IPackageSubmissionService +{ + private readonly IPackageIndexingService _indexer; + private readonly IPackageDatabase _packages; + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IValidationQueue _queue; + private readonly IEnumerable _validators; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly IOptionsSnapshot _validation; + private readonly ILogger _logger; + private readonly MaintenanceGate? _gate; + private readonly IRepositoryContext? _repository; + + public ValidatingPackageSubmissionService( + IPackageIndexingService indexer, + IPackageDatabase packages, + IContext context, + IStorageService storage, + IValidationQueue queue, + IEnumerable validators, + SystemTime time, + IOptionsSnapshot options, + IOptionsSnapshot validation, + ILogger logger, + MaintenanceGate? gate = null, + IRepositoryContext? repository = null) + { + _gate = gate; + _repository = repository; + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _validators = validators ?? throw new ArgumentNullException(nameof(validators)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _validation = validation ?? throw new ArgumentNullException(nameof(validation)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// Where a submission is staged: validation/{id}.nupkg for the default repository, + /// repos/{name}/validation/{id}.nupkg for any other (see ). + /// + internal static string StagedPath(RepositoryInfo repository, string submissionId) + => RepositoryStorage.Scope(repository, $"validation/{submissionId}.nupkg"); + + public async Task SubmitAsync(Stream package, CancellationToken cancellationToken) + { + if (!_validation.Value.Enabled) + { + return await _indexer.IndexAsync(package, cancellationToken); + } + + // Refused up front, before the package reaches storage: staging it and then failing to record it in the + // database (which is closed) would leave an orphan file behind. + _gate?.ThrowIfClosed(); + + string id; + string version; + try + { + using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) + { + var identity = reader.GetIdentity(); + id = identity.Id; + version = identity.Version.ToNormalizedString(); + } + } + catch (Exception e) + { + _logger.LogError(e, "Uploaded package is invalid"); + return PackageIndexingResult.InvalidPackage; + } + + if (!_options.Value.AllowPackageOverwrites + && await _packages.ExistsAsync(id, NuGet.Versioning.NuGetVersion.Parse(version), cancellationToken)) + { + return PackageIndexingResult.PackageAlreadyExists; + } + + // The same version cannot be validated twice at once. + var lowerId = id.ToLowerInvariant(); + #pragma warning disable CS8602, CS8604 + if (await _context.PackageValidations.AnyAsync( + #pragma warning restore CS8604 + v => v.PackageId.ToLower() == lowerId + #pragma warning restore CS8602 + && v.PackageVersion == version + && v.State == PackageValidationState.Pending, + cancellationToken)) + { + return PackageIndexingResult.PackageAlreadyExists; + } + + var submissionId = Guid.NewGuid().ToString("D"); + + package.Position = 0; + await _storage.PutAsync(StagedPath(_repository?.Current ?? RepositoryInfo.Default, submissionId), package, "application/octet-stream", cancellationToken); + + var now = _time.UtcNow; + var steps = _validators.Select(v => v.Name).Append(PackageValidation.IndexType); + foreach (var step in steps) + { + _context.PackageValidations.Add(new PackageValidation + { + SubmissionId = submissionId, + PackageId = id, + PackageVersion = version, + Type = step, + State = PackageValidationState.Pending, + Created = now, + }); + } + + await _context.SaveChangesAsync(cancellationToken); + await _queue.EnqueueAsync(submissionId, cancellationToken); + + _logger.LogInformation( + "Queued package {PackageId} {PackageVersion} for validation as {SubmissionId}", + id, + version, + submissionId); + + return PackageIndexingResult.Accepted; + } +} \ No newline at end of file diff --git a/src/BaGet.Validation/Services/ValidationAdministration.cs b/src/BaGet.Validation/Services/ValidationAdministration.cs new file mode 100644 index 000000000..605a7d854 --- /dev/null +++ b/src/BaGet.Validation/Services/ValidationAdministration.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using BaGet.Validation.Pipeline; +using BaGet.Validation.Queue; + +namespace BaGet.Validation.Services; + +/// +/// Lists the pending and quarantined submissions of every repository, and retries, releases or rejects one. +/// Releasing indexes a package that failed validation, so it is logged as a warning and recorded with +/// (the seam for the access-audit table). +/// +public sealed class ValidationAdministration : IValidationAdministration +{ + private readonly IContext _context; + private readonly IRepositoryService _repositories; + private readonly IRepositoryContext _repository; + private readonly IStorageService _storage; + private readonly IValidationQueue _queue; + private readonly PackageValidationRunner _runner; + private readonly IAdminAudit _audit; + private readonly ILogger _logger; + private readonly MaintenanceGate? _gate; + + public ValidationAdministration( + IContext context, + IRepositoryService repositories, + IRepositoryContext repository, + IStorageService storage, + IValidationQueue queue, + PackageValidationRunner runner, + IAdminAudit audit, + ILogger logger, + MaintenanceGate? gate = null) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _repositories = repositories ?? throw new ArgumentNullException(nameof(repositories)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _runner = runner ?? throw new ArgumentNullException(nameof(runner)); + _audit = audit ?? throw new ArgumentNullException(nameof(audit)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _gate = gate; + } + + /// + public bool IsSupported => _context is not NullContext && _context.PackageValidations != null; + + /// + public async Task> ListAsync(CancellationToken cancellationToken) + { + if (!IsSupported) return Array.Empty(); + + #pragma warning disable CS8604, CS8619 + var open = await _context.PackageValidations! + .IgnoreQueryFilters() + .AsNoTracking() + .Where(v => v.Type == PackageValidation.IndexType && v.State != PackageValidationState.Succeeded) + .OrderBy(v => v.Created).ThenBy(v => v.Key) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + if (open.Count == 0) return Array.Empty(); + + var ids = open.Select(v => v.SubmissionId).ToList(); + var failed = (await _context.PackageValidations! + .IgnoreQueryFilters() + .AsNoTracking() + .Where(v => ids.Contains(v.SubmissionId) && v.State == PackageValidationState.Failed) + .OrderBy(v => v.Key) + .ToListAsync(cancellationToken) + .ConfigureAwait(false)) + .ToLookup(v => v.SubmissionId); + #pragma warning restore CS8604, CS8619 + + var names = (await _repositories.ListAsync(cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, r => r.Name); + + return open + .Select(index => new ValidationSubmissionSummary( + index.SubmissionId!, + names.TryGetValue(index.RepositoryKey, out var name) ? name : Repository.DefaultName, + index.PackageId, + index.PackageVersion, + index.State == PackageValidationState.Pending ? ValidationSubmissionState.Pending : ValidationSubmissionState.Quarantined, + index.Created, + failed[index.SubmissionId] + .Where(v => !string.IsNullOrEmpty(v.Message)) + .Select(v => v.Type == PackageValidation.IndexType ? v.Message! : $"{v.Type}: {v.Message}") + .ToList())) + .ToList(); + } + + /// + public async Task RetryAsync(string submissionId, string? actor, CancellationToken cancellationToken) + { + _gate?.ThrowIfClosed(); + + var (steps, error) = await LoadAsync(submissionId, cancellationToken); + if (error != null) return error; + + var index = steps.Single(s => s.Type == PackageValidation.IndexType); + if (!await StagedExistsAsync(submissionId, cancellationToken)) return "The staged package is missing, so it cannot be validated again."; + + foreach (var step in steps) + { + step.State = PackageValidationState.Pending; + step.Message = null; + step.Completed = null; + } + + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await _queue.EnqueueAsync(submissionId, cancellationToken).ConfigureAwait(false); + + _audit.Record(actor, "validation.retry", Describe(index)); + + return null; + } + + /// + public async Task ReleaseAsync(string submissionId, string? actor, CancellationToken cancellationToken) + { + _gate?.ThrowIfClosed(); + + var (steps, error) = await LoadAsync(submissionId, cancellationToken); + if (error != null) return error; + + var index = steps.Single(s => s.Type == PackageValidation.IndexType); + if (index.State != PackageValidationState.Failed) return "Only a quarantined submission can be released; a pending one is still being validated."; + + var failedSteps = string.Join("; ", steps.Where(s => s.State == PackageValidationState.Failed && s != index).Select(s => $"{s.Type}: {s.Message}")); + var releaseError = await _runner.ReleaseAsync(submissionId, actor, cancellationToken).ConfigureAwait(false); + if (releaseError != null) return releaseError; + + _logger.LogWarning( + "{Actor} released quarantined package {Package} from submission {SubmissionId}; validation had failed: {Failures}", + actor, Describe(index), submissionId, failedSteps); + _audit.Record(actor, "validation.release", Describe(index), failedSteps.Length == 0 ? "indexing had failed" : failedSteps); + + return null; + } + + /// + public async Task RejectAsync(string submissionId, string? actor, CancellationToken cancellationToken) + { + _gate?.ThrowIfClosed(); + + // A validator may be running on it: stop that first, or it would publish what is being rejected. + if (!await PackageValidationRunner.StopRunAsync(submissionId, cancellationToken).ConfigureAwait(false)) + { + return "That submission is being validated and did not stop in time; try again."; + } + + var (steps, error) = await LoadAsync(submissionId, cancellationToken); + if (error != null) return error; + + var index = steps.Single(s => s.Type == PackageValidation.IndexType); + // A pending submission can be rejected too: one whose validation keeps failing would otherwise stay pending for + // good (pushing the version again answers 409, the repository cannot be deleted). The runner skips a submission + // whose rows are gone. + if (index.State != PackageValidationState.Failed && index.State != PackageValidationState.Pending) return "Only a pending or quarantined submission can be rejected."; + + // File first: if the rows could not be removed the submission stays listed and can be rejected again. + await _storage.DeleteAsync(ValidatingPackageSubmissionService.StagedPath(_repository.Current, submissionId), cancellationToken).ConfigureAwait(false); + _context.PackageValidations!.RemoveRange(steps); + await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + _audit.Record(actor, "validation.reject", Describe(index)); + + return null; + } + + private string Describe(PackageValidation index) + => $"repository {_repository.Current.Name}, {index.PackageId} {index.PackageVersion} (submission {index.SubmissionId})"; + + /// Loads the submission's steps and switches to its repository. + private async Task<(List Steps, string? Error)> LoadAsync(string submissionId, CancellationToken cancellationToken) + { + if (!IsSupported) return (new List(), "Validation is not available with this database."); + + #pragma warning disable CS8604 + var steps = await _context.PackageValidations! + .IgnoreQueryFilters() + .Where(v => v.SubmissionId == submissionId) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + #pragma warning restore CS8604 + + var index = steps.SingleOrDefault(s => s.Type == PackageValidation.IndexType); + if (index == null) return (steps, "There is no such submission."); + if (index.State == PackageValidationState.Succeeded) return (steps, "That package was already indexed."); + + if (!await _runner.UseSubmissionRepositoryAsync(steps, submissionId, cancellationToken).ConfigureAwait(false)) + { + return (steps, "The submission's repository no longer exists."); + } + + return (steps, null); + } + + private async Task StagedExistsAsync(string submissionId, CancellationToken cancellationToken) + { + try + { + using var staged = await _storage.GetAsync(ValidatingPackageSubmissionService.StagedPath(_repository.Current, submissionId), cancellationToken).ConfigureAwait(false); + + return true; + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + return false; + } + } +} diff --git a/src/BaGet.Validation/Signing/RepositorySignaturesServiceIndexProvider.cs b/src/BaGet.Validation/Signing/RepositorySignaturesServiceIndexProvider.cs new file mode 100644 index 000000000..01ce6726c --- /dev/null +++ b/src/BaGet.Validation/Signing/RepositorySignaturesServiceIndexProvider.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Protocol.Models; + +namespace BaGet.Validation.Signing; + +/// +/// Advertises RepositorySignatures/5.0.0 while a signing certificate is configured. +/// +public class RepositorySignaturesServiceIndexProvider : IServiceIndexResourceProvider +{ + private readonly RepositorySigner _signer; + private readonly IUrlGenerator _url; + + public RepositorySignaturesServiceIndexProvider(RepositorySigner signer, IUrlGenerator url) + { + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } + + public IEnumerable GetResources() + { + if (!_signer.IsConfigured) yield break; + + yield return new ServiceIndexItem + { + ResourceUrl = _url.GetRepositorySignaturesUrl(), + Type = "RepositorySignatures/5.0.0", + }; + } +} \ No newline at end of file diff --git a/src/BaGet.Validation/Signing/RepositorySigner.cs b/src/BaGet.Validation/Signing/RepositorySigner.cs new file mode 100644 index 000000000..f304e6873 --- /dev/null +++ b/src/BaGet.Validation/Signing/RepositorySigner.cs @@ -0,0 +1,114 @@ +using System; +using System.IO; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.Options; +using NuGet.Common; +using NuGet.Packaging.Signing; + +namespace BaGet.Validation.Signing; + +/// +/// Repository-signs validated packages with the configured certificate, so a client can +/// tell a package came through this server. See: +/// https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource +/// +public class RepositorySigner +{ + private readonly IOptionsSnapshot _options; + + public RepositorySigner(IOptionsSnapshot options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public bool IsConfigured => !string.IsNullOrEmpty(_options.Value.RepositorySigningCertificatePath); + + /// + /// The configured certificate, without its private key, or null if none is. + /// + public X509Certificate2? GetPublicCertificateOrNull() + { + if (!IsConfigured) return null; + + using var certificate = LoadCertificate(); + + return X509CertificateLoader.LoadCertificate(certificate.RawData); + } + + /// + /// Sign a package, returning the signed copy. A package that already has a + /// repository signature is returned as it is. + /// + /// The package to sign. It is read, not modified. + /// + /// This server's service index. The signature records it, and a client checks that + /// it matches the source the package came from. + /// + /// Cancels signing. + public async Task SignAsync(Stream package, string serviceIndexUrl, CancellationToken cancellationToken) + { + var directory = Path.Combine(Path.GetTempPath(), "BaGetSigning", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + + var input = Path.Combine(directory, "input.nupkg"); + var output = Path.Combine(directory, "output.nupkg"); + + try + { + using (var file = File.Create(input)) + { + package.Position = 0; + await package.CopyToAsync(file, cancellationToken); + } + + using (var certificate = LoadCertificate()) + using (var request = new RepositorySignPackageRequest( + certificate, + NuGet.Common.HashAlgorithmName.SHA256, + NuGet.Common.HashAlgorithmName.SHA256, + new Uri(serviceIndexUrl), + packageOwners: null)) + using (var options = SigningOptions.CreateFromFilePaths( + input, + output, + overwrite: true, + signatureProvider: new X509SignatureProvider(timestampProvider: null), + logger: NullLogger.Instance)) + { + await SigningUtility.SignAsync(options, request, cancellationToken); + } + + var signed = new MemoryStream(); + using (var file = File.OpenRead(output)) + { + await file.CopyToAsync(signed, cancellationToken); + } + + signed.Position = 0; + + return signed; + } + finally + { + try + { + Directory.Delete(directory, recursive: true); + } + catch (IOException) + { + // A temporary file left behind is not worth failing the push for. + } + } + } + + #pragma warning disable CS8604 + private X509Certificate2 LoadCertificate() + => X509CertificateLoader.LoadPkcs12FromFile( + _options.Value.RepositorySigningCertificatePath, + _options.Value.RepositorySigningCertificatePassword, + X509KeyStorageFlags.EphemeralKeySet); + #pragma warning restore CS8604 +} \ No newline at end of file diff --git a/src/BaGet.Validation/Signing/RepositorySigningCertificate.cs b/src/BaGet.Validation/Signing/RepositorySigningCertificate.cs new file mode 100644 index 000000000..d8c5e75f4 --- /dev/null +++ b/src/BaGet.Validation/Signing/RepositorySigningCertificate.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace BaGet.Validation.Signing; + +public class RepositorySigningCertificate +{ + [JsonPropertyName("fingerprints")] + public IReadOnlyDictionary? Fingerprints { get; set; } + + [JsonPropertyName("subject")] + public string? Subject { get; set; } + + [JsonPropertyName("issuer")] + public string? Issuer { get; set; } + + [JsonPropertyName("notBefore")] + public DateTime NotBefore { get; set; } + + [JsonPropertyName("notAfter")] + public DateTime NotAfter { get; set; } + + [JsonPropertyName("contentUrl")] + public string? ContentUrl { get; set; } +} diff --git a/src/BaGet.Web.Application/BaGet.Web.Application.csproj b/src/BaGet.Web.Application/BaGet.Web.Application.csproj new file mode 100644 index 000000000..f3fb54a6f --- /dev/null +++ b/src/BaGet.Web.Application/BaGet.Web.Application.csproj @@ -0,0 +1,37 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's web use cases: the data of the browse, upload and legal screens as plain DTOs, with no MVC or Razor dependency. + BaGet.Web.Application + enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Web.Application/Extensions/WebApplicationServiceCollectionExtensions.cs b/src/BaGet.Web.Application/Extensions/WebApplicationServiceCollectionExtensions.cs new file mode 100644 index 000000000..cf2d7152e --- /dev/null +++ b/src/BaGet.Web.Application/Extensions/WebApplicationServiceCollectionExtensions.cs @@ -0,0 +1,37 @@ +using BaGet.Identity.Application.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Services; +using BaGet.Web.Application.UseCases; + +namespace BaGet.Web.Application.Extensions; + +/// Registration of the use cases of the web screens. +public static class WebApplicationServiceCollectionExtensions +{ + /// + /// Registers the use cases (one scoped class per area of screens) and the account project's screen gate. Called by + /// AddBaGetWebApplication; a track that moves a screen's logic here adds its use case below. + /// + public static IServiceCollection AddBaGetWebUseCases(this IServiceCollection services) + { + services.AddBaGetIdentityApplication(); + + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + // The format screens and the browser uploads. + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + return services; + } +} diff --git a/src/BaGet.Web.Application/Models/Browse/IndexQuery.cs b/src/BaGet.Web.Application/Models/Browse/IndexQuery.cs new file mode 100644 index 000000000..677d455c4 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Browse/IndexQuery.cs @@ -0,0 +1,18 @@ +using BaGet.Core; + +namespace BaGet.Web.Application.Models.Browse; + +/// What the visitor asked the front page or the package list for (the query string of /, /packages). +/// The search text (q). +/// The 1-based page of results (p). +/// The package type filter, any for none. +/// The target framework filter, any for none. +/// Whether prerelease versions are included. +/// The requested order. +public sealed record IndexQuery( + string? Query = null, + int PageIndex = 1, + string PackageType = "any", + string Framework = "any", + bool Prerelease = true, + SearchSort SortBy = SearchSort.Relevance); diff --git a/src/BaGet.Web.Application/Models/Browse/ReportAbuseForm.cs b/src/BaGet.Web.Application/Models/Browse/ReportAbuseForm.cs new file mode 100644 index 000000000..44f5288d3 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Browse/ReportAbuseForm.cs @@ -0,0 +1,24 @@ +using System.ComponentModel.DataAnnotations; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Web.Application.Models.Browse; + +/// What the reporter fills in. The field names (Reason, Details, ReporterEmail) are the contract of the form and of the JSON body. +public sealed class ReportAbuseForm +{ + /// One of . + [Required] + public string? Reason { get; set; } + + /// What the reporter saw. + [Required] + [StringLength(AbstractContext.DefaultMaxStringLength)] + public string? Details { get; set; } + + /// The address of the reporter, optional. + [EmailAddress] + [StringLength(AbstractContext.MaxEmailLength)] + [Display(Name = "Your email (optional)")] + public string? ReporterEmail { get; set; } +} diff --git a/src/BaGet.Web.Application/Models/Browse/StatisticsViewModel.cs b/src/BaGet.Web.Application/Models/Browse/StatisticsViewModel.cs new file mode 100644 index 000000000..7095c93c7 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Browse/StatisticsViewModel.cs @@ -0,0 +1,7 @@ +using BaGet.Core; + +namespace BaGet.Web.Application.Models.Browse; + +/// What the statistics page shows. +/// The feed's totals and lists; null when the database cannot report them. +public sealed record StatisticsViewModel(FeedStatistics? Statistics); diff --git a/src/BaGet.Web.Application/Models/Docker/DockerImageViewModel.cs b/src/BaGet.Web.Application/Models/Docker/DockerImageViewModel.cs new file mode 100644 index 000000000..39ed4c1b6 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Docker/DockerImageViewModel.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.Models.Docker; + +/// What the page of one Docker image (/docker-images/{image}, ?digest= for a manifest) shows. +public sealed class DockerImageViewModel +{ + /// The image name from the address (it may contain slashes). + public string? Image { get; init; } + + /// The manifest to show in full (?digest=), or null for the overview. + public string? Digest { get; init; } + + /// Narrows the referrers to one artifact type (?artifactType=); empty keeps them all. + public string? ArtifactType { get; init; } + + /// The HTTP status the page is answered with: 200, or 404 when the image or manifest does not exist (the page then explains). + public int StatusCode { get; init; } = 200; + + /// The image, or null when there is none of that name. + public OciImageInfo? Info { get; init; } + + /// The chosen manifest, or null. + public OciManifestDetail? Selected { get; init; } + + /// The manifests whose subject is the chosen manifest (signatures, SBOMs). Empty without a selection. + public IReadOnlyList Referrers { get; init; } = Array.Empty(); + + /// The registry host as a Docker client writes it. + public string Host { get; init; } = string.Empty; + + /// The repository's name. + public string RepositoryName { get; init; } = string.Empty; + + /// Whether the repository caches an upstream registry (it takes no pushes). + public bool IsRemote { get; init; } + + /// Whether the signed-in user holds Delete on the image, so the manage page is offered. + public bool CanManage { get; init; } + + public IReadOnlyList PullTabs { get; init; } = Array.Empty(); + + /// The address of the registry API for the image (what a script calls). + public string RegistryUrl { get; init; } = string.Empty; +} diff --git a/src/BaGet.Web.Application/Models/Docker/DockerImagesViewModel.cs b/src/BaGet.Web.Application/Models/Docker/DockerImagesViewModel.cs new file mode 100644 index 000000000..531b152cf --- /dev/null +++ b/src/BaGet.Web.Application/Models/Docker/DockerImagesViewModel.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Web.Application.Snippets; +using BaGet.Web.Application.UseCases; + +namespace BaGet.Web.Application.Models.Docker; + +/// What the Docker front page (/docker-images) shows: this page of images and the commands for the client. +public sealed class DockerImagesViewModel +{ + /// The search text. + public string? Query { get; init; } + + /// The page, from 1. + public int PageIndex { get; init; } = 1; + + /// This page of results. + public OciImagePage Result { get; init; } = new(0, Array.Empty()); + + /// The registry host as a Docker client writes it (host:port). + public string Host { get; init; } = string.Empty; + + /// Whether the registry is reached over plain http (the Docker daemon then needs it as an insecure registry). + public bool IsHttp { get; init; } + + /// The repository's name, the first path segment of every image reference. + public string RepositoryName { get; init; } = string.Empty; + + /// Whether the repository caches an upstream registry (it takes no pushes). + public bool IsRemote { get; init; } + + /// Whether the repository merges other repositories (a push goes to its deploy repository). + public bool IsVirtual { get; init; } + + /// Whether another page follows. + public bool HasNext => PageIndex * DockerBrowseUseCase.ResultsPerPage < Result.Total; + + public IReadOnlyList CommandTabs { get; init; } = Array.Empty(); +} diff --git a/src/BaGet.Web.Application/Models/Maven/MavenArtifactViewModel.cs b/src/BaGet.Web.Application/Models/Maven/MavenArtifactViewModel.cs new file mode 100644 index 000000000..cf700b274 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Maven/MavenArtifactViewModel.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.Models.Maven; + +/// What the page of one Maven artifact (/maven-artifacts/{group}/{artifact}/{version?}) shows. +public sealed class MavenArtifactViewModel +{ + /// The group id from the address. + public string? Group { get; init; } + + /// The artifact id from the address. + public string? Artifact { get; init; } + + /// The version from the address; the latest when absent. + public string? Version { get; init; } + + /// The HTTP status the page is answered with: 200, or 404 when the artifact or version does not exist (the page then explains). + public int StatusCode { get; init; } = 200; + + /// The artifact, or null when there is none of those coordinates. + public MavenArtifactInfo? Info { get; init; } + + /// The version the page shows, with its files and POM. + public MavenVersionDetail? Selected { get; init; } + + /// The address Maven is configured with for this repository. + public string RepositoryUrl { get; init; } = string.Empty; + + /// The repository's name (the id in settings.xml). + public string RepositoryName { get; init; } = string.Empty; + + public IReadOnlyList InstallTabs { get; init; } = Array.Empty(); + + /// The owners, when accounts are on; empty otherwise. + public IReadOnlyList Owners { get; init; } = Array.Empty(); + + /// Whether the signed-in user can open the manage page (an owner or an administrator). + public bool CanManage { get; init; } + + /// The address of a file of the selected version. + public string FileUrl(string fileName) + => RepositoryUrl + MavenNames.ClientPath(Info!.GroupId, Info.ArtifactId, Selected!.Summary.Version, fileName); +} diff --git a/src/BaGet.Web.Application/Models/Maven/MavenArtifactsViewModel.cs b/src/BaGet.Web.Application/Models/Maven/MavenArtifactsViewModel.cs new file mode 100644 index 000000000..551e22b72 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Maven/MavenArtifactsViewModel.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Web.Application.Snippets; +using BaGet.Web.Application.UseCases; + +namespace BaGet.Web.Application.Models.Maven; + +/// What the Maven front page (/maven-artifacts) shows: this page of search results and the client configuration. +public sealed class MavenArtifactsViewModel +{ + /// The search text. + public string? Query { get; init; } + + /// The page, from 1. + public int PageIndex { get; init; } = 1; + + /// This page of results. + public MavenSearchPage Result { get; init; } = new(0, Array.Empty()); + + /// The repository's policy, redeploy and snapshot retention. + public MavenRepositorySettings Settings { get; init; } = new(); + + /// The address Maven is configured with for this repository. + public string RepositoryUrl { get; init; } = string.Empty; + + /// The kind of the repository: a remote one lists what it cached, a virtual one what its members hold. + public RepositoryKind Kind { get; init; } + + /// The repository's name, which is the id in settings.xml and the POM. + public string RepositoryName { get; init; } = string.Empty; + + /// Whether another page follows. + public bool HasNext => PageIndex * MavenBrowseUseCase.ResultsPerPage < Result.Total; + + public IReadOnlyList ConfigurationTabs { get; init; } = Array.Empty(); +} diff --git a/src/BaGet.Web.Application/Models/Maven/MavenUploadViewModel.cs b/src/BaGet.Web.Application/Models/Maven/MavenUploadViewModel.cs new file mode 100644 index 000000000..80161be72 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Maven/MavenUploadViewModel.cs @@ -0,0 +1,52 @@ +using BaGet.Core; + +namespace BaGet.Web.Application.Models.Maven; + +/// What the Maven upload page (/maven-upload) shows, before and after a deployment. +public sealed class MavenUploadViewModel +{ + /// Whether accounts are on (the uploader then signs in). + public bool AccountsEnabled { get; init; } + + /// Whether the server is read-only. + public bool IsReadOnlyMode { get; init; } + + /// Whether the visitor is signed in. + public bool SignedIn { get; init; } + + /// Without accounts there is no user to own an upload, so the uploader proves itself with the API key. + public bool NeedsApiKey => !AccountsEnabled; + + /// Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed. + public bool NothingCanAuthenticate { get; init; } + + /// Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in. + public bool CanUpload => !IsReadOnlyMode && !NothingCanAuthenticate && (!AccountsEnabled || SignedIn); + + /// The address Maven is configured with for this repository. + public string RepositoryUrl { get; init; } = string.Empty; + + /// The repository's name (the id in settings.xml). + public string RepositoryName { get; init; } = string.Empty; + + /// The repository's policy, shown beside the form. + public MavenRepositorySettings Settings { get; init; } = new(); + + /// What happened, for the page to show. + public string? Message { get; init; } + + /// Whether reports a failure. + public bool Failed { get; init; } + + /// The artifact just deployed (group:artifact), so the page can link to it. + public string? DeployedName { get; init; } + + /// The version just deployed. + public string? DeployedVersion { get; init; } + + /// The coordinates just posted, so a refused form keeps them. + public MavenDeployment? Posted { get; init; } + + /// The HTTP status the page is answered with (200, or the refusal's). + public int StatusCode { get; init; } = 200; +} diff --git a/src/BaGet.Web.Application/Models/Npm/NpmPackageViewModel.cs b/src/BaGet.Web.Application/Models/Npm/NpmPackageViewModel.cs new file mode 100644 index 000000000..21e9848ec --- /dev/null +++ b/src/BaGet.Web.Application/Models/Npm/NpmPackageViewModel.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using Microsoft.AspNetCore.Html; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.Models.Npm; + +/// What the page of one npm package (/npm-packages/{name}) shows. +public sealed class NpmPackageViewModel +{ + /// The package name from the address. + public string? Id { get; init; } + + /// The version asked for with ?version=; the latest when absent or unknown. + public string? RequestedVersion { get; init; } + + /// The HTTP status the page is answered with: 200, or 404 when the package does not exist (the page then explains). + public int StatusCode { get; init; } = 200; + + /// The package, or null when there is none of that name. + public NpmPackageInfo? Package { get; init; } + + /// The version the page shows. + public NpmVersionInfo? Selected { get; init; } + + /// The selected version's readme as safe HTML, or null. + public HtmlString? Readme { get; init; } + + /// The dist-tags that point at the selected version. + public IReadOnlyList SelectedTags { get; init; } = Array.Empty(); + + /// The address npm is configured with for this repository. + public string RegistryUrl { get; init; } = string.Empty; + + /// Where the selected version's tarball is. + public string? TarballUrl => Selected == null || Package == null + ? null + : RegistryUrl + Package.Name + "/-/" + NpmNames.TarballFileName(Package.Name, Selected.Version); + + public IReadOnlyList InstallTabs { get; init; } = Array.Empty(); + + /// The owners, when accounts are on; empty otherwise. + public IReadOnlyList Owners { get; init; } = Array.Empty(); + + /// Whether the signed-in user can open the manage page (an owner or an administrator). + public bool CanManage { get; init; } +} diff --git a/src/BaGet.Web.Application/Models/Npm/NpmPackagesViewModel.cs b/src/BaGet.Web.Application/Models/Npm/NpmPackagesViewModel.cs new file mode 100644 index 000000000..52f9217e8 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Npm/NpmPackagesViewModel.cs @@ -0,0 +1,24 @@ +using System; +using BaGet.Core; +using BaGet.Web.Application.UseCases; + +namespace BaGet.Web.Application.Models.Npm; + +/// What the npm front page (/npm-packages) shows: this page of search results and the registry address. +public sealed class NpmPackagesViewModel +{ + /// The search text. + public string? Query { get; init; } + + /// The page, from 1. + public int PageIndex { get; init; } = 1; + + /// This page of results. + public NpmSearchPage Result { get; init; } = new(0, Array.Empty()); + + /// The address npm is configured with for this repository. + public string RegistryUrl { get; init; } = string.Empty; + + /// Whether another page follows. + public bool HasNext => PageIndex * NpmBrowseUseCase.ResultsPerPage < Result.Total; +} diff --git a/src/BaGet.Web.Application/Models/Npm/NpmUploadViewModel.cs b/src/BaGet.Web.Application/Models/Npm/NpmUploadViewModel.cs new file mode 100644 index 000000000..d8ea01e9d --- /dev/null +++ b/src/BaGet.Web.Application/Models/Npm/NpmUploadViewModel.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Web.Application.Models.Npm; + +/// What the npm upload page (/npm-upload) shows, before and after a publish. +public sealed class NpmUploadViewModel +{ + /// Whether accounts are on (the uploader then signs in). + public bool AccountsEnabled { get; init; } + + /// Whether the server is read-only. + public bool IsReadOnlyMode { get; init; } + + /// Whether the visitor is signed in. + public bool SignedIn { get; init; } + + /// Without accounts there is no user to own an upload, so the uploader proves itself with the API key. + public bool NeedsApiKey => !AccountsEnabled; + + /// Accounts are off and no API key is set: nothing tells one visitor from another, so the page is closed. + public bool NothingCanAuthenticate { get; init; } + + /// Whether to render the form: not read-only, someone could be authenticated, and (with accounts) signed in. + public bool CanUpload => !IsReadOnlyMode && !NothingCanAuthenticate && (!AccountsEnabled || SignedIn); + + /// The address npm is configured with for this repository. + public string RegistryUrl { get; init; } = string.Empty; + + public IReadOnlyList PublishLines { get; init; } = Array.Empty(); + + /// What happened, for the page to show. + public string? Message { get; init; } + + /// Whether reports a failure. + public bool Failed { get; init; } + + /// The package just published, so the page can link to it. + public string? PublishedName { get; init; } + + /// The HTTP status the page is answered with (200, or the refusal's). + public int StatusCode { get; init; } = 200; +} diff --git a/src/BaGet.Web.Application/Models/Packages/DependencyGroupModel.cs b/src/BaGet.Web.Application/Models/Packages/DependencyGroupModel.cs new file mode 100644 index 000000000..14bf74a56 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/DependencyGroupModel.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace BaGet.Web.Application.Models.Packages; + +public class DependencyGroupModel +{ + public string? Name { get; set; } + public IReadOnlyList? Dependencies { get; set; } +} diff --git a/src/BaGet.Web.Application/Models/Packages/DependencyModel.cs b/src/BaGet.Web.Application/Models/Packages/DependencyModel.cs new file mode 100644 index 000000000..724bc48e4 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/DependencyModel.cs @@ -0,0 +1,7 @@ +namespace BaGet.Web.Application.Models.Packages; + +public record DependencyModel +{ + public string? PackageId { get; init; } + public string? VersionSpec { get; init; } +} \ No newline at end of file diff --git a/src/BaGet.Web.Application/Models/Packages/FrameworkGroup.cs b/src/BaGet.Web.Application/Models/Packages/FrameworkGroup.cs new file mode 100644 index 000000000..0a6416ee5 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/FrameworkGroup.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace BaGet.Web.Application.Models.Packages; + +/// +/// The frameworks of one package, as the package page's Frameworks tab shows them. +/// +public sealed class FrameworkGroup +{ + /// The family (.NET, .NET Core, .NET Standard, .NET Framework, Other). + public string? Name { get; init; } + + /// Frameworks the package ships assets for. + public List Declared { get; } = new(); + + /// Frameworks the package works with without declaring them. + public List Computed { get; } = new(); +} diff --git a/src/BaGet.Web.Application/Models/Packages/ManageAccess.cs b/src/BaGet.Web.Application/Models/Packages/ManageAccess.cs new file mode 100644 index 000000000..c71b5f5bb --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/ManageAccess.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Services.Ownership; + +namespace BaGet.Web.Application.Models.Packages; + +/// +/// Who is shown the owners and the link to the manage page on the npm package, Maven artifact and Docker image screens. The manage pages exist +/// where packages are stored (a local repository) and, for owners, only while accounts are on. +/// +public sealed class ManageAccess +{ + private readonly IRepositoryContext _repository; + private readonly IOptions _accounts; + private readonly IServiceProvider _services; + + /// Creates the service. + public ManageAccess(IRepositoryContext repository, IOptions accounts, IServiceProvider services) + { + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + /// + /// The owners of an npm package or Maven artifact (group:artifact) and whether may open its manage page (an owner, + /// directly or through an organization, or an administrator, signed in). Empty and false in a remote or virtual repository and while accounts are off. + /// + public async Task<(IReadOnlyList Owners, bool CanManage)> OwnersAndManageAsync(ClaimsPrincipal user, string name, CancellationToken cancellationToken) + { + if (_repository.Current.Kind != RepositoryKind.Local || !_accounts.Value.Enabled) return (Array.Empty(), false); + + var ownership = _services.GetService(); + if (ownership == null) return (Array.Empty(), false); + + var owners = (await ownership.GetOwnersAsync(name, cancellationToken)).Select(o => o.OwnerName ?? string.Empty).ToList(); + + return (owners, await CanOpenAsync(user, name, cancellationToken)); + } + + /// An owner (directly or through an organization) or an administrator, signed in. + private async Task CanOpenAsync(ClaimsPrincipal user, string name, CancellationToken cancellationToken) + { + if (user.Identity?.IsAuthenticated != true) return false; + + var sessions = _services.GetService(); + var principal = sessions == null ? null : await sessions.CreateAsync(user); + if (principal == null) return false; + if (principal.IsAdministrator) return true; + + var ownership = _services.GetService(); + + return ownership != null && await ownership.IsOwnerAsync(principal.UserId, principal.UserName, name, cancellationToken); + } + + /// Whether is offered the Docker manage page: signed in and holding Delete on the image (the rule the registry applies to a delete). + public async Task CanManageImageAsync(ClaimsPrincipal user, RepositoryInfo repository, string image, CancellationToken cancellationToken) + { + // The tools exist where images are pushed: only a local repository (the manage page of another kind is 404). + if (user.Identity?.IsAuthenticated != true || repository.Kind != RepositoryKind.Local) return false; + + var sessions = _services.GetService(); + var principal = sessions == null ? null : await sessions.CreateAsync(user); + if (principal == null) return false; + + return await _services.GetRequiredService().IsAllowedAsync(principal, repository, image, OciActions.Delete, cancellationToken); + } +} diff --git a/src/BaGet.Web.Application/Models/Packages/PackageDependencies.cs b/src/BaGet.Web.Application/Models/Packages/PackageDependencies.cs new file mode 100644 index 000000000..ba6c43cc6 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/PackageDependencies.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; +using NuGet.Frameworks; +using NuGet.Versioning; + +namespace BaGet.Web.Application.Models.Packages; + +/// +/// A package's dependencies grouped by target framework, for display. Shared by the +/// package page and the upload preview, which must describe the same package the same +/// way: a preview that grouped or named frameworks differently would be a preview of +/// something else. +/// +public static class PackageDependencies +{ + public static IReadOnlyList GroupByFramework( + IEnumerable? dependencies) + { + if (dependencies == null) return Array.Empty(); + + return dependencies + .GroupBy(d => d.TargetFramework) + .Select(group => new DependencyGroupModel + { + Name = PrettifyTargetFramework(group.Key), + Dependencies = group + .Where(d => d.Id != null) + .Select(d => new DependencyModel + { + PackageId = d.Id, + VersionSpec = (d.VersionRange != null) + ? VersionRange.Parse(d.VersionRange).PrettyPrint() + : string.Empty + }) + .ToList() + }) + .ToList(); + } + + public static string PrettifyTargetFramework(string? targetFramework) + { + if (targetFramework == null) return "All Frameworks"; + + NuGetFramework framework; + try + { + framework = NuGetFramework.Parse(targetFramework); + } + catch (Exception) + { + return targetFramework; + } + + string frameworkName; + if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetCoreApp, + StringComparison.OrdinalIgnoreCase)) + { + frameworkName = (framework.Version.Major >= 5) + ? ".NET" + : ".NET Core"; + } + else if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetStandard, + StringComparison.OrdinalIgnoreCase)) + { + frameworkName = ".NET Standard"; + } + else if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.Net, + StringComparison.OrdinalIgnoreCase)) + { + frameworkName = ".NET Framework"; + } + else + { + frameworkName = framework.Framework; + } + + var frameworkVersion = (framework.Version.Build == 0) + ? framework.Version.ToString(2) + : framework.Version.ToString(3); + + return $"{frameworkName} {frameworkVersion}"; + } +} diff --git a/src/BaGet.Web.Application/Models/Packages/PackageDetails.cs b/src/BaGet.Web.Application/Models/Packages/PackageDetails.cs new file mode 100644 index 000000000..a88aa509e --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/PackageDetails.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Web.Application.Models.Packages; + +/// What the package page shows about the version it displays (a flat copy of the stored package, with no navigation properties). +public sealed record PackageDetails +{ + /// The package ID. + public string? Id { get; init; } + + /// The normalized version. + public string? Version { get; init; } + + /// The description. + public string? Description { get; init; } + + /// The release notes. + public string? ReleaseNotes { get; init; } + + /// The project website, or an empty string. + public string? ProjectUrl { get; init; } + + /// The source repository, or an empty string. + public string? RepositoryUrl { get; init; } + + /// The downloads of this version. + public long Downloads { get; init; } + + /// The authors. + public IReadOnlyList Authors { get; init; } = Array.Empty(); +} diff --git a/src/BaGet.Web.Application/Models/Packages/PackageFrameworks.cs b/src/BaGet.Web.Application/Models/Packages/PackageFrameworks.cs new file mode 100644 index 000000000..48814efce --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/PackageFrameworks.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NuGet.Frameworks; + +namespace BaGet.Web.Application.Models.Packages; + +/// +/// Groups a package's declared target frameworks and computes the further +/// frameworks it is compatible with, the way nuget.org's Frameworks tab does. +/// +internal static class PackageFrameworks +{ + public const string Net = ".NET"; + public const string NetCore = ".NET Core"; + public const string NetStandard = ".NET Standard"; + public const string NetFramework = ".NET Framework"; + public const string Other = "Other"; + + private static readonly string[] GroupOrder = { Net, NetCore, NetStandard, NetFramework, Other }; + + /// The current frameworks a package is checked against. + internal static readonly IReadOnlyList KnownFrameworks = new[] + { + "net10.0", "net9.0", "net8.0", "net7.0", "net6.0", "net5.0", + "netcoreapp3.1", "netcoreapp3.0", "netcoreapp2.2", "netcoreapp2.1", "netcoreapp2.0", + "netstandard2.1", "netstandard2.0", + "net481", "net48", "net472", "net471", "net47", "net462", "net461", "net46", "net452", "net451", "net45", + }; + + public static IReadOnlyList Compute(IEnumerable? declaredMonikers) + { + #pragma warning disable CS8602 + var declared = (declaredMonikers ?? Enumerable.Empty()) + .Where(m => !string.IsNullOrWhiteSpace(m)) + .Select(m => (Moniker: m.Trim(), Framework: NuGetFramework.ParseFolder(m.Trim()))) + .Where(f => !f.Framework.IsAny && !f.Framework.IsAgnostic) + .GroupBy(f => f.Moniker, StringComparer.OrdinalIgnoreCase) + .Select(g => g.First()) + .ToList(); + #pragma warning restore CS8602 + + var groups = new Dictionary(); + + FrameworkGroup GroupFor(string name) + { + if (!groups.TryGetValue(name, out var group)) + { + groups[name] = group = new FrameworkGroup { Name = name }; + } + + return group; + } + + foreach (var (moniker, framework) in declared) + { + GroupFor(GroupName(framework)).Declared.Add(moniker); + } + + var declaredFrameworks = declared + .Where(f => !f.Framework.IsUnsupported) + .Select(f => f.Framework) + .ToList(); + + if (declaredFrameworks.Count > 0) + { + var reducer = new FrameworkReducer(); + + foreach (var moniker in KnownFrameworks) + { + if (declared.Any(d => string.Equals(d.Moniker, moniker, StringComparison.OrdinalIgnoreCase))) continue; + + var target = NuGetFramework.ParseFolder(moniker); + if (reducer.GetNearest(target, declaredFrameworks) != null) + { + GroupFor(GroupName(target)).Computed.Add(moniker); + } + } + } + + return GroupOrder + .Where(groups.ContainsKey) + .Select(name => groups[name]) + .ToList(); + } + + private static string GroupName(NuGetFramework framework) + { + if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetCoreApp, StringComparison.OrdinalIgnoreCase)) + { + return framework.Version.Major >= 5 ? Net : NetCore; + } + + if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetStandard, StringComparison.OrdinalIgnoreCase)) + { + return NetStandard; + } + + if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.Net, StringComparison.OrdinalIgnoreCase)) + { + return NetFramework; + } + + return Other; + } +} diff --git a/src/BaGet.Web.Application/Models/Packages/PackageVersionEntry.cs b/src/BaGet.Web.Application/Models/Packages/PackageVersionEntry.cs new file mode 100644 index 000000000..24e79a2ba --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/PackageVersionEntry.cs @@ -0,0 +1,10 @@ +using System; + +namespace BaGet.Web.Application.Models.Packages; + +/// One row of the versions table of the package page. +/// The normalized version. +/// Its downloads. +/// Whether it is the version shown. +/// When it was published. +public sealed record PackageVersionEntry(string Version, long Downloads, bool Selected, DateTime LastUpdated); diff --git a/src/BaGet.Web.Application/Models/Packages/ReadmeMarkdown.cs b/src/BaGet.Web.Application/Models/Packages/ReadmeMarkdown.cs new file mode 100644 index 000000000..0b654b697 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Packages/ReadmeMarkdown.cs @@ -0,0 +1,106 @@ +using System; +using System.Linq; +using Markdig; +using Markdig.Renderers.Html; +using Markdig.Syntax; +using Markdig.Syntax.Inlines; +using Microsoft.AspNetCore.Html; + +namespace BaGet.Web.Application.Models.Packages; + +/// +/// Renders a package's readme. The package page and the upload preview use one pipeline +/// so that what an uploader is shown is what readers will be shown. +/// +public static class ReadmeMarkdown +{ + // Readmes are written by whoever pushed the package, so they are untrusted: raw HTML in + // the source is escaped rather than rendered, and links and images with a script scheme + // are neutralised. Markdown itself (headings, tables, code, ordinary links) is unaffected. + // + // The extensions are listed rather than taken from UseAdvancedExtensions(), which includes + // GenericAttributes: "# Hi {onmouseover=...}" would emit an event handler. MediaLinks + // (iframes and players) and the maths and diagram blocks are left out too: a readme does + // not need them. + private static readonly MarkdownPipeline Pipeline = CreatePipeline(genericAttributes: false); + + internal static MarkdownPipeline CreatePipeline(bool genericAttributes) + { + var builder = new MarkdownPipelineBuilder() + .UseAbbreviations() + .UseAutoIdentifiers() + .UseAutoLinks() + .UseDefinitionLists() + .UseEmphasisExtras() + .UseFigures() + .UseFootnotes() + .UseGridTables() + .UseListExtras() + .UsePipeTables() + .UseTaskLists() + .DisableHtml(); + + // Only for the test that proves the sanitiser below holds even if the extension is on. + if (genericAttributes) builder.UseGenericAttributes(); + + return builder.Build(); + } + + private static readonly string[] UnsafeSchemes = { "javascript:", "vbscript:", "data:" }; + + public static HtmlString? ToSafeHtml(string? markdown) => ToHtml(markdown); + + public static HtmlString? ToHtml(string? markdown) => ToHtml(markdown, Pipeline); + + internal static HtmlString? ToHtml(string? markdown, MarkdownPipeline pipeline) + { + if (markdown == null) return null; + + var document = Markdown.Parse(markdown, pipeline); + RemoveUnsafeAttributes(document); + foreach (var link in document.Descendants()) + { + if (IsUnsafe(link.Url)) link.Url = "#"; + } + + foreach (var autolink in document.Descendants()) + { + if (IsUnsafe(autolink.Url)) autolink.Url = "#"; + } + + return new HtmlString(document.ToHtml(pipeline)); + } + + /// + /// Defence in depth: whatever put attributes on a node, event handlers (on*), inline + /// styles and the attributes that carry a URL or markup of their own never reach the page. + /// + private static void RemoveUnsafeAttributes(MarkdownDocument document) + { + foreach (var node in document.Descendants()) + { + var properties = node.TryGetAttributes()?.Properties; + properties?.RemoveAll(pair => IsUnsafeAttribute(pair.Key)); + } + } + + private static bool IsUnsafeAttribute(string? name) + { + var cleaned = new string((name ?? string.Empty).Where(c => !char.IsWhiteSpace(c) && !char.IsControl(c)).ToArray()); + + return cleaned.StartsWith("on", StringComparison.OrdinalIgnoreCase) + || UnsafeAttributes.Contains(cleaned, StringComparer.OrdinalIgnoreCase); + } + + private static readonly string[] UnsafeAttributes = { "style", "formaction", "form", "srcdoc", "href", "src", "action", "xlink:href", "data" }; + + private static bool IsUnsafe(string? url) + { + if (string.IsNullOrWhiteSpace(url)) return false; + + // Browsers ignore whitespace and control characters inside the scheme. + var cleaned = new string(url.Where(c => !char.IsWhiteSpace(c) && !char.IsControl(c)).ToArray()); + + return UnsafeSchemes.Any(scheme => cleaned.StartsWith(scheme, StringComparison.OrdinalIgnoreCase)); + } +} \ No newline at end of file diff --git a/src/BaGet.Web.Application/Models/Upload/UploadPreview.cs b/src/BaGet.Web.Application/Models/Upload/UploadPreview.cs new file mode 100644 index 000000000..13e7c8f1a --- /dev/null +++ b/src/BaGet.Web.Application/Models/Upload/UploadPreview.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using Microsoft.AspNetCore.Html; +using BaGet.Web.Application.Models.Packages; + +namespace BaGet.Web.Application.Models.Upload; + +/// What a staged NuGet upload contains, as the preview of the upload page shows it (read from the archive itself). +public sealed class UploadPreview +{ + /// The handle of the staged file; only the user who staged it can open it. + public string? Token { get; set; } + + /// Whether the file is a symbol package (.snupkg, by its nuspec's package type). + public bool IsSymbolPackage { get; set; } + + /// The package ID, from the nuspec. + public string? Id { get; set; } + + /// The normalized version, from the nuspec. + public string? Version { get; set; } + + /// The description. + public string? Description { get; set; } + + /// The authors. + public IReadOnlyList Authors { get; set; } = Array.Empty(); + + /// The license expression or license file the package declares, if any. + public string? License { get; set; } + + /// The license URL, if any. + public string? LicenseUrl { get; set; } + + /// The dependencies by target framework. + public IReadOnlyList DependencyGroups { get; set; } = Array.Empty(); + + /// The readme as safe HTML, if the package has one. + public HtmlString? Readme { get; set; } + + /// The PDBs of a symbol package. + public IReadOnlyList SymbolFiles { get; set; } = Array.Empty(); + + /// Whether the version a symbol package belongs to is on this server. + public bool TargetPackageExists { get; set; } + + /// What to tell about a symbol package whose package is missing. + public string? TargetPackageMessage { get; set; } +} diff --git a/src/BaGet.Web.Application/Models/Upload/UploadTokenRequest.cs b/src/BaGet.Web.Application/Models/Upload/UploadTokenRequest.cs new file mode 100644 index 000000000..a7dd123a2 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Upload/UploadTokenRequest.cs @@ -0,0 +1,18 @@ + +namespace BaGet.Web.Application.Models.Upload; + +/// +/// What the second and third step of the NuGet upload send (publish and discard a staged upload): the handle of the staged file and, while accounts are +/// off, the API key that authenticates the uploader. The key is read and never echoed in an answer. +/// +public sealed class UploadTokenRequest +{ + /// The handle of the staged upload (). + public string Token { get; init; } = string.Empty; + + /// The API key of the uploader while accounts are off (otherwise the signed-in session or the key of the request authenticates). + public string? ApiKey { get; init; } + + /// The confirmation that the uploader may publish the package (required to publish, ignored when discarding). + public bool AcceptTerms { get; init; } +} diff --git a/src/BaGet.Web.Application/Models/Upload/UploadViewModel.cs b/src/BaGet.Web.Application/Models/Upload/UploadViewModel.cs new file mode 100644 index 000000000..34790a736 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Upload/UploadViewModel.cs @@ -0,0 +1,54 @@ +using BaGet.Web.Application.UseCases; + +namespace BaGet.Web.Application.Models.Upload; + +/// What the NuGet upload page (/upload) shows: the form, the preview of a staged file, or the outcome of a step. +public sealed class UploadViewModel +{ + /// + /// The package ID a link arrived with, as "upload a new version of this" does. A hint for the page only: the ID and version that + /// are published are read from the file, never from the request. + /// + public string? Id { get; set; } + + /// Whether accounts are on (the uploader then signs in). + public bool AccountsEnabled { get; set; } + + /// Whether the server is read-only. + public bool IsReadOnlyMode { get; set; } + + /// Whether the visitor is signed in. + public bool SignedIn { get; set; } + + /// With accounts off there is no user to own an upload, so the pusher proves itself with an API key. + public bool NeedsApiKey => !AccountsEnabled; + + /// + /// Nothing on this server can tell one caller from another (accounts off and no global API key): the browser upload is closed. + /// + public bool NothingCanAuthenticate { get; set; } + + /// What the page says in that state, so the explanation and the refusal are one sentence. + public string NoApiKeyExplanation => UploadUseCase.NoApiKeyMessage; + + /// Whether to render the form at all. + public bool CanUpload => !IsReadOnlyMode && !NothingCanAuthenticate && (!AccountsEnabled || SignedIn); + + /// The staged upload awaiting confirmation, or null while on step one. + public UploadPreview? Staged { get; set; } + + /// What happened, for the page to show. + public string? Message { get; set; } + + /// Whether reports a failure. + public bool Failed { get; set; } + + /// Set once something is published, so the page can link to it. + public UploadPreview? Published { get; set; } + + /// The token of a staged upload whose API key was rejected, so the key can be entered again. + public string? RetryToken { get; set; } + + /// The HTTP status the page is answered with (200, or the refusal's). + public int StatusCode { get; set; } = 200; +} diff --git a/src/BaGet.Web.Application/Models/Upload/UploadedFile.cs b/src/BaGet.Web.Application/Models/Upload/UploadedFile.cs new file mode 100644 index 000000000..ea7dec6b3 --- /dev/null +++ b/src/BaGet.Web.Application/Models/Upload/UploadedFile.cs @@ -0,0 +1,33 @@ +using System; +using System.IO; + +namespace BaGet.Web.Application.Models.Upload; + +/// +/// A file chosen in an upload form, as a use case sees it: the name the client gave, its size and a way to read it. The web layer adapts its +/// own file type to it (IFormFile of a multipart request), so a use case needs no HTTP types. +/// +public sealed class UploadedFile +{ + private readonly Func _open; + + /// Creates the file. + /// The name the client sent (never trusted as a path). + /// The size in bytes. + /// Opens the content for reading; each call returns a new stream the caller disposes. + public UploadedFile(string? fileName, long length, Func open) + { + FileName = fileName ?? string.Empty; + Length = length; + _open = open ?? throw new ArgumentNullException(nameof(open)); + } + + /// The name the client sent. + public string FileName { get; } + + /// The size in bytes. + public long Length { get; } + + /// Opens the content for reading. + public Stream OpenReadStream() => _open(); +} diff --git a/src/BaGet.Web.Application/README.md b/src/BaGet.Web.Application/README.md new file mode 100644 index 000000000..b23691d6e --- /dev/null +++ b/src/BaGet.Web.Application/README.md @@ -0,0 +1,13 @@ +# Extension.BaGet.Web.Application + +The web **use cases** of [BaGet Extension](https://pieroviano.github.io/BaGet/): the data of the browse, upload and legal screens as plain DTOs +(`StatisticsViewModel`, `LegalScreen`, `IndexScreen`, `PackageScreen`, `ReportAbuseScreen`, the npm, Maven, Docker and upload view models, ...), their use cases (`StatisticsUseCase`, `LegalUseCase`, `IndexUseCase`, `PackageUseCase`, `ReportAbuseUseCase`, `UploadUseCase`, `NpmBrowseUseCase`, `MavenBrowseUseCase`, `DockerBrowseUseCase`, ...) and the helpers that compute presentation +data (readme Markdown to safe HTML, install snippets, dependency and framework grouping). A browser upload takes its file as an HTTP-free `UploadedFile` and authenticates through `UploadAuthenticator` (the session, a pasted API key while accounts are off, or the key of a JSON API request). No MVC or Razor dependency (test-enforced); the `/api/ui` controllers that expose these use cases as JSON are in +[`Extension.BaGet.Web.V3`](https://www.nuget.org/packages/Extension.BaGet.Web.V3), the screens in [`Extension.BaGet.Web.FrontEnd`](https://www.nuget.org/packages/Extension.BaGet.Web.FrontEnd). + +A use case takes its inputs explicitly, returns a `ScreenResult` (see `Extension.BaGet.Identity.Application`) and never sees `HttpContext`, `ModelState` +or `TempData`. `AddBaGetWebUseCases` registers them; `AddBaGetWebApplication` calls it. + +## Layout + +One type per file, namespace = `BaGet.Web.Application` + folder (`CodeLayoutTests`): `UseCases`, `Screens`, `Snippets`, `Services`, `Models/{Browse,Packages,Npm,Maven,Docker,Upload}`, `Extensions`. diff --git a/src/BaGet.Web.Application/Screens/IndexScreen.cs b/src/BaGet.Web.Application/Screens/IndexScreen.cs new file mode 100644 index 000000000..3b5322656 --- /dev/null +++ b/src/BaGet.Web.Application/Screens/IndexScreen.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Protocol.Models; + +namespace BaGet.Web.Application.Screens; + +/// What the front page and the package list show: the search that was asked for and its results. +public sealed record IndexScreen +{ + /// The search text. + public string? Query { get; init; } + + /// The 1-based page of results. + public int PageIndex { get; init; } = 1; + + /// The package type filter, any for none. + public string PackageType { get; init; } = "any"; + + /// The target framework filter, any for none. + public string Framework { get; init; } = "any"; + + /// Whether prerelease versions are included. + public bool Prerelease { get; init; } = true; + + /// The requested order. + public SearchSort SortBy { get; init; } = SearchSort.Relevance; + + /// The orders the search provider can apply on the server; with only the default there is nothing to choose. + public IReadOnlyList SupportedSorts { get; init; } = new[] { SearchSort.Relevance }; + + /// True for the front page: the repository's root with no search. Everything else lists packages. + public bool IsHome { get; init; } + + /// The feed's totals, shown on the front page; null when the database cannot report them. + public FeedStatistics? Totals { get; init; } + + /// The page of results (empty on the front page). + public IReadOnlyList Packages { get; init; } = Array.Empty(); + + /// When each listed package ID was last published, by ID; empty when unsupported. + public IReadOnlyDictionary LastUpdated { get; init; } = new Dictionary(); +} diff --git a/src/BaGet.Web.Application/Screens/LegalContent.cs b/src/BaGet.Web.Application/Screens/LegalContent.cs new file mode 100644 index 000000000..f21baa80f --- /dev/null +++ b/src/BaGet.Web.Application/Screens/LegalContent.cs @@ -0,0 +1,28 @@ +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Html; +using Microsoft.Extensions.Hosting; +using BaGet.Web.Application.Models.Packages; + +namespace BaGet.Web.Application.Screens; + +/// +/// The workflow behind the legal pages: reads the operator-supplied Markdown file. Used by LegalController. BaGet ships no legal text of its own: there is no content +/// while the file is not configured, is not an allowed Markdown path () or does not exist. +/// +internal static class LegalContent +{ + /// The rendered file, or null when the page is a 404. + public static async Task ReadAsync(string? configuredPath, IHostEnvironment environment, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(configuredPath) || !MarkdownFilePathAttribute.IsAllowed(configuredPath)) return null; + + // Path.Combine keeps an absolute path as it is. + var fullPath = Path.Combine(environment.ContentRootPath, configuredPath); + if (!File.Exists(fullPath)) return null; + + return ReadmeMarkdown.ToSafeHtml(await File.ReadAllTextAsync(fullPath, cancellationToken)); + } +} diff --git a/src/BaGet.Web.Application/Screens/PackageScreen.cs b/src/BaGet.Web.Application/Screens/PackageScreen.cs new file mode 100644 index 000000000..5210e1be8 --- /dev/null +++ b/src/BaGet.Web.Application/Screens/PackageScreen.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using BaGet.Core; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.Screens; + +/// What the package page shows. +public sealed record PackageScreen +{ + /// False when the package (or any listed version of it) does not exist; then only names the ID. + public bool Found { get; init; } + + /// The version shown. + public PackageDetails Package { get; init; } = new(); + + /// The package is a dotnet template. + public bool IsDotnetTemplate { get; init; } + + /// The package is a dotnet tool. + public bool IsDotnetTool { get; init; } + + /// When any version was last published. + public DateTime LastUpdated { get; init; } + + /// Downloads of every version. + public long TotalDownloads { get; init; } + + /// The packages that depend on this one. + public IReadOnlyList UsedBy { get; init; } = Array.Empty(); + + /// The dependencies, by framework. + public IReadOnlyList DependencyGroups { get; init; } = Array.Empty(); + + /// The listed versions, newest first. + public IReadOnlyList Versions { get; init; } = Array.Empty(); + + /// The readme as safe HTML (), or null. + public string? ReadmeHtml { get; init; } + + /// The frameworks the package supports, by family. + public IReadOnlyList FrameworkGroups { get; init; } = Array.Empty(); + + /// The install commands, one tab per tool. + public IReadOnlyList InstallTabs { get; init; } = Array.Empty(); + + /// Owner names; empty unless accounts are enabled and the package has owners. + public IReadOnlyList Owners { get; init; } = Array.Empty(); + + /// The avatar address of each owner by name; empty when Gravatar is off or accounts are disabled. + public IReadOnlyDictionary OwnerAvatars { get; init; } = new Dictionary(); + + /// + /// Where the management page is, when the caller may open it (an owner holding the Manage permission, or an administrator), else null. + /// The use case answers an application-relative address (~/packages/…); the controller resolves it against the path base. + /// + public string? ManageUrl { get; init; } + + /// The icon address. + public string? IconUrl { get; init; } + + /// The license address, null for a license expression or file. + public string? LicenseUrl { get; init; } + + /// Where the package file is downloaded. + public string? PackageDownloadUrl { get; init; } + + /// + /// This version on nuget.info, the web app of NuGet Package Explorer, as nuget.org links it. nuget.info always downloads from + /// nuget.org, so the link only works for a package that is also published there. + /// + public string? PackageExplorerUrl { get; init; } +} diff --git a/src/BaGet.Web.Application/Screens/ReportAbuseScreen.cs b/src/BaGet.Web.Application/Screens/ReportAbuseScreen.cs new file mode 100644 index 000000000..dd0f9aa8e --- /dev/null +++ b/src/BaGet.Web.Application/Screens/ReportAbuseScreen.cs @@ -0,0 +1,11 @@ +using BaGet.Web.Application.Models.Browse; + +namespace BaGet.Web.Application.Screens; + +/// The report-abuse screen: the package it is about, what was typed, and whether the report was recorded. +/// The package ID. +/// The package version. +/// Reports are kept in the database, which Azure Table storage cannot do. +/// True once the report was recorded. +/// What was typed (empty on the first visit). +public sealed record ReportAbuseScreen(string? Id, string? Version, bool CanReport, bool Submitted, ReportAbuseForm Form); diff --git a/src/BaGet.Web.Application/Services/UploadAuthenticator.cs b/src/BaGet.Web.Application/Services/UploadAuthenticator.cs new file mode 100644 index 000000000..8d8269f03 --- /dev/null +++ b/src/BaGet.Web.Application/Services/UploadAuthenticator.cs @@ -0,0 +1,50 @@ +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using BaGet.Identity.Application.Security; + +namespace BaGet.Web.Application.Services; + +/// +/// Who is uploading through a browser form (NuGet, npm, Maven). A caller that authenticated with an API key (JSON API) is that key, within its scopes +/// and repository limits. With accounts on it is the signed-in session; with accounts off there is no session to trust, so a pasted API key +/// authenticates instead - exactly as the push endpoints require one. +/// +public sealed class UploadAuthenticator +{ + private readonly IOptions _accounts; + private readonly IAuthenticationService _authentication; + private readonly IServiceProvider _services; + + /// Creates the authenticator. + public UploadAuthenticator(IOptions accounts, IAuthenticationService authentication, IServiceProvider services) + { + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + /// The uploader, or null when nothing authenticates the request. + /// The request's user (the session, or the owner of the key). + /// The API key that authenticated a JSON API request, or null. + /// The API key pasted into the form (used only while accounts are off). + /// Cancellation. + public async Task AuthenticateAsync(ClaimsPrincipal user, BaGetPrincipal? key, string? apiKey, CancellationToken cancellationToken) + { + if (key != null) return key; + + if (!_accounts.Value.Enabled) + { + return await _authentication.AuthenticatePrincipalAsync(apiKey, cancellationToken); + } + + // Resolved per request: the factory is only registered while accounts are on. + var factory = _services.GetService(); + + return factory == null ? null : await factory.CreateAsync(user); + } +} diff --git a/src/BaGet.Web.Application/Services/UploadAvailability.cs b/src/BaGet.Web.Application/Services/UploadAvailability.cs new file mode 100644 index 000000000..52db2a09b --- /dev/null +++ b/src/BaGet.Web.Application/Services/UploadAvailability.cs @@ -0,0 +1,27 @@ +using BaGet.Core; + +namespace BaGet.Web.Application.Services; + +/// +/// Whether the server can take an upload at all, independent of who is asking. One rule for the Upload page and the +/// navigation that links to it, so the site never offers a page that could only explain why it is closed. +/// +internal static class UploadAvailability +{ + /// + /// Nothing on the server can tell one caller from another: accounts are off and no global API key is set, + /// which is how BaGet ships. + /// + internal static bool NothingCanAuthenticate(BaGetOptions options, AccountsOptions accounts) + => !accounts.Enabled && string.IsNullOrEmpty(options.ApiKey); + + /// + /// Whether an upload can succeed for someone able to authenticate: not read-only, the maintenance gate open + /// (a database copy closes it) and something to authenticate with. Signing in is not required here: an + /// anonymous visitor is sent to sign in by the page itself. + /// + internal static bool IsPossible(BaGetOptions options, AccountsOptions accounts, MaintenanceGate? gate) + => !options.IsReadOnlyMode + && !(gate?.IsClosed ?? false) + && !NothingCanAuthenticate(options, accounts); +} diff --git a/src/BaGet.Web.Application/Snippets/DockerSnippets.cs b/src/BaGet.Web.Application/Snippets/DockerSnippets.cs new file mode 100644 index 000000000..1cb78340e --- /dev/null +++ b/src/BaGet.Web.Application/Snippets/DockerSnippets.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; + +namespace BaGet.Web.Application.Snippets; + +/// +/// The commands and configuration the Docker pages show: docker login with an API key, pull and push by tag or digest, and +/// the daemon setting a plain-http registry needs. Image references are {host}/{repository}/{image}: the BaGet repository +/// is the first path segment. +/// +public static class DockerSnippets +{ + /// The login command; the password is an API key. + public static string Login(string host) => $"docker login {host}"; + + /// The reference of an image in the registry, with a tag or a digest. + public static string Reference(string host, string repository, string image, string? tag = null, string? digest = null) + => $"{host}/{repository}/{image}" + (digest != null ? "@" + digest : tag != null ? ":" + tag : string.Empty); + + /// The pull command. + public static string Pull(string host, string repository, string image, string? tag = null, string? digest = null) + => "docker pull " + Reference(host, repository, image, tag, digest); + + /// The commands that push a local image to the registry. + public static IReadOnlyList Push(string host, string repository, string image, string tag = "latest") + => new[] + { + $"docker tag my-image:{tag} {Reference(host, repository, image, tag)}", + $"docker push {Reference(host, repository, image, tag)}", + }; + + /// A multi-platform push with buildx. + public static string BuildxPush(string host, string repository, string image, string tag = "latest") + => $"docker buildx build --platform linux/amd64,linux/arm64 -t {Reference(host, repository, image, tag)} --push ."; + + /// The daemon setting that allows a registry served over plain http (/etc/docker/daemon.json). + public static IReadOnlyList InsecureRegistry(string host) + => new[] + { + "{", + $" \"insecure-registries\": [\"{host}\"]", + "}", + }; + + /// The curl call that gets a token for a scope with an API key, for scripts. + public static string Token(string tokenUrl, string repository, string image, string actions = "pull") + => $"curl -u user:API_KEY \"{tokenUrl}?service=BaGet&scope=repository:{repository}/{image}:{actions}\""; +} diff --git a/src/BaGet.Web.Application/Snippets/InstallSnippet.cs b/src/BaGet.Web.Application/Snippets/InstallSnippet.cs new file mode 100644 index 000000000..c2e6b64ed --- /dev/null +++ b/src/BaGet.Web.Application/Snippets/InstallSnippet.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace BaGet.Web.Application.Snippets; + +/// One tab of the "install / configure / push" commands of a package, artifact or image page (one tool per tab). +public sealed class InstallSnippet +{ + /// The tool the tab is for. + public string? Name { get; init; } + + /// A shell prompt shown before the first line; not part of the copied text. + public string? Prefix { get; init; } + + /// The lines to copy. + public IReadOnlyList? Lines { get; init; } +} diff --git a/src/BaGet.Web.Application/Snippets/InstallSnippets.cs b/src/BaGet.Web.Application/Snippets/InstallSnippets.cs new file mode 100644 index 000000000..ab49b40da --- /dev/null +++ b/src/BaGet.Web.Application/Snippets/InstallSnippets.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; + +namespace BaGet.Web.Application.Snippets; + +/// +/// The "install this package" commands of the package page, one tab per tool. +/// +internal static class InstallSnippets +{ + public static IReadOnlyList Build(string? id, string? version, bool isTemplate, bool isTool) + { + if (isTemplate) + { + return new[] + { + new InstallSnippet { Name = ".NET CLI", Prefix = ">", Lines = new[] { $"dotnet new install {id}::{version}" } }, + }; + } + + if (isTool) + { + return new[] + { + new InstallSnippet { Name = ".NET CLI", Prefix = ">", Lines = new[] { $"dotnet tool install --global {id} --version {version}" } }, + }; + } + + // Cake needs an explicit opt-in to resolve a prerelease version. + #pragma warning disable CS8602 + var cakeSuffix = version.Contains('-') ? "&prerelease" : string.Empty; + #pragma warning restore CS8602 + var cakeSource = $"nuget:?package={id}&version={version}{cakeSuffix}"; + + return new[] + { + new InstallSnippet { Name = ".NET CLI", Prefix = ">", Lines = new[] { $"dotnet add package {id} --version {version}" } }, + new InstallSnippet { Name = "PackageReference", Prefix = "", Lines = new[] { $"" } }, + new InstallSnippet + { + Name = "Central Package Management", + Prefix = "", + Lines = new[] { $"", $"" }, + }, + new InstallSnippet { Name = "Paket CLI", Prefix = ">", Lines = new[] { $"paket add {id} --version {version}" } }, + new InstallSnippet { Name = "Package Manager", Prefix = "PM>", Lines = new[] { $"Install-Package {id} -Version {version}" } }, + new InstallSnippet { Name = "Script & Interactive", Prefix = "", Lines = new[] { $"#r \"nuget: {id}, {version}\"" } }, + new InstallSnippet { Name = "File-based apps", Prefix = "", Lines = new[] { $"#:package {id}@{version}" } }, + new InstallSnippet { Name = "Cake", Prefix = "", Lines = new[] { $"#addin {cakeSource}", $"#tool {cakeSource}" } }, + new InstallSnippet { Name = "NUKE", Prefix = ">", Lines = new[] { $"nuke :add-package {id} --version {version}" } }, + }; + } +} diff --git a/src/BaGet.Web.Application/Snippets/MavenSnippets.cs b/src/BaGet.Web.Application/Snippets/MavenSnippets.cs new file mode 100644 index 000000000..be1b70ee8 --- /dev/null +++ b/src/BaGet.Web.Application/Snippets/MavenSnippets.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using System.Net; + +namespace BaGet.Web.Application.Snippets; + +/// +/// The configuration the Maven pages show: the settings.xml server entry (the credentials Maven sends after the repository +/// challenges it), the POM's distributionManagement and repositories, the dependency to copy, and Gradle's +/// equivalents. One definition, so the list page, the artifact page and the upload page never disagree. Values are XML-escaped. +/// +internal static class MavenSnippets +{ + private static string X(string? value) => WebUtility.HtmlEncode(value ?? string.Empty); + + /// The <server> entry for ~/.m2/settings.xml; its id must be the one the POM's repository uses. + public static IReadOnlyList SettingsXml(string repositoryId) => new[] + { + "", + " ", + " ", + " " + X(repositoryId) + "", + " your user name", + " your API key", + " ", + " ", + "", + }; + + /// + /// The <mirror> entry for ~/.m2/settings.xml that sends every request for Maven Central through this + /// repository (a remote repository that proxies it); its id is also the <server> id of the credentials. + /// + public static IReadOnlyList Mirror(string repositoryId, string url) => new[] + { + "", + " ", + " ", + " " + X(repositoryId) + "", + " central", + " " + X(url) + "", + " ", + " ", + "", + }; + + /// The POM's distributionManagement: where mvn deploy sends releases and snapshots. + public static IReadOnlyList DistributionManagement(string repositoryId, string url) => new[] + { + "", + " ", + " " + X(repositoryId) + "", + " " + X(url) + "", + " ", + " ", + " " + X(repositoryId) + "", + " " + X(url) + "", + " ", + "", + }; + + /// The POM's repositories entry a consumer adds to resolve from this repository. + public static IReadOnlyList Repositories(string repositoryId, string url, bool releases, bool snapshots) => new[] + { + "", + " ", + " " + X(repositoryId) + "", + " " + X(url) + "", + " " + (releases ? "true" : "false") + "", + " " + (snapshots ? "true" : "false") + "", + " ", + "", + }; + + /// The dependency element for an artifact version. + public static IReadOnlyList Dependency(string groupId, string artifactId, string version) => new[] + { + "", + " " + X(groupId) + "", + " " + X(artifactId) + "", + " " + X(version) + "", + "", + }; + + /// Gradle's repository block (Kotlin DSL) with the credentials from properties. + public static IReadOnlyList GradleRepository(string url) => new[] + { + "repositories {", + " maven {", + " url = uri(\"" + url + "\")", + " credentials {", + " username = providers.gradleProperty(\"mavenUser\").get()", + " password = providers.gradleProperty(\"mavenKey\").get()", + " }", + " }", + "}", + }; + + /// Gradle's dependency notation for an artifact version. + public static string GradleDependency(string groupId, string artifactId, string version) + => $"implementation(\"{groupId}:{artifactId}:{version}\")"; + + /// The command that deploys the project to the repository set up in the POM. + public static string DeployCommand => "mvn deploy"; + + /// The command that fetches an artifact by coordinates, for a quick check. + public static string GetCommand(string groupId, string artifactId, string version, string repositoryId, string url) + => $"mvn dependency:get -Dartifact={groupId}:{artifactId}:{version} -DremoteRepositories={repositoryId}::::{url}"; +} diff --git a/src/BaGet.Web.Application/Snippets/NpmInfoName.cs b/src/BaGet.Web.Application/Snippets/NpmInfoName.cs new file mode 100644 index 000000000..59c753e95 --- /dev/null +++ b/src/BaGet.Web.Application/Snippets/NpmInfoName.cs @@ -0,0 +1,7 @@ +namespace BaGet.Web.Application.Snippets; + +/// Name helpers that the pages need without the validation of . +internal static class NpmInfoName +{ + public static string? Scope(string name) => BaGet.Core.NpmNames.Scope(name); +} diff --git a/src/BaGet.Web.Application/Snippets/NpmInstallSnippets.cs b/src/BaGet.Web.Application/Snippets/NpmInstallSnippets.cs new file mode 100644 index 000000000..4d6cbc5aa --- /dev/null +++ b/src/BaGet.Web.Application/Snippets/NpmInstallSnippets.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; + +namespace BaGet.Web.Application.Snippets; + +/// +/// The commands and .npmrc lines the npm pages show: how to point a client at the repository's registry, sign in, install +/// and publish. One definition, so the list page, the package page and the upload page never disagree. +/// +internal static class NpmInstallSnippets +{ + /// The .npmrc key under which npm keeps the token for a registry: //host:port/path/:_authToken. + public static string AuthKey(string registryUrl) + { + var uri = new Uri(registryUrl); + + return "//" + uri.Authority + uri.AbsolutePath.TrimEnd('/') + "/:_authToken"; + } + + /// + /// The registry line of an .npmrc: registry=… for everything, or @scope:registry=… when the package is + /// scoped (so packages of other scopes keep coming from npmjs). + /// + public static string RegistryLine(string registryUrl, string? scope) + => (scope == null ? "registry" : scope + ":registry") + "=" + registryUrl; + + /// The install tabs for : the install command, and the client configuration it needs. + public static IReadOnlyList Build(string name, string? version, string? tag, string registryUrl) + { + var scope = NpmInfoName.Scope(name); + var spec = version == null ? name : name + "@" + version; + + var install = new List { "npm install " + spec }; + if (tag != null && tag != "latest") install.Add("npm install " + name + "@" + tag); + + return new[] + { + new InstallSnippet { Name = "npm", Prefix = ">", Lines = install }, + new InstallSnippet { Name = "yarn", Prefix = ">", Lines = new[] { "yarn add " + spec } }, + new InstallSnippet { Name = "pnpm", Prefix = ">", Lines = new[] { "pnpm add " + spec } }, + new InstallSnippet + { + Name = ".npmrc", + Lines = new[] + { + RegistryLine(registryUrl, scope), + AuthKey(registryUrl) + "=", + }, + }, + }; + } + + /// The commands that sign in and publish to the registry. + public static IReadOnlyList PublishLines(string registryUrl) + => new[] + { + "npm login --registry=" + registryUrl, + "npm publish --registry=" + registryUrl, + }; +} diff --git a/src/BaGet.Web.Application/UseCases/DockerBrowseUseCase.cs b/src/BaGet.Web.Application/UseCases/DockerBrowseUseCase.cs new file mode 100644 index 000000000..ecaa67198 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/DockerBrowseUseCase.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using BaGet.Web.Application.Models.Docker; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.UseCases; + +/// +/// The screens of a Docker repository: the image list (/docker-images) with the commands that point Docker at the registry, and one image +/// (/docker-images/{image}; with a digest, one manifest in full). Used by DockerBrowseApiController, which the view controller calls in process. +/// +public sealed class DockerBrowseUseCase +{ + /// Images per page. + public const int ResultsPerPage = 20; + + private readonly IOciRegistry _registry; + private readonly IUrlGenerator _urls; + private readonly IRepositoryAccess _access; + private readonly IRepositoryContext _repository; + private readonly ManageAccess _manage; + + /// Creates the use case. + public DockerBrowseUseCase(IOciRegistry registry, IUrlGenerator urls, IRepositoryAccess access, IRepositoryContext repository, ManageAccess manage) + { + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + _urls = urls ?? throw new ArgumentNullException(nameof(urls)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _manage = manage ?? throw new ArgumentNullException(nameof(manage)); + } + + /// The images whose name contains the text (only those the visitor may read) and the commands that point Docker at the registry. + public async Task> ImagesAsync(string? query, int pageIndex, ClaimsPrincipal user, CancellationToken cancellationToken) + { + if (pageIndex < 1) + { + return ScreenResult.Invalid(new DockerImagesViewModel(), new Dictionary { ["p"] = new[] { "The page must be 1 or more." } }, 400); + } + + var repository = _repository.Current; + var result = await _registry.ListImagesAsync( + query, + (pageIndex - 1) * ResultsPerPage, + ResultsPerPage, + (name, token) => _access.CanReadPackageAsync(user, repository, name, token), + cancellationToken); + + var (host, isHttp) = _urls.GetOciRegistryHost(); + var repositoryName = repository.Name; + var isRemote = repository.Kind == RepositoryKind.Remote; + var tabs = new List + { + new() { Name = "Login", Prefix = ">", Lines = new[] { DockerSnippets.Login(host) } }, + new() { Name = "Pull", Prefix = ">", Lines = new[] { DockerSnippets.Pull(host, repositoryName, "team/app", "latest") } }, + }; + if (isRemote) + { + // A cache of Docker Hub serves the official images as single names: nginx is library/nginx there. + tabs.Add(new InstallSnippet { Name = "Pull an official image", Prefix = ">", Lines = new[] { DockerSnippets.Pull(host, repositoryName, "nginx", "latest") } }); + } + else + { + tabs.Add(new InstallSnippet { Name = "Push", Prefix = ">", Lines = DockerSnippets.Push(host, repositoryName, "team/app") }); + tabs.Add(new InstallSnippet { Name = "Multi-platform", Prefix = ">", Lines = new[] { DockerSnippets.BuildxPush(host, repositoryName, "team/app") } }); + } + + if (isHttp) tabs.Add(new InstallSnippet { Name = "Plain http (daemon.json)", Lines = DockerSnippets.InsecureRegistry(host) }); + + return ScreenResult.Ok(new DockerImagesViewModel + { + Query = query, + PageIndex = pageIndex, + Result = result, + Host = host, + IsHttp = isHttp, + RepositoryName = repositoryName, + IsRemote = isRemote, + IsVirtual = repository.Kind == RepositoryKind.Virtual, + CommandTabs = tabs, + }); + } + + /// + /// One image: tags, manifests and, with a digest, one manifest in full. Not found when the image name or the digest is not valid; an image or + /// manifest that does not exist is the page that explains it, with status 404. + /// + public async Task> ImageAsync(string? image, string? digest, string? artifactType, ClaimsPrincipal user, CancellationToken cancellationToken) + { + if (!OciNames.IsValidImage(image)) return ScreenResult.NotFound(); + if (digest != null && !OciNames.IsValidDigest(digest)) return ScreenResult.NotFound(); + + var repository = _repository.Current; + var repositoryName = repository.Name; + var isRemote = repository.Kind == RepositoryKind.Remote; + var registryUrl = $"{_urls.GetOciRegistryUrl()}{repositoryName}/{image}/"; + ScreenResult Missing(OciImageInfo? info) => ScreenResult.Ok( + new DockerImageViewModel + { + Image = image, + Digest = digest, + ArtifactType = artifactType, + Info = info, + RepositoryName = repositoryName, + IsRemote = isRemote, + RegistryUrl = registryUrl, + StatusCode = 404, + }, + 404); + + var info = await _registry.GetImageAsync(image!, cancellationToken); + if (info == null) + { + // The page explains what is missing, with the status a link checker expects. + return Missing(null); + } + + OciManifestDetail? selected = null; + if (digest != null) + { + selected = await _registry.GetManifestDetailAsync(image!, digest, cancellationToken); + if (selected == null) return Missing(info); + } + + IReadOnlyList referrers = Array.Empty(); + if (selected != null) + { + referrers = await _registry.GetReferrersAsync(image!, selected.Summary.Digest, string.IsNullOrWhiteSpace(artifactType) ? null : artifactType.Trim(), cancellationToken) ?? Array.Empty(); + } + + var (host, _) = _urls.GetOciRegistryHost(); + var tag = selected?.Summary.Tags.FirstOrDefault() ?? info.Tags.FirstOrDefault()?.Name; + var tabs = new List(); + if (tag != null) tabs.Add(new InstallSnippet { Name = "Pull by tag", Prefix = ">", Lines = new[] { DockerSnippets.Pull(host, repositoryName, image!, tag: tag) } }); + var pullDigest = selected?.Summary.Digest ?? info.Tags.FirstOrDefault()?.Digest ?? info.Manifests.FirstOrDefault()?.Digest; + if (pullDigest != null) tabs.Add(new InstallSnippet { Name = "Pull by digest", Prefix = ">", Lines = new[] { DockerSnippets.Pull(host, repositoryName, image!, digest: pullDigest) } }); + if (!isRemote) tabs.Add(new InstallSnippet { Name = "Push", Prefix = ">", Lines = DockerSnippets.Push(host, repositoryName, image!) }); + + return ScreenResult.Ok(new DockerImageViewModel + { + Image = image, + Digest = digest, + ArtifactType = artifactType, + Info = info, + Selected = selected, + Referrers = referrers, + Host = host, + RepositoryName = repositoryName, + IsRemote = isRemote, + RegistryUrl = registryUrl, + PullTabs = tabs, + CanManage = await _manage.CanManageImageAsync(user, repository, image!, cancellationToken), + }); + } +} diff --git a/src/BaGet.Web.Application/UseCases/IndexUseCase.cs b/src/BaGet.Web.Application/UseCases/IndexUseCase.cs new file mode 100644 index 000000000..21f236940 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/IndexUseCase.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using BaGet.Protocol.Models; +using BaGet.Web.Application.Models.Browse; +using BaGet.Web.Application.Screens; + +namespace BaGet.Web.Application.UseCases; + +/// +/// The front page and the package list (/, /packages, /?q=…, and under /r/{repo}/) of a NuGet repository: the +/// totals on the front page, else one page of search results. +/// +public sealed class IndexUseCase +{ + /// Results per page. + public const int ResultsPerPage = 20; + + private readonly ISearchService _search; + private readonly StatisticsService _statistics; + + /// Creates the use case. + public IndexUseCase(ISearchService search, StatisticsService statistics) + { + _search = search ?? throw new ArgumentNullException(nameof(search)); + _statistics = statistics ?? throw new ArgumentNullException(nameof(statistics)); + } + + /// The orders the search provider can apply (only relevance when it says nothing). + public IReadOnlyCollection SupportedSorts + => _search.SupportedSorts ?? new[] { SearchSort.Relevance }; + + /// False when the query cannot be answered (a sort that is not a defined value, a page below 1): the screen answers 400. + public static bool IsValid(IndexQuery query) + => Enum.IsDefined(typeof(SearchSort), query.SortBy) && query.PageIndex >= 1; + + /// The front page (when the query asks for nothing) or one page of results. + /// What was asked for. + /// True when the address is the repository's root without a q parameter: only then can the screen be the front page. + /// Cancels the search. + public async Task> GetAsync(IndexQuery query, bool atRepositoryRoot, CancellationToken cancellationToken) + { + if (query == null) throw new ArgumentNullException(nameof(query)); + + var supported = SupportedSorts.ToList(); + var screen = new IndexScreen + { + Query = query.Query, + PageIndex = query.PageIndex, + PackageType = query.PackageType, + Framework = query.Framework, + Prerelease = query.Prerelease, + SortBy = query.SortBy, + SupportedSorts = supported, + }; + + if (IsFrontPage(query, atRepositoryRoot)) + { + return ScreenResult.Ok(screen with + { + IsHome = true, + Totals = _statistics.IsSupported ? await _statistics.GetAsync(cancellationToken) : null, + }); + } + + var packageType = query.PackageType == "any" ? null : query.PackageType; + var framework = query.Framework == "any" ? null : query.Framework; + var canSort = supported.Count > 1; + + var search = await _search.SearchAsync( + new SearchRequest + { + Skip = (query.PageIndex - 1) * ResultsPerPage, + Take = ResultsPerPage, + IncludePrerelease = query.Prerelease, + IncludeSemVer2 = true, + PackageType = packageType, + Framework = framework, + Query = query.Query, + + // A provider that cannot sort ignores the request, so the page stays honest + // about it by not offering the choice. + SortBy = canSort && supported.Contains(query.SortBy) ? query.SortBy : SearchSort.Relevance, + }, + cancellationToken); + + IReadOnlyList packages = search.Data ?? (IReadOnlyList)Array.Empty(); + var lastUpdated = await _statistics.GetLastUpdatedAsync( + packages.Select(p => p.PackageId).ToList(), + cancellationToken, + includePrerelease: query.Prerelease, + includeSemVer2: true); + + return ScreenResult.Ok(screen with { Packages = packages, LastUpdated = lastUpdated }); + } + + private static bool IsFrontPage(IndexQuery query, bool atRepositoryRoot) + => atRepositoryRoot + && string.IsNullOrWhiteSpace(query.Query) + && query.PackageType == "any" + && query.Framework == "any" + && query.Prerelease + && query.PageIndex == 1; +} diff --git a/src/BaGet.Web.Application/UseCases/LegalScreen.cs b/src/BaGet.Web.Application/UseCases/LegalScreen.cs new file mode 100644 index 000000000..34946944f --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/LegalScreen.cs @@ -0,0 +1,8 @@ +using BaGet.Web.Application.Models.Packages; + +namespace BaGet.Web.Application.UseCases; + +/// What a legal page (Terms of Use, Privacy Policy) shows: its heading and the operator's Markdown rendered to safe HTML. +/// The heading and page title. +/// The operator's Markdown file as HTML (raw HTML in the source is escaped, script links neutralised: ). +public sealed record LegalScreen(string Title, string ContentHtml); diff --git a/src/BaGet.Web.Application/UseCases/LegalUseCase.cs b/src/BaGet.Web.Application/UseCases/LegalUseCase.cs new file mode 100644 index 000000000..02e67d5c6 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/LegalUseCase.cs @@ -0,0 +1,44 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using BaGet.Web.Application.Screens; + +namespace BaGet.Web.Application.UseCases; + +/// +/// The Terms of Use (/terms) and Privacy Policy (/privacy) screens: the operator-supplied Markdown files +/// (Site:TermsOfUsePath, Site:PrivacyPolicyPath). Not found while a file is not configured, is not an allowed Markdown path or does not exist. +/// +public sealed class LegalUseCase +{ + private readonly IOptionsSnapshot _site; + private readonly IHostEnvironment _environment; + + /// Creates the use case. + public LegalUseCase(IOptionsSnapshot site, IHostEnvironment environment) + { + _site = site ?? throw new ArgumentNullException(nameof(site)); + _environment = environment ?? throw new ArgumentNullException(nameof(environment)); + } + + /// The Privacy Policy. + public Task> PrivacyAsync(CancellationToken cancellationToken) + => ShowAsync(_site.Value.PrivacyPolicyPath, "Privacy Policy", cancellationToken); + + /// The Terms of Use. + public Task> TermsAsync(CancellationToken cancellationToken) + => ShowAsync(_site.Value.TermsOfUsePath, "Terms of Use", cancellationToken); + + private async Task> ShowAsync(string? path, string title, CancellationToken cancellationToken) + { + var content = await LegalContent.ReadAsync(path, _environment, cancellationToken); + + return content == null + ? ScreenResult.NotFound() + : ScreenResult.Ok(new LegalScreen(title, content.Value ?? string.Empty)); + } +} diff --git a/src/BaGet.Web.Application/UseCases/MavenBrowseUseCase.cs b/src/BaGet.Web.Application/UseCases/MavenBrowseUseCase.cs new file mode 100644 index 000000000..db4d2eb92 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/MavenBrowseUseCase.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.Options; +using BaGet.Web.Application.Models.Maven; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Models.Upload; +using BaGet.Web.Application.Services; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.UseCases; + +/// +/// The screens of a Maven repository: the artifact list (/maven-artifacts) with the configuration that points Maven and Gradle at the +/// repository, one artifact (/maven-artifacts/{group}/{artifact}/{version?}) and the browser deployment (/maven-upload), whose +/// deploy goes through , the call mvn deploy's uploads end in. Used by +/// MavenBrowseApiController, which the view controller calls in process. +/// +public sealed class MavenBrowseUseCase +{ + /// Artifacts per page. + public const int ResultsPerPage = 20; + + internal const string ReadOnlyMessage = "This server is in read-only mode, so nothing can be uploaded."; + internal const string SignInMessage = "Sign in to upload an artifact."; + internal const string ApiKeyRejectedMessage = "That API key was not accepted."; + internal const string NoFileMessage = "Choose a file or a POM to deploy."; + + private readonly IMavenRepository _maven; + private readonly IUrlGenerator _urls; + private readonly IRepositoryAccess _access; + private readonly IRepositoryContext _repository; + private readonly IOptionsSnapshot _options; + private readonly IOptions _accounts; + private readonly UploadAuthenticator _authenticator; + private readonly ManageAccess _manage; + + /// Creates the use case. + public MavenBrowseUseCase( + IMavenRepository maven, + IUrlGenerator urls, + IRepositoryAccess access, + IRepositoryContext repository, + IOptionsSnapshot options, + IOptions accounts, + UploadAuthenticator authenticator, + ManageAccess manage) + { + _maven = maven ?? throw new ArgumentNullException(nameof(maven)); + _urls = urls ?? throw new ArgumentNullException(nameof(urls)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); + _manage = manage ?? throw new ArgumentNullException(nameof(manage)); + } + + /// The artifacts whose coordinates or POM text contain the search text (only those the visitor may open) and the client configuration. + public async Task> ArtifactsAsync(string? query, int pageIndex, ClaimsPrincipal user, CancellationToken cancellationToken) + { + if (pageIndex < 1) + { + return ScreenResult.Invalid(new MavenArtifactsViewModel(), new Dictionary { ["p"] = new[] { "The page must be 1 or more." } }, 400); + } + + // The listing names only the artifacts whose pages the visitor may open. + var repository = _repository.Current; + var result = await _maven.SearchAsync( + query, + (pageIndex - 1) * ResultsPerPage, + ResultsPerPage, + (name, token) => _access.CanReadPackageAsync(user, repository, name, token), + cancellationToken); + var settings = await _maven.GetSettingsAsync(cancellationToken); + + var kind = repository.Kind; + var id = repository.Name; + var url = _urls.GetMavenRepositoryUrl(); + var tabs = new List { new() { Name = "settings.xml", Lines = MavenSnippets.SettingsXml(id) } }; + if (kind == RepositoryKind.Remote) tabs.Add(new InstallSnippet { Name = "Mirror of Maven Central (settings.xml)", Lines = MavenSnippets.Mirror(id, url) }); + if (kind != RepositoryKind.Remote) tabs.Add(new InstallSnippet { Name = "Deploy (pom.xml)", Lines = MavenSnippets.DistributionManagement(id, url) }); + + tabs.Add(new InstallSnippet { Name = "Resolve (pom.xml)", Lines = MavenSnippets.Repositories(id, url, settings.Policy != MavenPolicy.Snapshots, settings.Policy != MavenPolicy.Releases) }); + tabs.Add(new InstallSnippet { Name = "Gradle", Lines = MavenSnippets.GradleRepository(url) }); + + return ScreenResult.Ok(new MavenArtifactsViewModel + { + Query = query, + PageIndex = pageIndex, + Result = result, + Settings = settings, + RepositoryUrl = url, + Kind = kind, + RepositoryName = id, + ConfigurationTabs = tabs, + }); + } + + /// + /// One artifact: its versions, and for the chosen version its files, POM and the dependency to copy. Not found when the coordinates or the + /// version are not valid Maven names; an artifact or version that does not exist is the page that explains it, with status 404. + /// + public async Task> ArtifactAsync(string? group, string? artifact, string? version, ClaimsPrincipal user, CancellationToken cancellationToken) + { + if (!MavenNames.IsValidGroupId(group) || !MavenNames.IsValidArtifactId(artifact)) return ScreenResult.NotFound(); + if (version != null && !MavenNames.IsValidVersion(version)) return ScreenResult.NotFound(); + + var repositoryUrl = _urls.GetMavenRepositoryUrl(); + var repositoryName = _repository.Current.Name; + + var info = await _maven.GetArtifactAsync(group!, artifact!, cancellationToken); + if (info == null) + { + // The page explains what is missing, with the status a link checker expects. + return Explained(new MavenArtifactViewModel { Group = group, Artifact = artifact, Version = version, RepositoryUrl = repositoryUrl, RepositoryName = repositoryName, StatusCode = 404 }); + } + + var chosen = version == null ? info.Latest : info.Versions.FirstOrDefault(v => v.Version == version); + if (chosen == null) + { + return Explained(new MavenArtifactViewModel { Group = group, Artifact = artifact, Version = version, Info = info, RepositoryUrl = repositoryUrl, RepositoryName = repositoryName, StatusCode = 404 }); + } + + var selected = await _maven.GetVersionAsync(info.GroupId, info.ArtifactId, chosen.Version, cancellationToken); + IReadOnlyList installTabs = Array.Empty(); + if (selected != null) + { + installTabs = new[] + { + new InstallSnippet { Name = "Maven", Lines = MavenSnippets.Dependency(info.GroupId, info.ArtifactId, chosen.Version) }, + new InstallSnippet { Name = "Gradle", Lines = new[] { MavenSnippets.GradleDependency(info.GroupId, info.ArtifactId, chosen.Version) } }, + new InstallSnippet + { + Name = "Check", + Prefix = ">", + Lines = new[] { MavenSnippets.GetCommand(info.GroupId, info.ArtifactId, chosen.Version, repositoryName, repositoryUrl) }, + }, + }; + } + + // Owners and the manage page belong to a repository that holds artifacts of its own (a local one). + var (owners, canManage) = await _manage.OwnersAndManageAsync(user, info.Name, cancellationToken); + + return Explained(new MavenArtifactViewModel + { + Group = group, + Artifact = artifact, + Version = version, + Info = info, + Selected = selected, + RepositoryUrl = repositoryUrl, + RepositoryName = repositoryName, + InstallTabs = installTabs, + Owners = owners, + CanManage = canManage, + }); + } + + /// The upload page before anything was posted. + public async Task> UploadFormAsync(ClaimsPrincipal user, CancellationToken cancellationToken) + => Result(Build(user, await _maven.GetSettingsAsync(cancellationToken), null, null, false, null, null, 200)); + + /// Deploys the chosen files under the given coordinates. A refusal is the form again (with the coordinates posted), with the status it carries. + public async Task> DeployAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? groupId, + string? artifactId, + string? version, + string? packaging, + string? classifier, + UploadedFile? file, + UploadedFile? pom, + string? apiKey, + CancellationToken cancellationToken) + => Result(await DeployCoreAsync(user, key, groupId, artifactId, version, packaging, classifier, file, pom, apiKey, cancellationToken)); + + private async Task DeployCoreAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? groupId, + string? artifactId, + string? version, + string? packaging, + string? classifier, + UploadedFile? file, + UploadedFile? pom, + string? apiKey, + CancellationToken cancellationToken) + { + var settings = await _maven.GetSettingsAsync(cancellationToken); + var posted = new MavenDeployment { GroupId = groupId, ArtifactId = artifactId, Version = version, Packaging = packaging, Classifier = classifier }; + MavenUploadViewModel Refuse(int status, string message) => Build(user, settings, posted, message, true, null, null, status); + + if (_options.Value.IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); + if (UploadAvailability.NothingCanAuthenticate(_options.Value, _accounts.Value)) + { + return Refuse(401, "This server has no API key configured and no accounts, so the browser upload is closed."); + } + + var principal = await _authenticator.AuthenticateAsync(user, key, apiKey, cancellationToken); + if (principal == null) return Refuse(401, _accounts.Value.Enabled ? SignInMessage : ApiKeyRejectedMessage); + + var hasFile = file != null && file.Length > 0; + var hasPom = pom != null && pom.Length > 0; + if (!hasFile && !hasPom) return Refuse(400, NoFileMessage); + + await using var main = hasFile ? file!.OpenReadStream() : null; + await using var pomStream = hasPom ? pom!.OpenReadStream() : null; + MavenResult result; + try + { + result = await _maven.DeployAsync( + principal, + new MavenDeployment + { + GroupId = groupId, + ArtifactId = artifactId, + Version = version, + Packaging = packaging, + Classifier = classifier, + File = main, + Pom = pomStream, + }, + cancellationToken); + } + catch (ScanBlockedException e) + { + // The scanning policy of the repository refuses an artifact with known vulnerabilities. + return Refuse(403, e.Message); + } + + if (!result.Succeeded) + { + return Refuse(StatusOf(result.Status), result.Message ?? "The artifact was not deployed."); + } + + return Build(user, settings, posted, result.Message ?? "Deployed.", false, result.Subject, version?.Trim(), 200); + } + + // A page that explains a missing artifact carries 404 as its status (the screen is still shown). + private static ScreenResult Explained(MavenArtifactViewModel model) + => ScreenResult.Ok(model, model.StatusCode == 200 ? null : model.StatusCode); + + private static ScreenResult Result(MavenUploadViewModel model) + => model.Failed + ? ScreenResult.Invalid(model, model.Message ?? string.Empty, model.StatusCode) + : ScreenResult.Ok(model, model.StatusCode == 200 ? null : model.StatusCode); + + private static int StatusOf(MavenStatus status) => status switch + { + MavenStatus.Unauthorized => 401, + MavenStatus.Forbidden => 403, + MavenStatus.NotFound => 404, + MavenStatus.Conflict => 409, + MavenStatus.TooLarge => 413, + _ => 400, + }; + + private MavenUploadViewModel Build( + ClaimsPrincipal user, + MavenRepositorySettings settings, + MavenDeployment? posted, + string? message, + bool failed, + string? deployedName, + string? deployedVersion, + int status) + => new() + { + AccountsEnabled = _accounts.Value.Enabled, + IsReadOnlyMode = _options.Value.IsReadOnlyMode, + SignedIn = user.Identity?.IsAuthenticated == true, + NothingCanAuthenticate = UploadAvailability.NothingCanAuthenticate(_options.Value, _accounts.Value), + RepositoryUrl = _urls.GetMavenRepositoryUrl(), + RepositoryName = _repository.Current.Name, + Settings = settings, + Message = message, + Failed = failed, + DeployedName = deployedName, + DeployedVersion = deployedVersion, + Posted = posted, + StatusCode = status, + }; +} diff --git a/src/BaGet.Web.Application/UseCases/NpmBrowseUseCase.cs b/src/BaGet.Web.Application/UseCases/NpmBrowseUseCase.cs new file mode 100644 index 000000000..a2fea5fd5 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/NpmBrowseUseCase.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.Options; +using BaGet.Web.Application.Models.Npm; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Models.Upload; +using BaGet.Web.Application.Services; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.UseCases; + +/// +/// The screens of an npm repository: the package list (/npm-packages), one package (/npm-packages/{name}) and the browser upload +/// (/npm-upload), whose publish goes through , the call npm publish ends in. Used by +/// NpmBrowseApiController, which the view controller calls in process. +/// +public sealed class NpmBrowseUseCase +{ + /// Packages per page. + public const int ResultsPerPage = 20; + + internal const string ReadOnlyMessage = "This server is in read-only mode, so nothing can be uploaded."; + internal const string SignInMessage = "Sign in to upload a package."; + internal const string ApiKeyRejectedMessage = "That API key was not accepted."; + internal const string NoFileMessage = "Choose the .tgz file that npm pack made."; + + private readonly INpmRegistry _registry; + private readonly IUrlGenerator _urls; + private readonly IRepositoryAccess _access; + private readonly IRepositoryContext _repository; + private readonly IOptionsSnapshot _options; + private readonly IOptions _accounts; + private readonly UploadAuthenticator _authenticator; + private readonly ManageAccess _manage; + + /// Creates the use case. + public NpmBrowseUseCase( + INpmRegistry registry, + IUrlGenerator urls, + IRepositoryAccess access, + IRepositoryContext repository, + IOptionsSnapshot options, + IOptions accounts, + UploadAuthenticator authenticator, + ManageAccess manage) + { + _registry = registry ?? throw new ArgumentNullException(nameof(registry)); + _urls = urls ?? throw new ArgumentNullException(nameof(urls)); + _access = access ?? throw new ArgumentNullException(nameof(access)); + _repository = repository ?? throw new ArgumentNullException(nameof(repository)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); + _manage = manage ?? throw new ArgumentNullException(nameof(manage)); + } + + /// The packages whose name contains the text, listed only when the visitor may open their pages. + public async Task> PackagesAsync(string? query, int pageIndex, ClaimsPrincipal user, CancellationToken cancellationToken) + { + if (pageIndex < 1) + { + return ScreenResult.Invalid(new NpmPackagesViewModel(), new Dictionary { ["p"] = new[] { "The page must be 1 or more." } }, 400); + } + + // The listing names only the packages whose pages the visitor may open. + var repository = _repository.Current; + var result = await _registry.SearchAsync( + query, + (pageIndex - 1) * ResultsPerPage, + ResultsPerPage, + (name, token) => _access.CanReadPackageAsync(user, repository, name, token), + cancellationToken); + + return ScreenResult.Ok( + new NpmPackagesViewModel { Query = query, PageIndex = pageIndex, Result = result, RegistryUrl = _urls.GetNpmRegistryUrl() }); + } + + /// + /// One package: readme, versions, dist-tags, owners and install commands. Not found when the name is not a valid npm name; a package + /// that does not exist is the page that explains it, with status 404. + /// + public async Task> PackageAsync(string? id, string? requestedVersion, ClaimsPrincipal user, CancellationToken cancellationToken) + { + if (!NpmNames.TryParseLookup(id, out var name, out _)) return ScreenResult.NotFound(); + + var registryUrl = _urls.GetNpmRegistryUrl(); + var package = await _registry.GetPackageAsync(name, cancellationToken); + if (package == null) + { + // The page explains what is missing, with the status a link checker expects. + return Explained(new NpmPackageViewModel { Id = id, RequestedVersion = requestedVersion, RegistryUrl = registryUrl, StatusCode = 404 }); + } + + var selected = (requestedVersion == null ? null : package.Versions.FirstOrDefault(v => v.Version == requestedVersion)) + ?? package.Latest; + if (selected == null) + { + return Explained(new NpmPackageViewModel { Id = id, RequestedVersion = requestedVersion, RegistryUrl = registryUrl, Package = package }); + } + + var readme = ReadmeMarkdown.ToHtml(selected.Readme); + var selectedTags = package.DistTags.Where(t => t.Value == selected.Version).Select(t => t.Key).OrderBy(t => t, StringComparer.Ordinal).ToList(); + var installTabs = NpmInstallSnippets.Build(package.Name, selected.Version, selectedTags.FirstOrDefault(t => t != "latest"), registryUrl); + + // Owners and the manage page belong to a repository that holds packages of its own; a remote one caches an upstream's and a + // virtual one holds none (it is managed where the package is stored). + var (owners, canManage) = await _manage.OwnersAndManageAsync(user, package.Name, cancellationToken); + + return Explained(new NpmPackageViewModel + { + Id = id, + RequestedVersion = requestedVersion, + RegistryUrl = registryUrl, + Package = package, + Selected = selected, + Readme = readme, + SelectedTags = selectedTags, + InstallTabs = installTabs, + Owners = owners, + CanManage = canManage, + }); + } + + /// The upload page before anything was posted. + public ScreenResult UploadForm(ClaimsPrincipal user) => Result(Build(user, null, false, null, 200)); + + /// + /// Publishes the chosen tarball with the dist-tag (default latest). A refusal is the form again, with the status it carries. + /// + public async Task> PublishAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + UploadedFile? package, + string? tag, + string? apiKey, + CancellationToken cancellationToken) + => Result(await PublishCoreAsync(user, key, package, tag, apiKey, cancellationToken)); + + private async Task PublishCoreAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + UploadedFile? package, + string? tag, + string? apiKey, + CancellationToken cancellationToken) + { + if (_options.Value.IsReadOnlyMode) return Refuse(user, 401, ReadOnlyMessage); + if (UploadAvailability.NothingCanAuthenticate(_options.Value, _accounts.Value)) + { + return Refuse(user, 401, "This server has no API key configured and no accounts, so the browser upload is closed."); + } + + var principal = await _authenticator.AuthenticateAsync(user, key, apiKey, cancellationToken); + if (principal == null) return Refuse(user, 401, _accounts.Value.Enabled ? SignInMessage : ApiKeyRejectedMessage); + + if (package == null || package.Length == 0) return Refuse(user, 400, NoFileMessage); + + // The registry reads the file twice (its package.json, then the bytes), so it must be seekable. + using var upload = package.OpenReadStream(); + using var copy = upload.CanSeek ? null : await upload.AsTemporaryFileStreamAsync(cancellationToken); + var content = copy ?? upload; + + var chosenTag = string.IsNullOrWhiteSpace(tag) ? "latest" : tag.Trim(); + NpmResult result; + try + { + result = await _registry.PublishTarballAsync(principal, content, chosenTag, cancellationToken); + } + catch (ScanBlockedException e) + { + // The scanning policy of the repository refuses a package with known vulnerabilities. + return Refuse(user, 403, e.Message); + } + + if (!result.Succeeded) + { + return Refuse(user, StatusOf(result.Status), result.Message ?? "The package was not published."); + } + + return Build(user, result.Message ?? "Published.", false, result.Subject, 200); + } + + // A page that explains a missing package carries 404 as its status (the screen is still shown). + private static ScreenResult Explained(NpmPackageViewModel model) + => ScreenResult.Ok(model, model.StatusCode == 200 ? null : model.StatusCode); + + private static ScreenResult Result(NpmUploadViewModel model) + => model.Failed + ? ScreenResult.Invalid(model, model.Message ?? string.Empty, model.StatusCode) + : ScreenResult.Ok(model, model.StatusCode == 200 ? null : model.StatusCode); + + private static int StatusOf(NpmStatus status) => status switch + { + NpmStatus.Unauthorized => 401, + NpmStatus.Forbidden => 403, + NpmStatus.NotFound => 404, + NpmStatus.Conflict => 409, + _ => 400, + }; + + private NpmUploadViewModel Refuse(ClaimsPrincipal user, int status, string message) => Build(user, message, true, null, status); + + private NpmUploadViewModel Build(ClaimsPrincipal user, string? message, bool failed, string? publishedName, int status) + { + var registryUrl = _urls.GetNpmRegistryUrl(); + + return new NpmUploadViewModel + { + AccountsEnabled = _accounts.Value.Enabled, + IsReadOnlyMode = _options.Value.IsReadOnlyMode, + SignedIn = user.Identity?.IsAuthenticated == true, + NothingCanAuthenticate = UploadAvailability.NothingCanAuthenticate(_options.Value, _accounts.Value), + RegistryUrl = registryUrl, + PublishLines = NpmInstallSnippets.PublishLines(registryUrl), + Message = message, + Failed = failed, + PublishedName = publishedName, + StatusCode = status, + }; + } +} diff --git a/src/BaGet.Web.Application/UseCases/PackageUseCase.cs b/src/BaGet.Web.Application/UseCases/PackageUseCase.cs new file mode 100644 index 000000000..7ce7afbd5 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/PackageUseCase.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using NuGet.Versioning; +using BaGet.Identity.Application.Links; +using BaGet.Identity.Application.Security; +using BaGet.Identity.Application.Services.Accounts; +using BaGet.Identity.Application.Services.Ownership; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Screens; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.Application.UseCases; + +/// +/// The package page (/packages/{id}/{version?}, and under /r/{repo}/): finds the version to show (the requested one, else +/// the newest listed) and gathers what the page displays. The access rule on the package (Read) is the repository check of the screen. +/// +public sealed class PackageUseCase +{ + private readonly IPackageService _packages; + private readonly IPackageContentService _content; + private readonly ISearchService _search; + private readonly IUrlGenerator _url; + private readonly IServiceProvider _services; + + /// Creates the use case. + /// The packages of the repository. + /// The package files. + /// Finds the dependents. + /// Builds the download addresses. + /// Finds the services that exist only when accounts are enabled (owners, avatars, the Manage rule). + public PackageUseCase( + IPackageService packages, + IPackageContentService content, + ISearchService search, + IUrlGenerator url, + IServiceProvider services) + { + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _content = content ?? throw new ArgumentNullException(nameof(content)); + _search = search ?? throw new ArgumentNullException(nameof(search)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + _services = services ?? throw new ArgumentNullException(nameof(services)); + } + + /// Loads the page of (and , else the newest listed one). + /// The package ID. + /// The requested version, or null for the newest listed one. + /// The signed in user (decides whether the Manage link is offered); null or anonymous for a visitor. + /// Cancels the load. + public async Task> GetAsync( + string id, + string? version, + ClaimsPrincipal? caller, + CancellationToken cancellationToken) + { + var packages = await _packages.FindPackagesAsync(id, cancellationToken); + var listedPackages = packages.Where(p => p.Listed).ToList(); + + // Try to find the requested version. + Package? package = null; + if (NuGetVersion.TryParse(version, out var requestedVersion)) + { + package = packages.SingleOrDefault(p => p.Version == requestedVersion); + } + + // Otherwise try to display the latest version. + if (package == null) + { + package = listedPackages.OrderByDescending(p => p.Version).FirstOrDefault(); + } + + if (package == null) + { + return ScreenResult.Ok(new PackageScreen { Found = false, Package = new PackageDetails { Id = id } }); + } + + var packageVersion = package.Version; + var isTemplate = package.PackageTypes?.Any(t => t.Name?.Equals("Template", StringComparison.OrdinalIgnoreCase) == true) ?? false; + var isTool = package.PackageTypes?.Any(t => t.Name?.Equals("DotnetTool", StringComparison.OrdinalIgnoreCase) == true) ?? false; + + var dependents = await _search.FindDependentsAsync(package.Id, cancellationToken); + + string? readme = null; + if (package.HasReadme) + { + readme = await GetReadmeHtmlOrNullAsync(package.Id, packageVersion, cancellationToken); + } + + var screen = new PackageScreen + { + Found = true, + Package = new PackageDetails + { + Id = package.Id, + Version = package.NormalizedVersionString, + Description = package.Description, + ReleaseNotes = package.ReleaseNotes, + ProjectUrl = package.ProjectUrlString, + RepositoryUrl = package.RepositoryUrlString, + Downloads = package.Downloads, + Authors = package.Authors ?? Array.Empty(), + }, + IsDotnetTemplate = isTemplate, + IsDotnetTool = isTool, + LastUpdated = packages.Max(p => p.Published), + TotalDownloads = packages.Sum(p => p.Downloads), + UsedBy = dependents.Data ?? (IReadOnlyList)Array.Empty(), + DependencyGroups = PackageDependencies.GroupByFramework(package.Dependencies), + Versions = ToVersions(listedPackages, packageVersion), + ReadmeHtml = readme, + IconUrl = package.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(package.Id, packageVersion) + : package.IconUrlString, + LicenseUrl = GetLicenseUrlOrNull(package), + FrameworkGroups = PackageFrameworks.Compute(package.TargetFrameworks?.Select(f => f.Moniker)), + InstallTabs = InstallSnippets.Build(package.Id, package.NormalizedVersionString, isTemplate, isTool), + PackageDownloadUrl = _url.GetPackageDownloadUrl(package.Id, packageVersion), + PackageExplorerUrl = "https://nuget.info/packages/" + + Uri.EscapeDataString(package.Id ?? string.Empty) + "/" + Uri.EscapeDataString(package.NormalizedVersionString ?? string.Empty), + }; + + // PackageOwnershipService is only registered when accounts are enabled. + var ownership = _services.GetService(); + if (ownership != null) + { + var owners = (await ownership.GetOwnersAsync(package.Id, cancellationToken)).Select(o => o.OwnerName).ToList(); + var avatars = await _services.GetRequiredService().GetUrlsAsync(owners, 32, cancellationToken); + string? manageUrl = null; + + // A virtual repository holds no packages to manage: they are managed in the member that stores them. + var repository = _services.GetService()?.Current; + if (caller?.Identity?.IsAuthenticated == true + && repository?.Kind != RepositoryKind.Virtual + && await CanManageAsync(caller, ownership, package.Id, cancellationToken)) + { + manageUrl = RepositoryPageLinks.Manage(repository?.Name, package.Id); + } + + screen = screen with { Owners = owners, OwnerAvatars = avatars, ManageUrl = manageUrl }; + } + + return ScreenResult.Ok(screen); + } + + // The rule of the management page itself: an owner holding a management permission in this repository, or an administrator. + private async Task CanManageAsync(ClaimsPrincipal user, PackageOwnershipService ownership, string? packageId, CancellationToken cancellationToken) + { + var userId = _services.GetService>()?.GetUserId(user); + if (await ownership.IsOwnerAsync(userId, user.Identity?.Name, packageId, cancellationToken) + && await ManagePermission.HeldAnyAsync(_services, user, packageId, cancellationToken)) return true; + + var administrators = _services.GetService(); + return administrators != null && await administrators.IsAdministratorAsync(user, cancellationToken); + } + + /// + /// The license address, or null when there is none. A package that declares a license + /// expression or file carries only the deprecation placeholder here, which leads nowhere useful. + /// + private static string? GetLicenseUrlOrNull(Package package) + { + var url = package.LicenseUrlString; + if (string.IsNullOrEmpty(url)) return null; + if (url.StartsWith("https://aka.ms/deprecateLicenseUrl", StringComparison.OrdinalIgnoreCase)) return null; + + return url; + } + + private static IReadOnlyList ToVersions(IReadOnlyList packages, NuGetVersion selectedVersion) + => packages + .OrderByDescending(p => p.Version) + .Select(p => new PackageVersionEntry(p.Version.ToNormalizedString(), p.Downloads, p.Version == selectedVersion, p.Published)) + .ToList(); + + private async Task GetReadmeHtmlOrNullAsync(string? packageId, NuGetVersion packageVersion, CancellationToken cancellationToken) + { + string readme; + using (var readmeStream = await _content.GetPackageReadmeStreamOrNullAsync(packageId, packageVersion, cancellationToken)) + { + if (readmeStream == null) return null; + + using (var reader = new StreamReader(readmeStream)) + { + readme = await reader.ReadToEndAsync(); + } + } + + return ReadmeMarkdown.ToHtml(readme)?.Value; + } +} diff --git a/src/BaGet.Web.Application/UseCases/ReportAbuseUseCase.cs b/src/BaGet.Web.Application/UseCases/ReportAbuseUseCase.cs new file mode 100644 index 000000000..efd8c1ebf --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/ReportAbuseUseCase.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; +using BaGet.Web.Application.Models.Browse; +using BaGet.Web.Application.Screens; + +namespace BaGet.Web.Application.UseCases; + +/// +/// The report-abuse screen (/packages/{id}/{version}/report-abuse, and under /r/{repo}/; 404 in a virtual repository): +/// records a report against a package version, for its owners and the administrator. Works for any ID and version (a client expands the +/// report abuse template from whatever it is looking at). +/// +public sealed class ReportAbuseUseCase +{ + private readonly IContext _context; + private readonly SystemTime _time; + + /// Creates the use case. + public ReportAbuseUseCase(IContext context, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + /// Reports are kept in the database, which Azure Table storage cannot do. + public bool CanReport => !(_context is NullContext); + + /// The empty form for a package version. + public ScreenResult Get(string? id, string? version) + => ScreenResult.Ok(new ReportAbuseScreen(id, version, CanReport, false, new ReportAbuseForm())); + + /// + /// Validates and records the report: Ok with Submitted once recorded, Invalid with the reasons (keyed by field name) to show the + /// form again, NotFound when reports are unsupported or the ID or version is not one. + /// + public async Task> SubmitAsync(string? id, string? version, ReportAbuseForm form, CancellationToken cancellationToken) + { + if (form == null) throw new ArgumentNullException(nameof(form)); + + var canReport = CanReport; + if (!canReport) return ScreenResult.NotFound(); + + var errors = Validate(form); + if (!AbuseReport.Reasons.Contains(form.Reason, StringComparer.Ordinal)) + { + Add(errors, nameof(ReportAbuseForm.Reason), "Choose one of the reasons listed."); + } + + if (id == null || id.Length > AbstractContext.MaxPackageIdLength || !NuGetVersion.TryParse(version, out var parsed)) + { + return ScreenResult.NotFound(); + } + + var screen = new ReportAbuseScreen(id, version, canReport, false, form); + if (errors.Count > 0) + { + return ScreenResult.Invalid(screen, errors.ToDictionary(p => p.Key, p => p.Value.ToArray())); + } + + #pragma warning disable CS8602 + _context.AbuseReports.Add(new AbuseReport + { + PackageId = id, + PackageVersion = parsed.ToNormalizedString(), + Reason = form.Reason, + Details = form.Details, + ReporterEmail = string.IsNullOrWhiteSpace(form.ReporterEmail) ? null : form.ReporterEmail.Trim(), + Created = _time.UtcNow, + }); + #pragma warning restore CS8602 + await _context.SaveChangesAsync(cancellationToken); + + return ScreenResult.Ok(screen with { Submitted = true }); + } + + // The DataAnnotations of the form, in property order, keyed by property name (what model binding produced for the page). + private static Dictionary> Validate(ReportAbuseForm form) + { + var errors = new Dictionary>(); + var results = new List(); + Validator.TryValidateObject(form, new ValidationContext(form), results, validateAllProperties: true); + foreach (var result in results) + { + foreach (var member in result.MemberNames.DefaultIfEmpty(string.Empty)) + { + Add(errors, member, result.ErrorMessage ?? "The value is not valid."); + } + } + + return errors; + } + + private static void Add(Dictionary> errors, string key, string message) + { + if (!errors.TryGetValue(key, out var list)) errors[key] = list = new List(); + list.Add(message); + } +} diff --git a/src/BaGet.Web.Application/UseCases/StatisticsUseCase.cs b/src/BaGet.Web.Application/UseCases/StatisticsUseCase.cs new file mode 100644 index 000000000..c246722f1 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/StatisticsUseCase.cs @@ -0,0 +1,25 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using BaGet.Web.Application.Models.Browse; + +namespace BaGet.Web.Application.UseCases; + +/// The statistics screen (/stats, /r/{repo}/stats in the request's repository): the feed's totals and lists. +public sealed class StatisticsUseCase +{ + private readonly StatisticsService _statistics; + + /// Creates the use case. + public StatisticsUseCase(StatisticsService statistics) + { + _statistics = statistics ?? throw new ArgumentNullException(nameof(statistics)); + } + + /// The feed's statistics; the model's Statistics is null when the database cannot report them. + public async Task> GetAsync(CancellationToken cancellationToken) + => ScreenResult.Ok( + new StatisticsViewModel(_statistics.IsSupported ? await _statistics.GetAsync(cancellationToken) : null)); +} diff --git a/src/BaGet.Web.Application/UseCases/UploadUseCase.cs b/src/BaGet.Web.Application/UseCases/UploadUseCase.cs new file mode 100644 index 000000000..8f737c7b7 --- /dev/null +++ b/src/BaGet.Web.Application/UseCases/UploadUseCase.cs @@ -0,0 +1,602 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Application.Screens; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Packaging; +using NuGet.Versioning; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Models.Upload; +using BaGet.Web.Application.Services; + +namespace BaGet.Web.Application.UseCases; + +using NuGetPackageType = NuGet.Packaging.Core.PackageType; + +/// +/// Uploading a NuGet package through the browser, in two steps: the first stages the file and shows what it contains, the second +/// publishes it (or the third discards it). Every step goes through the same authorization and the same submission pipeline as +/// dotnet nuget push, so the browser can do what the pusher's own API key could, and no more. The use case of the Upload screen +/// (UploadApiController, which the view controller calls in process). +/// +/// +/// Deliberately not an account page: those answer 404 while accounts are disabled, and this one must still work there - with a +/// pasted API key, exactly as the push endpoint requires one. Each step returns the to render and +/// the status to answer it with; a refusal is a page with a message, never a bare error. +/// +public sealed class UploadUseCase +{ + internal const string ReadOnlyMessage = + "This server is in read-only mode, so nothing can be uploaded."; + + internal const string SignInMessage = + "Sign in to upload a package."; + + internal const string ApiKeyRejectedMessage = + "That API key was not accepted."; + + internal const string NoApiKeyMessage = + "This server has no API key configured and no accounts, so there is nothing to " + + "tell one visitor from another and nothing to authenticate an upload with. " + + "Set \"ApiKey\", or enable \"Accounts:Enabled\", to upload through the browser."; + + internal const string UnknownTokenMessage = + "This upload is no longer staged. It was cancelled, already published, or staged " + + "by someone else - upload the file again."; + + internal const string UnreadableMessage = + "This file could not be read as a package. Upload the .nupkg or .snupkg a build " + + "produced, not a renamed or repacked copy."; + + internal const string TermsMessage = + "Confirm that you have the right to publish this package before submitting."; + + internal const string InvalidSymbolPackageMessage = + "This symbol package is not valid (its entries, a PDB that is not portable, or " + + "PDBs that do not match the package)."; + + internal const string NotASymbolPackageMessage = + "A .snupkg must declare the SymbolsPackage package type in its own nuspec. This " + + "file does not, so it is not a symbol package - and a symbols archive is not a " + + "package either. Repack it as a symbol package, or upload the .nupkg instead."; + + internal const string CouldNotStageMessage = + "The server could not store this upload. Try again."; + + private readonly IOptionsSnapshot _options; + private readonly IOptions _accounts; + private readonly IPackageAuthorizationService _authorization; + private readonly IPackageSubmissionService _submissions; + private readonly ISymbolIndexingService _symbols; + private readonly IPackageStagingService _staging; + private readonly IPackageDatabase _packages; + private readonly ILogger _logger; + private readonly IScanGate _scanGate; + private readonly UploadAuthenticator _authenticator; + + /// Creates the use case. + public UploadUseCase( + IOptionsSnapshot options, + IOptions accounts, + IPackageAuthorizationService authorization, + IPackageSubmissionService submissions, + ISymbolIndexingService symbols, + IPackageStagingService staging, + IPackageDatabase packages, + ILogger logger, + IScanGate scanGate, + UploadAuthenticator authenticator) + { + _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); + _scanGate = scanGate ?? throw new ArgumentNullException(nameof(scanGate)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _submissions = submissions ?? throw new ArgumentNullException(nameof(submissions)); + _symbols = symbols ?? throw new ArgumentNullException(nameof(symbols)); + _staging = staging ?? throw new ArgumentNullException(nameof(staging)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + private bool AccountsEnabled => _accounts.Value.Enabled; + + private bool IsReadOnlyMode => _options.Value.IsReadOnlyMode; + + private bool NothingCanAuthenticate => UploadAvailability.NothingCanAuthenticate(_options.Value, _accounts.Value); + + private string NotAuthenticatedMessage => AccountsEnabled ? SignInMessage : ApiKeyRejectedMessage; + + /// The page as a visitor first sees it (step one). + public ScreenResult Show(ClaimsPrincipal user, string? id) => ScreenResult.Ok(NewModel(user, id)); + + /// Step one: stages the file and describes what it contains. + public async Task> StageAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? id, + UploadedFile? package, + string? apiKey, + CancellationToken cancellationToken) + { + return Result(await StageCoreAsync(user, key, id, package, apiKey, cancellationToken)); + } + + private async Task StageCoreAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? id, + UploadedFile? package, + string? apiKey, + CancellationToken cancellationToken) + { + var model = NewModel(user, id); + + if (IsReadOnlyMode) return Refuse(model, 401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(model, 401, NoApiKeyMessage); + + var principal = await _authenticator.AuthenticateAsync(user, key, apiKey, cancellationToken); + if (principal == null) return Refuse(model, 401, NotAuthenticatedMessage); + + if (package == null || package.Length == 0) + { + return Refuse(model, 400, "Choose a .nupkg or .snupkg file to upload."); + } + + var fileName = Path.GetFileName(package.FileName) ?? string.Empty; + var extension = Path.GetExtension(fileName); + if (!extension.Equals(".nupkg", StringComparison.OrdinalIgnoreCase) && + !extension.Equals(".snupkg", StringComparison.OrdinalIgnoreCase)) + { + return Refuse(model, 400, "A package is a .nupkg file, and symbols are a .snupkg file."); + } + + // The spooled upload is seekable, which is what reading the archive needs; one + // that is not is copied once rather than reported as unreadable. + using var upload = package.OpenReadStream(); + using var copy = upload.CanSeek ? null : await upload.AsTemporaryFileStreamAsync(cancellationToken); + var content = copy ?? upload; + + var staged = await ReadOrNullAsync(content, cancellationToken); + if (staged == null) return Refuse(model, 400, UnreadableMessage); + + // The content decides the pipeline, never the file's name. A .snupkg whose + // nuspec does not declare the symbols package type is therefore not a symbol + // package - and publishing it as a package would store a symbols archive as the + // .nupkg of that ID and version, while the symbol endpoint reads the identical + // bytes as symbols. Refused rather than published as something it is not. + if (extension.Equals(".snupkg", StringComparison.OrdinalIgnoreCase) && !staged.IsSymbolPackage) + { + return Refuse(model, 400, NotASymbolPackageMessage); + } + + // Authorized before the upload is stored: there is no point keeping a file its + // uploader may not publish. + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) + { + return Refuse(model, 403, Denied(staged.Id)); + } + + // The scanning policy of the repository may refuse a package with known vulnerabilities: said now, not after the upload. + if (!staged.IsSymbolPackage) + { + var blocked = await RefuseIfBlockedAsync(model, content, cancellationToken); + if (blocked != null) return blocked; + } + + await DescribeSymbolTargetAsync(staged, cancellationToken); + + content.Position = 0; + + try + { + staged.Token = await _staging.StageAsync(content, principal.UserId, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // A failure the server owns, reported the way the equivalent failure on the + // confirm step is: a sentence with a status code, never a bare 500 or a + // stack trace. + _logger.LogError(e, "Could not stage an upload of {PackageId} {PackageVersion}", staged.Id, staged.Version); + + return Refuse(model, 500, CouldNotStageMessage); + } + + model.Staged = staged; + + return model; + } + + /// Step two: publishes the staged upload. + public async Task> SubmitAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? id, + string token, + string? apiKey, + bool acceptTerms, + CancellationToken cancellationToken) + { + return Result(await SubmitCoreAsync(user, key, id, token, apiKey, acceptTerms, cancellationToken)); + } + + private async Task SubmitCoreAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? id, + string token, + string? apiKey, + bool acceptTerms, + CancellationToken cancellationToken) + { + var model = NewModel(user, id); + + if (IsReadOnlyMode) return Refuse(model, 401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(model, 401, NoApiKeyMessage); + + var principal = await _authenticator.AuthenticateAsync(user, key, apiKey, cancellationToken); + if (principal == null) return RefuseKey(model, token); + + // Whoever staged the upload is the only one who can open it, so another user's + // token is indistinguishable from one that never existed. + Stream content; + using (var stagedStream = await _staging.OpenAsync(token, principal.UserId, cancellationToken)) + { + if (stagedStream == null) return Refuse(model, 404, UnknownTokenMessage); + + // Copied and closed before anything is removed: an open handle on the staged + // blob stops it being deleted on file systems that refuse to delete open files. + content = await stagedStream.AsTemporaryFileStreamAsync(cancellationToken); + } + + using var ownedContent = content; + + var staged = await ReadOrNullAsync(content, cancellationToken); + if (staged == null) + { + await _staging.RemoveAsync(token, principal.UserId, cancellationToken); + return Refuse(model, 400, UnreadableMessage); + } + + staged.Token = token; + await DescribeSymbolTargetAsync(staged, cancellationToken); + + // The checkbox is enforced here too, not only in the browser: the upload stays + // staged so the box can be ticked and the preview submitted again. + if (!acceptTerms) + { + model.Staged = staged; + return Refuse(model, 400, TermsMessage); + } + + // Re-checked at submission: ownership may have changed while the preview was on + // screen, and the first check guarded the store, not the publish. + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) + { + await _staging.RemoveAsync(token, principal.UserId, cancellationToken); + return Refuse(model, 403, Denied(staged.Id)); + } + + content.Position = 0; + + return staged.IsSymbolPackage + ? await PublishSymbolsAsync(model, staged, content, principal, cancellationToken) + : await PublishPackageAsync(model, staged, content, principal, cancellationToken); + } + + /// + /// Discard a staged upload. Authenticated, owner-checked and refused in read-only + /// mode, exactly as the other two steps are: the token is the only handle on an + /// upload, so anyone who learned one - from a log, a screenshot, a shared screen - + /// could otherwise make its owner upload the whole file again, and the deletion is a + /// write to the store that read-only mode is meant to freeze. + /// + public async Task> CancelAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? id, + string token, + string? apiKey, + CancellationToken cancellationToken) + { + return Result(await CancelCoreAsync(user, key, id, token, apiKey, cancellationToken)); + } + + private async Task CancelCoreAsync( + ClaimsPrincipal user, + BaGetPrincipal? key, + string? id, + string token, + string? apiKey, + CancellationToken cancellationToken) + { + var model = NewModel(user, id); + + if (IsReadOnlyMode) return Refuse(model, 401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(model, 401, NoApiKeyMessage); + + var principal = await _authenticator.AuthenticateAsync(user, key, apiKey, cancellationToken); + if (principal == null) return RefuseKey(model, token); + + // Another user's token is indistinguishable from one that never existed, as it + // is when submitting. + if (!await _staging.RemoveAsync(token, principal.UserId, cancellationToken)) + { + return Refuse(model, 404, UnknownTokenMessage); + } + + model.Message = "The upload was discarded."; + + return model; + } + + private async Task PublishPackageAsync( + UploadViewModel model, + UploadPreview staged, + Stream content, + BaGetPrincipal principal, + CancellationToken cancellationToken) + { + PackageIndexingResult result; + // Decided before the push: afterwards every ID exists. + var isNewId = !await _packages.ExistsAsync(staged.Id, cancellationToken); + var refused = await RefuseIfBlockedAsync(model, content, cancellationToken); + if (refused != null) + { + model.Staged = staged; + return refused; + } + + try + { + result = await _submissions.SubmitAsync(content, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException) && !(e is MaintenanceException)) + { + // A failure the server owns: said in a sentence rather than as a stack trace, + // and the upload is kept so it can be submitted again. + _logger.LogError(e, "Could not publish the staged upload {Token}", staged.Token); + + model.Staged = staged; + return Refuse(model, 500, "The server could not publish this package. Try again."); + } + + // An accepted package claims its ID now, as it does on the push endpoint: it is + // the pusher's even while it is being validated. + // The package is already published when this runs, so a failure here must not + // turn the page into a bare 500, and must not keep the staged upload alive. + var ownershipRecorded = true; + try + { + if (result == PackageIndexingResult.Success || result == PackageIndexingResult.Accepted) + { + await _authorization.OnPushedAsync(principal, staged.Id, isNewId, cancellationToken); + } + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogError(e, "Could not record the ownership of {PackageId}", staged.Id); + ownershipRecorded = false; + } + finally + { + await _staging.RemoveAsync(staged.Token, principal.UserId, cancellationToken); + } + + switch (result) + { + case PackageIndexingResult.Success: + case PackageIndexingResult.Accepted: + // Only a package that is indexed can be linked to: an accepted one is + // still being validated, so its page does not exist yet and may never. + if (result == PackageIndexingResult.Success) model.Published = staged; + + model.Message = result == PackageIndexingResult.Accepted + ? $"{staged.Id} {staged.Version} was accepted and is being validated." + : $"{staged.Id} {staged.Version} was published."; + + if (!ownershipRecorded) + { + model.Message += $" Recording you as the owner of {staged.Id} failed; ask an administrator to add you."; + } + + return model; + + case PackageIndexingResult.PackageAlreadyExists: + // This upload can never be published, so keeping it staged would leave a + // file nobody could use. + return Refuse(model, 409, + $"{staged.Id} {staged.Version} is already on this server, and this server does " + + "not replace a published version. Publish a new version instead."); + + default: + return Refuse(model, 400, UnreadableMessage); + } + } + + private async Task PublishSymbolsAsync( + UploadViewModel model, + UploadPreview staged, + Stream? content, + BaGetPrincipal principal, + CancellationToken cancellationToken) + { + // Branched on the indexing result, not on a status code: a malformed symbol + // package and one whose package is missing are told apart here, while the push + // endpoint reports the first as 400 and every exception as 400 as well. + var result = await _symbols.IndexAsync(content, cancellationToken); + + await _staging.RemoveAsync(staged.Token, principal.UserId, cancellationToken); + + switch (result) + { + case SymbolIndexingResult.Success: + // No OnPushedAsync: symbols never claim an ID, exactly as on the symbol + // endpoint, so a symbol upload confers no ownership. + model.Published = staged; + model.Message = $"The symbols for {staged.Id} {staged.Version} were published."; + return model; + + case SymbolIndexingResult.PackageNotFound: + return Refuse(model, 404, MissingSymbolTarget(staged)); + + default: + return Refuse(model, 400, InvalidSymbolPackageMessage); + } + } + + private static string Denied(string? packageId) + => $"You may not publish '{packageId}'. Either someone else owns it, or it predates " + + "this server's accounts and only an administrator may publish to it."; + + private static string MissingSymbolTarget(UploadPreview staged) + => "Symbols can only be uploaded for a package version already on this server. " + + $"Push {staged.Id} {staged.Version} first."; + + /// + /// Everything the preview shows, read from the archive itself. Null when the file is + /// not a package at all. + /// + private async Task ReadOrNullAsync(Stream content, CancellationToken cancellationToken) + { + try + { + content.Position = 0; + + using var reader = new PackageArchiveReader(content, leaveStreamOpen: true); + var nuspec = reader.NuspecReader; + + // The content decides which pipeline runs, not the file's name: a symbol + // package says so in its own nuspec, so renaming a file cannot send it to a + // pipeline its content does not belong to. + var isSymbolPackage = nuspec + .GetPackageTypes() + .Any(t => string.Equals(t.Name, NuGetPackageType.SymbolsPackage.Name, StringComparison.OrdinalIgnoreCase)); + + var staged = new UploadPreview + { + IsSymbolPackage = isSymbolPackage, + Id = nuspec.GetId(), + Version = nuspec.GetVersion().ToNormalizedString(), + }; + + if (isSymbolPackage) + { + staged.SymbolFiles = reader + .GetFiles() + .Where(f => Path.GetExtension(f).Equals(".pdb", StringComparison.OrdinalIgnoreCase)) + .OrderBy(f => f, StringComparer.OrdinalIgnoreCase) + .ToList(); + + return staged; + } + + var metadata = reader.GetPackageMetadata(); + + staged.Description = metadata.Description; + staged.Authors = metadata.Authors ?? Array.Empty(); + staged.LicenseUrl = metadata.LicenseUrlString; + staged.License = nuspec.GetLicenseMetadata()?.License; + staged.DependencyGroups = PackageDependencies.GroupByFramework(metadata.Dependencies); + + if (reader.HasReadme()) + { + using var readme = await reader.GetReadmeAsync(cancellationToken); + using var text = new StreamReader(readme); + + staged.Readme = ReadmeMarkdown.ToHtml(await text.ReadToEndAsync(cancellationToken)); + } + + return staged; + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogInformation(e, "An upload could not be read as a package"); + return null; + } + finally + { + if (content.CanSeek) content.Position = 0; + } + } + + /// + /// Symbols carry no metadata of their own, so the preview reports the version they + /// belong to - and says now, rather than after the upload is confirmed, when there is + /// no such version to attach them to. + /// + private async Task DescribeSymbolTargetAsync(UploadPreview staged, CancellationToken cancellationToken) + { + if (!staged.IsSymbolPackage) return; + if (!NuGetVersion.TryParse(staged.Version, out var version)) return; + + var target = await _packages.FindOrNullAsync(staged.Id, version, includeUnlisted: true, cancellationToken); + + staged.TargetPackageExists = target != null; + staged.TargetPackageMessage = target == null ? MissingSymbolTarget(staged) : null; + } + + /// + /// A rejected API key on the confirm or discard step. The staged upload is untouched, + /// so the page keeps its token and offers the key again instead of dropping back to + /// step one and forcing the whole file to be uploaded again. + /// + private UploadViewModel RefuseKey(UploadViewModel model, string token) + { + if (!AccountsEnabled && !string.IsNullOrEmpty(token) && token.Length == 32 && token.All(Uri.IsHexDigit)) + { + model.RetryToken = token; + } + + return Refuse(model, 401, NotAuthenticatedMessage); + } + + // 403 with the reason when the scanning policy of the repository refuses a package with these dependencies (the stream is rewound). + private async Task RefuseIfBlockedAsync(UploadViewModel model, Stream package, CancellationToken cancellationToken) + { + if (!_scanGate.Enabled || !await _scanGate.BlocksDeploysAsync(cancellationToken)) return null; + + var components = NuGetScanComponents.TryRead(package); + if (components == null) return null; + + try + { + await _scanGate.CheckDeployAsync(components, cancellationToken); + + return null; + } + catch (ScanBlockedException e) + { + return Refuse(model, 403, e.Message); + } + } + + // A refusal is a screen the form is shown again on, with the status the refusal carries and its sentence as the form's error; the rest is the screen. + private static ScreenResult Result(UploadViewModel model) + => model.Failed + ? ScreenResult.Invalid(model, model.Message ?? string.Empty, model.StatusCode) + : ScreenResult.Ok(model, model.StatusCode == 200 ? null : model.StatusCode); + + private static UploadViewModel Refuse(UploadViewModel model, int statusCode, string message) + { + model.Failed = true; + model.Message = message; + model.StatusCode = statusCode; + + return model; + } + + private UploadViewModel NewModel(ClaimsPrincipal user, string? id) => new() + { + Id = id, + AccountsEnabled = AccountsEnabled, + IsReadOnlyMode = IsReadOnlyMode, + SignedIn = user.Identity?.IsAuthenticated == true, + NothingCanAuthenticate = NothingCanAuthenticate, + }; +} diff --git a/src/BaGet.Web.FrontEnd/BaGet.Web.FrontEnd.csproj b/src/BaGet.Web.FrontEnd/BaGet.Web.FrontEnd.csproj new file mode 100644 index 000000000..fc31731b6 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/BaGet.Web.FrontEnd.csproj @@ -0,0 +1,43 @@ + + + + net10.0 + latest + NuGet + BaGet Extension's package browsing screens: the view controllers and views of the home, package, upload, statistics and format browse pages, and AddBaGetFrontEnd. + BaGet.Web.V3 + true + enable + $(NoWarn);CS8620 + Extension.$(MSBuildProjectName) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/ApiCatalogController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/ApiCatalogController.cs new file mode 100644 index 000000000..4648d682d --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/ApiCatalogController.cs @@ -0,0 +1,22 @@ +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.V3.ViewModels; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The administration REST API (/api/v1) for people (/admin/api): where it is, how to authenticate (the key of an +/// administrator with the admin:api scope, or the global key), the password confirmation header, and every operation with the +/// page that offers the same operation. Read-only, administrators only. Replaces the /Admin/Api Razor Page; renders what +/// answers. +/// +public sealed class ApiCatalogController : AdminControllerBase +{ + /// Lists the operations. + [Route("admin/api"), HttpGet, HttpHead, PageHandler] + public async Task Index() + => Render(await Api(api => api.Get()), "Index"); +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/DockerBrowseController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/DockerBrowseController.cs new file mode 100644 index 000000000..ef671bed6 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/DockerBrowseController.cs @@ -0,0 +1,40 @@ +using System.ComponentModel.DataAnnotations; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Models.Docker; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The web pages of a Docker repository: the image list (/docker-images) and one image +/// (/docker-images/{image}, ?digest= for a manifest). They replace the Razor Pages DockerImages and +/// DockerImage: same URLs, same repository rules (: Read on the repository and, +/// for the image page, on the image; 404 in a repository that is not Docker's). Views are in Views/DockerBrowse/. The work is , reached through the JSON twin +/// in process; this controller only renders what it answers. +/// +public sealed class DockerBrowseController : UiControllerBase +{ + /// The image list with a search box and the client commands. + [Route("docker-images"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Docker)] + public async Task Images( + string? q, + [Range(1, int.MaxValue)] int p = 1, + CancellationToken cancellationToken = default) + { + if (!ModelState.IsValid) return BadRequest(); + + return Render(await Api(api => api.Images(q, p, cancellationToken)), "Images"); + } + + /// One image: tags, manifests, and with ?digest= one manifest in full. + [Route("docker-images/{**image}"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Docker)] + public async Task Image(string? image, string? digest, string? artifactType, CancellationToken cancellationToken = default) + => Render(await Api(api => api.Image(image, digest, artifactType, cancellationToken)), "Image"); +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/HomeController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/HomeController.cs new file mode 100644 index 000000000..d8dde3847 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/HomeController.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Routing; +using BaGet.Web.Application.Screens; +using BaGet.Web.V3.Routing; +using BaGet.Web.V3.ViewModels; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The front page (/, with no search) and the package list (/packages, /?q=…) of a NuGet repository, at its own +/// route and at /r/{repo}/…. Replaces the /Index Razor Page: same +/// URLs and links to the front page. In a repository of another format the front page +/// redirects to the format's own browse page (FrontPage). Renders what answers. +/// +[RepositoryPage(FrontPage = true)] +public sealed class HomeController : UiControllerBase +{ + /// The front page or one page of search results. + [Route(""), Route("index"), Route("packages"), RouteNotForLinks("", "index"), HttpGet, HttpHead, PageHandler] + public async Task Index(IndexViewModel model, CancellationToken cancellationToken) + { + if (!ModelState.IsValid) return BadRequest(); + + // Only the repository's root can be the front page; the address decides which question the twin is asked. + var query = model.ToQuery(); + var response = AtRepositoryRoot() + ? await Api(api => api.Home(query.Query, query.PageIndex, query.PackageType, query.Framework, query.Prerelease, query.SortBy, cancellationToken)) + : await Api(api => api.Packages(query.Query, query.PageIndex, query.PackageType, query.Framework, query.Prerelease, query.SortBy, cancellationToken)); + + return Render(response, "Index", screen => model.Fill(screen)); + } + + // The front page of a repository is its root: "/" for the default, "/r/{name}" for another. + private bool AtRepositoryRoot() + { + var path = Request.Path.Value?.TrimEnd('/'); + var root = HttpContext.GetRouteValue(Routes.RepositoryRouteKey) is string repository ? "/r/" + repository : string.Empty; + return string.Equals(path ?? string.Empty, root, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/LegalController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/LegalController.cs new file mode 100644 index 000000000..6826278d4 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/LegalController.cs @@ -0,0 +1,32 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Html; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.UseCases; +using BaGet.Web.V3.ViewModels; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The Terms of Use (/terms) and Privacy Policy (/privacy) pages: the operator-supplied Markdown files +/// (Site:TermsOfUsePath, Site:PrivacyPolicyPath), 404 while a file is not configured or does not exist. Same URLs, same +/// views in Views/Legal/. Renders what answers. +/// +public sealed class LegalController : UiControllerBase +{ + /// The Privacy Policy. + [Route("privacy"), HttpGet, HttpHead, PageHandler] + public async Task Privacy(CancellationToken cancellationToken) + => Render(await Api(api => api.Privacy(cancellationToken)), "Privacy", ToViewModel); + + /// The Terms of Use. + [Route("terms"), HttpGet, HttpHead, PageHandler] + public async Task Terms(CancellationToken cancellationToken) + => Render(await Api(api => api.Terms(cancellationToken)), "Terms", ToViewModel); + + // The view keeps its model (hosts override the view); the twin's DTO carries the rendered HTML as text. + private static object? ToViewModel(LegalScreen screen) => new LegalViewModel(screen.Title, new HtmlString(screen.ContentHtml)); +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/MavenBrowseController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/MavenBrowseController.cs new file mode 100644 index 000000000..9855ffbee --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/MavenBrowseController.cs @@ -0,0 +1,66 @@ +using System.ComponentModel.DataAnnotations; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Models.Maven; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The web pages of a Maven repository: the artifact list (/maven-artifacts), one artifact +/// (/maven-artifacts/{group}/{artifact}/{version?}) and the browser deployment (/maven-upload). They replace the Razor +/// Pages MavenArtifacts, MavenArtifact and MavenUpload: same URLs, same repository rules +/// (: Read on the repository, on group:artifact for the artifact page, the right to +/// publish for the upload; 404 in a repository that is not Maven's). Views are in Views/MavenBrowse/. The work is , reached through the JSON twin +/// in process; this controller only renders what it answers. +/// +public sealed class MavenBrowseController : UiControllerBase +{ + /// The artifact list with a search box and the client configuration. + [Route("maven-artifacts"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Maven)] + public async Task Artifacts( + string? q, + [Range(1, int.MaxValue)] int p = 1, + CancellationToken cancellationToken = default) + { + if (!ModelState.IsValid) return BadRequest(); + + return Render(await Api(api => api.Artifacts(q, p, cancellationToken)), "Artifacts"); + } + + /// One artifact: versions, files, POM, the dependency to copy. + [Route("maven-artifacts/{group}/{artifact}/{version?}"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Maven)] + public async Task Artifact(string? group, string? artifact, string? version, CancellationToken cancellationToken = default) + => Render(await Api(api => api.Artifact(group, artifact, version, cancellationToken)), "Artifact"); + + /// The upload form. + [Route("maven-upload"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Maven, Upload = true)] + public async Task Upload(CancellationToken cancellationToken) + => Render(await Api(api => api.Upload(cancellationToken)), "Upload"); + + /// Deploys the chosen files under the given coordinates. + [Route("maven-upload"), HttpPost, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Maven, Upload = true)] + [UploadSizeLimit] + public async Task UploadPost( + string? groupId, + string? artifactId, + string? version, + string? packaging, + string? classifier, + IFormFile? file, + IFormFile? pom, + string? apiKey, + CancellationToken cancellationToken) + => Render( + await Api(api => api.UploadPost(groupId, artifactId, version, packaging, classifier, file, pom, apiKey, cancellationToken)), + "Upload"); +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/NpmBrowseController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/NpmBrowseController.cs new file mode 100644 index 000000000..a10476377 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/NpmBrowseController.cs @@ -0,0 +1,54 @@ +using System.ComponentModel.DataAnnotations; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Models.Npm; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The web pages of an npm repository: the package list (/npm-packages), one package (/npm-packages/{name}) and the +/// browser upload (/npm-upload). They replace the Razor Pages NpmPackages, NpmPackage and NpmUpload: same URLs, same repository rules (: Read on the repository, on +/// the package for the package page, the right to publish for the upload; 404 in a repository that is not npm's). Views are in +/// Views/NpmBrowse/. The work is , reached through the JSON twin +/// in process; this controller only renders what it answers. +/// +public sealed class NpmBrowseController : UiControllerBase +{ + /// The package list with a search box. + [Route("npm-packages"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Npm)] + public async Task Packages( + string? q, + [Range(1, int.MaxValue)] int p = 1, + CancellationToken cancellationToken = default) + { + if (!ModelState.IsValid) return BadRequest(); + + return Render(await Api(api => api.Packages(q, p, cancellationToken)), "Packages"); + } + + /// One package: readme, versions, dist-tags, install commands. + [Route("npm-packages/{*id}"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Npm)] + public async Task Package(string? id, string? version, CancellationToken cancellationToken = default) + => Render(await Api(api => api.Package(id, version, cancellationToken)), "Package"); + + /// The upload form. + [Route("npm-upload"), HttpGet, HttpHead, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Npm, Upload = true)] + public async Task Upload() + => Render(await Api(api => api.Upload()), "Upload"); + + /// Publishes the chosen tarball with the dist-tag (default latest). + [Route("npm-upload"), HttpPost, PageHandler] + [RepositoryPage(Format = RepositoryFormat.Npm, Upload = true)] + [UploadSizeLimit] + public async Task UploadPost(IFormFile? package, string? tag, string? apiKey, CancellationToken cancellationToken) + => Render(await Api(api => api.UploadPost(package, tag, apiKey, cancellationToken)), "Upload"); +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/PackageController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/PackageController.cs new file mode 100644 index 000000000..156fbf1db --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/PackageController.cs @@ -0,0 +1,24 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Screens; +using BaGet.Web.V3.ViewModels; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The page of a package (/packages/{id}/{version?}, and under /r/{repo}/): the requested version, else the newest +/// listed one. Replaces the /Package Razor Page. The access rule on the +/// package (Read) is the repository check of . Renders what answers. +/// +[RepositoryPage] +public sealed class PackageController : UiControllerBase +{ + /// Shows the package. + [Route("packages/{id}/{version?}"), HttpGet, HttpHead, PageHandler] + public async Task Show(string id, string? version, CancellationToken cancellationToken) + => Render(await Api(api => api.Get(id, version, cancellationToken)), "Show", PackageViewModel.From); +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/ReportAbuseController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/ReportAbuseController.cs new file mode 100644 index 000000000..be84dbab6 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/ReportAbuseController.cs @@ -0,0 +1,48 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Models.Browse; +using BaGet.Web.Application.Screens; +using BaGet.Web.V3.ViewModels; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// Report abuse (/packages/{id}/{version}/report-abuse, and under /r/{repo}/; 404 in a virtual repository). Replaces the +/// /ReportAbuse Razor Page. The form is posted with antiforgery +/// validation (). Renders what answers. +/// +[RepositoryPage(NotOnVirtual = true)] +public sealed class ReportAbuseController : UiControllerBase +{ + /// The empty form. + [Route("packages/{id}/{version}/report-abuse"), HttpGet, HttpHead, PageHandler] + public async Task Show(string? id, string? version) + => Render(await Api(api => api.Get(id, version)), "Show", ToViewModel); + + /// Records the report. + [Route("packages/{id}/{version}/report-abuse"), HttpPost, PageHandler] + public async Task Submit(string? id, string? version, ReportAbuseViewModel model, CancellationToken cancellationToken) + { + // The use case validates the form itself (same rules, same field names), so the errors of model binding are dropped, not shown twice. + ModelState.Clear(); + var form = new ReportAbuseForm { Reason = model.Reason, Details = model.Details, ReporterEmail = model.ReporterEmail }; + + return Render(await Api(api => api.Submit(id, version, form, cancellationToken)), "Show", ToViewModel); + } + + private static object? ToViewModel(ReportAbuseScreen screen) + => new ReportAbuseViewModel + { + Id = screen.Id, + Version = screen.Version, + Reason = screen.Form.Reason, + Details = screen.Form.Details, + ReporterEmail = screen.Form.ReporterEmail, + Submitted = screen.Submitted, + CanReport = screen.CanReport, + }; +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/StatisticsController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/StatisticsController.cs new file mode 100644 index 000000000..b0e0a8f35 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/StatisticsController.cs @@ -0,0 +1,22 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Models.Browse; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The feed's statistics (/stats, and /r/{repo}/stats; 404 in a virtual repository). Replaces the /Statistics +/// Razor Page. +/// +[RepositoryPage(NotOnVirtual = true)] +public sealed class StatisticsController : UiControllerBase +{ + /// The statistics page. + [Route("stats"), HttpGet, HttpHead, PageHandler] + public async Task Index(CancellationToken cancellationToken) + => Render(await Api(api => api.Get(cancellationToken)), "Index"); +} diff --git a/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/UploadController.cs b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/UploadController.cs new file mode 100644 index 000000000..7638a428e --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Controllers/FrontEnd/UploadController.cs @@ -0,0 +1,58 @@ +using System.Threading; +using System.Threading.Tasks; +using BaGet.Frontend.Controllers.Base; +using BaGet.Frontend.Mvc.Attributes; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Models.Upload; +using BaGet.Web.Application.UseCases; + +namespace BaGet.Web.V3.Controllers.FrontEnd; + +/// +/// The NuGet upload page (/upload, /r/{repo}/upload): uploading through the browser in two steps, the first stages +/// the file and shows what it contains (?handler=Stage), the second publishes it (?handler=Submit) or discards it +/// (?handler=Cancel). It replaces the Razor Page Upload: same URLs and forms. The repository rule is +/// : the caller needs the right to publish, and a virtual repository continues in its +/// deploy repository. View: Views/Upload/Index.cshtml. The work is , reached through the JSON twin +/// in process; this controller only renders what it answers. +/// +/// +/// Deliberately not an account controller: those answer 404 while accounts are disabled, and this page must still work there - +/// with a pasted API key, exactly as the push endpoint requires one. Every step is authenticated (session, or API key) by the +/// use case; the antiforgery token is validated by . +/// +[Route("upload")] +[RepositoryPage(Upload = true)] +public sealed class UploadController : UiControllerBase +{ + /// Step one: the form. + [HttpGet, HttpHead, PageHandler] + public async Task Index(string? id) + => Render(await Api(api => api.Get(id)), "Index"); + + /// Stages the chosen file and shows what it contains. + [HttpPost, PageHandler("Stage")] + [UploadSizeLimit] + public async Task Stage(string? id, IFormFile? package, string? apiKey, CancellationToken cancellationToken) + => Render(await Api(api => api.Stage(id, package, apiKey, cancellationToken)), "Index"); + + /// Publishes the staged upload. + [HttpPost, PageHandler("Submit")] + public async Task Submit(string? id, string token, string? apiKey, bool acceptTerms, CancellationToken cancellationToken) + { + var request = new UploadTokenRequest { Token = token ?? string.Empty, ApiKey = apiKey, AcceptTerms = acceptTerms }; + + return Render(await Api(api => api.Submit(id, request, cancellationToken)), "Index"); + } + + /// Discards the staged upload. + [HttpPost, PageHandler("Cancel")] + public async Task Cancel(string? id, string token, string? apiKey, CancellationToken cancellationToken) + { + var request = new UploadTokenRequest { Token = token ?? string.Empty, ApiKey = apiKey }; + + return Render(await Api(api => api.Cancel(id, request, cancellationToken)), "Index"); + } +} diff --git a/src/BaGet.Web.FrontEnd/Extensions/FrontEndServiceCollectionExtensions.cs b/src/BaGet.Web.FrontEnd/Extensions/FrontEndServiceCollectionExtensions.cs new file mode 100644 index 000000000..6a0e43843 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Extensions/FrontEndServiceCollectionExtensions.cs @@ -0,0 +1,40 @@ +using BaGet.Frontend.Routing; +using BaGet.Identity.Controllers.FrontEnd; +using BaGet.Web.V3.Controllers.FrontEnd; +using BaGet.Web.V3.Extensions; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace BaGet; + +/// Registers BaGet's web UI: the view controllers and views, as opposed to the web APIs AddBaGetWebApplication registers. +public static class FrontEndServiceCollectionExtensions +{ + /// + /// Adds the screens of the web UI to a host that called AddBaGetWebApplication: the three front-end assemblies + /// (BaGet.Frontend.Base with the layout and shared partials, BaGet.Identity.FrontEnd and BaGet.Web.FrontEnd) as MVC application + /// parts (a host without the Web SDK has no generated [ApplicationPart] attributes), Razor view support, and the link helpers that keep + /// a page's links inside the repository being browsed. A host that serves only the APIs does not call it and has no screen. + /// + public static IServiceCollection AddBaGetFrontEnd(this IServiceCollection services) + { + // BaGet ships no Razor Page (every screen is a controller action), but a host's own pages (which find BaGet's layout in Views/Shared) keep working, so Razor Pages stays registered. + services.AddRazorPages(); + + services + .AddControllers() + .AddApplicationPartsOnce( + typeof(RepositoryUrlHelper).Assembly, + typeof(AdminUsersController).Assembly, + typeof(HomeController).Assembly); + + // Page links stay inside the repository being browsed (see RepositoryUrlHelper). + services.Replace(ServiceDescriptor.Singleton()); + + // Which controller action is a repository page, so a link to it carries the request's repository. + services.TryAddSingleton(); + + return services; + } +} diff --git a/src/BaGet.Web.FrontEnd/Extensions/RazorExtensions.cs b/src/BaGet.Web.FrontEnd/Extensions/RazorExtensions.cs new file mode 100644 index 000000000..c6ba1707e --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Extensions/RazorExtensions.cs @@ -0,0 +1,11 @@ +using Humanizer; + +namespace BaGet.Web.V3.Extensions; + +public static class RazorExtensions +{ + public static string ToMetric(this long value) + { + return ((double) value).ToMetric(); + } +} \ No newline at end of file diff --git a/src/BaGet.Web.FrontEnd/README.md b/src/BaGet.Web.FrontEnd/README.md new file mode 100644 index 000000000..7f2b1fc4f --- /dev/null +++ b/src/BaGet.Web.FrontEnd/README.md @@ -0,0 +1,37 @@ +# Extension.BaGet.Web.FrontEnd + +The package-browsing **screens** of [BaGet Extension](https://pieroviano.github.io/BaGet/) and the registration of the whole web UI: view controllers and views of the home, +package, statistics, report abuse, upload, legal, API catalog and npm / Maven / Docker browse pages. Each controller calls its JSON twin +(`Extension.BaGet.Web.V3`) in process and renders. A host that serves only the APIs does not reference it. + +```powershell +dotnet add package Extension.BaGet.Web.FrontEnd +``` + +## Usage + +```csharp +builder.Services.AddBaGetWebApplication(ConfigureBaGetApplication); // Extension.BaGet.Web.V3: APIs and protocols +builder.Services.AddBaGetFrontEnd(); // this package: screens, layout, link helpers +``` + +`AddBaGetFrontEnd` adds `Extension.BaGet.Frontend.Base`, `Extension.BaGet.Identity.FrontEnd` and this assembly as MVC application parts (a host without the +Web SDK has no generated `[ApplicationPart]` attributes), keeps Razor Pages registered for a host's own pages, and replaces `IUrlHelperFactory` with `RepositoryUrlHelperFactory` +(links stay inside the repository being browsed). + +## Contents + +| Folder | Role | +|---|---| +| `Controllers/FrontEnd` | `HomeController`, `PackageController`, `StatisticsController`, `ReportAbuseController`, `ApiCatalogController`, `LegalController`, `UploadController`, `NpmBrowseController`, `MavenBrowseController`, `DockerBrowseController` | +| `Views` | One folder per controller; `Views/Shared/_ScanFindings`. The layout and the other shared partials are in `Extension.BaGet.Frontend.Base` | +| `ViewModels` | View models only the screens use (the API catalog's are in `Extension.BaGet.Web.V3`) | +| `Extensions` | `AddBaGetFrontEnd`, `RazorExtensions` | + +## Layout + +One type per file, no nested types, namespace = `BaGet.Web.V3` + folder (`CodeLayoutTests`; `FrontEndServiceCollectionExtensions` stays in `BaGet`). + +## Links + +[Documentation](https://pieroviano.github.io/BaGet/) · [UI API](https://pieroviano.github.io/BaGet/ui-api/) · [Source](https://github.com/pieroviano/BaGet) diff --git a/src/BaGet.Web.FrontEnd/ViewModels/IndexViewModel.cs b/src/BaGet.Web.FrontEnd/ViewModels/IndexViewModel.cs new file mode 100644 index 000000000..970c61b8c --- /dev/null +++ b/src/BaGet.Web.FrontEnd/ViewModels/IndexViewModel.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using BaGet.Core; +using BaGet.Protocol.Models; +using Microsoft.AspNetCore.Mvc; +using BaGet.Web.Application.Models.Browse; +using BaGet.Web.Application.Screens; + +namespace BaGet.Web.V3.ViewModels; + +/// +/// What the front page and the package list show: the search the visitor asked for (bound from the query string, same names +/// as the former Razor Page's properties) and the results the use case found (filled from the screen the JSON twin answered). +/// +public sealed class IndexViewModel +{ + /// The search text (q). + [FromQuery(Name = "q")] + public string? Query { get; set; } + + /// The 1-based page of results (p). + [FromQuery(Name = "p")] + [Range(1, int.MaxValue)] + public int PageIndex { get; set; } = 1; + + /// The package type filter, any for none. + [FromQuery] + public string PackageType { get; set; } = "any"; + + /// The target framework filter, any for none. + [FromQuery] + public string Framework { get; set; } = "any"; + + /// Whether prerelease versions are included. + [FromQuery] + public bool Prerelease { get; set; } = true; + + /// The requested order (sortBy). + [FromQuery(Name = "sortBy")] + public SearchSort SortBy { get; set; } = SearchSort.Relevance; + + /// The orders the search provider can apply on the server; with only the default the page shows no sort control. + public IReadOnlyCollection SupportedSorts { get; internal set; } = new[] { SearchSort.Relevance }; + + /// Whether there is anything to choose among . + public bool CanSort => SupportedSorts.Count > 1; + + /// The page of results. + public IReadOnlyList? Packages { get; internal set; } + + /// True for the site's front page: the root URL with no search. Everything else lists packages. + public bool IsHome { get; internal set; } + + /// The feed's totals, shown on the front page; null when the database cannot report them. + public FeedStatistics? Totals { get; internal set; } + + /// When each listed package ID was last published, by ID; empty when unsupported. + public IReadOnlyDictionary LastUpdated { get; internal set; } = new Dictionary(); + + /// The query of the request, as the use case takes it. + internal IndexQuery ToQuery() => new(Query, PageIndex, PackageType, Framework, Prerelease, SortBy); + + /// Fills this model (which carries the bound query) from what the JSON twin answered. + internal IndexViewModel Fill(IndexScreen screen) + { + SupportedSorts = screen.SupportedSorts; + IsHome = screen.IsHome; + Totals = screen.Totals; + Packages = screen.Packages; + LastUpdated = screen.LastUpdated; + return this; + } +} diff --git a/src/BaGet.Web.FrontEnd/ViewModels/LegalViewModel.cs b/src/BaGet.Web.FrontEnd/ViewModels/LegalViewModel.cs new file mode 100644 index 000000000..1e8e7c449 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/ViewModels/LegalViewModel.cs @@ -0,0 +1,8 @@ +using Microsoft.AspNetCore.Html; + +namespace BaGet.Web.V3.ViewModels; + +/// What a legal page (Terms of Use, Privacy Policy) shows: its heading and the operator's Markdown, rendered safely. +/// The heading and page title. +/// The rendered Markdown file. +public sealed record LegalViewModel(string Title, HtmlString Content); diff --git a/src/BaGet.Web.FrontEnd/ViewModels/PackageVersionRow.cs b/src/BaGet.Web.FrontEnd/ViewModels/PackageVersionRow.cs new file mode 100644 index 000000000..97af8fedd --- /dev/null +++ b/src/BaGet.Web.FrontEnd/ViewModels/PackageVersionRow.cs @@ -0,0 +1,20 @@ +using System; +using NuGet.Versioning; + +namespace BaGet.Web.V3.ViewModels; + +/// One row of the versions table of the package page. +public sealed record PackageVersionRow +{ + /// The version. + public NuGetVersion? Version { get; init; } + + /// Its downloads. + public long Downloads { get; init; } + + /// Whether it is the version shown. + public bool Selected { get; init; } + + /// When it was published. + public DateTime LastUpdated { get; init; } +} diff --git a/src/BaGet.Web.FrontEnd/ViewModels/PackageViewModel.cs b/src/BaGet.Web.FrontEnd/ViewModels/PackageViewModel.cs new file mode 100644 index 000000000..c07a2fde2 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/ViewModels/PackageViewModel.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using BaGet.Core; +using BaGet.Web.V3.Controllers.UI; +using Microsoft.AspNetCore.Html; +using NuGet.Versioning; +using BaGet.Web.Application.Models.Packages; +using BaGet.Web.Application.Screens; +using BaGet.Web.Application.Snippets; + +namespace BaGet.Web.V3.ViewModels; + +/// What the package page shows; filled from the screen the JSON twin answered (). +public sealed class PackageViewModel +{ + /// False when the package (or any listed version of it) does not exist; then only names the ID. + public bool Found { get; internal set; } + + /// The version shown. + public Package? Package { get; internal set; } + + /// The package is a dotnet template. + public bool IsDotnetTemplate { get; internal set; } + + /// The package is a dotnet tool. + public bool IsDotnetTool { get; internal set; } + + /// When any version was last published. + public DateTime LastUpdated { get; internal set; } + + /// Downloads of every version. + public long TotalDownloads { get; internal set; } + + /// The packages that depend on this one. + public IReadOnlyList? UsedBy { get; internal set; } + + /// The dependencies, by framework. + public IReadOnlyList? DependencyGroups { get; internal set; } + + /// The listed versions, newest first. + public IReadOnlyList? Versions { get; internal set; } + + /// The readme, rendered safely. + public HtmlString? Readme { get; internal set; } + + /// The frameworks the package supports, by family. + internal IReadOnlyList FrameworkGroups { get; set; } = Array.Empty(); + /// The install commands, one tab per tool. + internal IReadOnlyList InstallTabs { get; set; } = Array.Empty(); + + /// Owner names; empty unless accounts are enabled and the package has owners. + public IReadOnlyList Owners { get; internal set; } = Array.Empty(); + + /// The avatar address of each owner by name; empty when Gravatar is off or accounts are disabled. + public IReadOnlyDictionary OwnerAvatars { get; internal set; } = new Dictionary(); + + /// + /// The address of the management page when the signed in user may open it (an owner, directly or through an organization, or an + /// administrator), else null and the page offers no link. + /// + public string? ManageUrl { get; internal set; } + + /// The icon address. + public string? IconUrl { get; internal set; } + + /// The license address, null for a license expression or file. + public string? LicenseUrl { get; internal set; } + + /// Where the package file is downloaded. + public string? PackageDownloadUrl { get; internal set; } + + /// + /// This version on nuget.info, the web app of NuGet Package Explorer, as nuget.org links it. nuget.info always downloads from + /// nuget.org, so the link only works for a package that is also published there. + /// + public string? PackageExplorerUrl { get; internal set; } + + /// The model of the view for what the JSON twin answered. The package is a flat copy: only the members the page prints are set. + internal static PackageViewModel From(PackageScreen screen) + { + var details = screen.Package; + return new PackageViewModel + { + Found = screen.Found, + Package = new Package + { + Id = details.Id, + NormalizedVersionString = details.Version, + Description = details.Description, + ReleaseNotes = details.ReleaseNotes, + ProjectUrl = Uri.TryCreate(details.ProjectUrl, UriKind.Absolute, out var project) ? project : null, + RepositoryUrl = Uri.TryCreate(details.RepositoryUrl, UriKind.Absolute, out var source) ? source : null, + Downloads = details.Downloads, + Authors = details.Authors.ToArray(), + }, + IsDotnetTemplate = screen.IsDotnetTemplate, + IsDotnetTool = screen.IsDotnetTool, + LastUpdated = screen.LastUpdated, + TotalDownloads = screen.TotalDownloads, + UsedBy = screen.UsedBy, + DependencyGroups = screen.DependencyGroups, + Versions = screen.Versions + .Select(v => new PackageVersionRow { Version = NuGetVersion.Parse(v.Version), Downloads = v.Downloads, Selected = v.Selected, LastUpdated = v.LastUpdated }) + .ToList(), + Readme = screen.ReadmeHtml == null ? null : new HtmlString(screen.ReadmeHtml), + FrameworkGroups = screen.FrameworkGroups, + InstallTabs = screen.InstallTabs, + Owners = screen.Owners, + OwnerAvatars = screen.OwnerAvatars, + ManageUrl = screen.ManageUrl, + IconUrl = screen.IconUrl, + LicenseUrl = screen.LicenseUrl, + PackageDownloadUrl = screen.PackageDownloadUrl, + PackageExplorerUrl = screen.PackageExplorerUrl, + }; + } +} diff --git a/src/BaGet.Web.FrontEnd/ViewModels/ReportAbuseViewModel.cs b/src/BaGet.Web.FrontEnd/ViewModels/ReportAbuseViewModel.cs new file mode 100644 index 000000000..f31f0f931 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/ViewModels/ReportAbuseViewModel.cs @@ -0,0 +1,40 @@ +using System.ComponentModel.DataAnnotations; +using BaGet.Core; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Web.V3.ViewModels; + +/// The report-abuse form and its outcome. The field names (Reason, Details, ReporterEmail) are the contract of the form. +public sealed class ReportAbuseViewModel +{ + /// The package ID (route). + public string? Id { get; set; } + + /// The package version (route). + public string? Version { get; set; } + + /// One of . + [Required] + public string? Reason { get; set; } + + /// What the reporter saw. + [Required] + [StringLength(AbstractContext.DefaultMaxStringLength)] + public string? Details { get; set; } + + /// The address of the reporter, optional. + [EmailAddress] + [StringLength(AbstractContext.MaxEmailLength)] + [Display(Name = "Your email (optional)")] + public string? ReporterEmail { get; set; } + + /// True once the report was recorded. Never bound from the form (the page's property had a private setter). + [BindNever, ValidateNever] + public bool Submitted { get; set; } + + /// Reports are kept in the database, which Azure Table storage cannot do. + [BindNever, ValidateNever] + public bool CanReport { get; set; } +} diff --git a/src/BaGet.Web.FrontEnd/ViewModels/ScanFindingsView.cs b/src/BaGet.Web.FrontEnd/ViewModels/ScanFindingsView.cs new file mode 100644 index 000000000..eb54b7976 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/ViewModels/ScanFindingsView.cs @@ -0,0 +1,6 @@ +namespace BaGet.Web.V3.ViewModels; + +/// The version whose scan findings the _ScanFindings partial shows on a package page. +/// The artifact name as the format names it (NuGet id, npm name, Maven group:artifact, Docker image). +/// The version (Docker: the manifest digest). +public sealed record ScanFindingsView(string Name, string Version); diff --git a/src/BaGet.Web.FrontEnd/Views/ApiCatalog/Index.cshtml b/src/BaGet.Web.FrontEnd/Views/ApiCatalog/Index.cshtml new file mode 100644 index 000000000..68fbe3818 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Views/ApiCatalog/Index.cshtml @@ -0,0 +1,66 @@ +@* The folder name would make the generated namespace BaGet.Web.V3.ApiCatalog, which hides the ApiCatalog type. *@ +@namespace BaGet.Web.V3.ApiCatalogViews +@model ApiCatalogViewModel +@{ + ViewData["Title"] = "REST API"; +} + +
+

REST API

+ + +

+ Everything on the administration pages can be done over HTTP at @Model.ApiBase, for scripts and + automation. The OpenAPI 3 description is at @Model.OpenApiUrl; the documents of the UI API and of the package protocols are at + /openapi/ui.json and /openapi/protocols.json, and /scalar browses all three (administrators only). +

+ +

Authenticate

+
    +
  • + Send an administrator's API key with the admin:api scope as Authorization: Bearer <key> + (or the key as the Basic password, or X-NuGet-ApiKey). Create one under + API keys; the scope is offered to administrators only, the key must not be limited to + repositories, and it stops working the moment its owner is no longer an administrator. +
  • +
  • Or the server's global ApiKey, when one is configured.
  • +
  • The browser session is never accepted.
  • +
+ +

Confirmation

+

+ Where the page asks for your password again (marked password below), send the key owner's password in + @Model.ConfirmHeader. The global key is its own confirmation. Writes answer + 503 with Retry-After while the server is read-only. Errors are application/problem+json; + lists take ?page= and ?pageSize= (at most 200). +

+ +

Operations

+ + + + + + @foreach (var endpoint in Model.Endpoints) + { + + + + + + + + } + +
MethodPathWhat it doesConfirmationSame on the page
@endpoint.Method@endpoint.Path@endpoint.Summary@(endpoint.Confirm ? "password" : "-") + @{ var link = Url.Action(endpoint.UiScreen.Action, endpoint.UiScreen.Controller); } + @if (link != null) + { + @endpoint.UiScreen.Controller/@endpoint.UiScreen.Action + } + else + { + @endpoint.UiScreen.Controller/@endpoint.UiScreen.Action + } +
+
diff --git a/src/BaGet.Web.FrontEnd/Views/DockerBrowse/Image.cshtml b/src/BaGet.Web.FrontEnd/Views/DockerBrowse/Image.cshtml new file mode 100644 index 000000000..ed1bc1e54 --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Views/DockerBrowse/Image.cshtml @@ -0,0 +1,262 @@ +@model BaGet.Web.Application.Models.Docker.DockerImageViewModel + +@{ + ViewData["Title"] = Model.Image ?? "Docker image"; + ViewData["HideSearchBar"] = true; +} + +@if (Model.Info == null) +{ +
+

Image not found

+ +

+ There is no image @Model.Image in this repository@(Model.IsRemote ? " yet: an image of the upstream is cached the first time it is pulled" : ""). + Browse the images. +

+
+ + return; +} + +@if (Model.Digest != null && Model.Selected == null) +{ +
+

Manifest not found

+ +

The image @Model.Info.Name has no manifest @Model.Digest.

+
+ + return; +} + +@{ + var info = Model.Info; + var selected = Model.Selected; +} + +
+

+ @info.Name + @if (selected != null) + { + manifest @selected.Summary.Digest.Substring(0, 19) + } +

+ + +

+ @info.Tags.Count tag@(info.Tags.Count == 1 ? "" : "s"), + @info.Manifests.Count manifest@(info.Manifests.Count == 1 ? "" : "s"), + @info.Size.ToString("N0") bytes stored, + updated @info.Modified.Humanize(). + @if (Model.CanManage) + { + Manage + } +

+ + @if (selected != null && !selected.Summary.IsIndex) + { + + } + + @if (selected == null) + { +

Tags

+ @if (info.Tags.Count == 0) + { +

No tag. @(Model.IsRemote ? "Pull one through this repository to cache it." : "Push one with docker push.")

+ } + else + { + + + + @foreach (var tag in info.Tags) + { + + + + + + } + +
TagManifestUpdated
@tag.Name@tag.Digest.Substring(0, 19)...@tag.Updated.Humanize()
+ } + +

Manifests

+ + + + @foreach (var manifest in info.Manifests) + { + + + + + + + + + } + +
DigestTypePlatformTagsLayersSize
@manifest.Digest.Substring(0, 19)...@(manifest.IsIndex ? "index (multi-platform)" : manifest.ArtifactType != null && !manifest.ArtifactType.Contains("image.config") ? manifest.ArtifactType : "image")@(manifest.Platform ?? "")@string.Join(", ", manifest.Tags)@(manifest.IsIndex ? "" : manifest.LayerCount.ToString())@(manifest.IsIndex ? "" : manifest.ContentSize.ToString("N0") + " bytes")
+ + @if (info.UnreferencedBlobs > 0) + { +

@info.UnreferencedBlobs layer@(info.UnreferencedBlobs == 1 ? "" : "s") of this image are used by no manifest.

+ } + } + else + { +

Manifest

+ + + + + + @if (selected.Summary.Platform != null) + { + + } + @if (selected.Summary.ArtifactType != null) + { + + } + @if (selected.Summary.SubjectDigest != null) + { + + } + + + +
Digest@selected.Summary.Digest
Media type@selected.Summary.MediaType
Size@selected.Summary.Size.ToString("N0") bytes
Platform@selected.Summary.Platform
Artifact type@selected.Summary.ArtifactType
Subject@selected.Summary.SubjectDigest
Tags@(selected.Summary.Tags.Count == 0 ? "none" : string.Join(", ", selected.Summary.Tags))
Pushed@selected.Summary.Created.Humanize()
+ + @if (Model.Referrers.Count > 0 || !string.IsNullOrWhiteSpace(Model.ArtifactType)) + { +

Referrers

+
+ + + + @if (!string.IsNullOrWhiteSpace(Model.ArtifactType)) + { + Clear + } +
+ } + @if (Model.Referrers.Count > 0) + { + + + + @foreach (var referrer in Model.Referrers) + { + + + + + + } + +
ManifestArtifact typeSize
@referrer.Digest.Substring(0, 19)...@(referrer.ArtifactType ?? referrer.MediaType)@referrer.Size.ToString("N0") bytes
+ } + + @if (selected.Platforms.Count > 0) + { +

Platforms

+ + + + @foreach (var platform in selected.Platforms) + { + + + + + + } + +
PlatformManifestSize
@platform.Platform + @if (platform.Present) + { + @platform.Digest.Substring(0, 19)... + } + else + { + @platform.Digest.Substring(0, 19)... (not in this image) + } + @platform.Size.ToString("N0") bytes
+ } + + @if (selected.Config != null) + { +

Config and layers

+ + + + + + + + + + @for (var i = 0; i < selected.Layers.Count; i++) + { + var layer = selected.Layers[i]; + + + + + + + } + + + + +
#DigestTypeSize
config@selected.Config.Digest@selected.Config.MediaType@selected.Config.Size.ToString("N0") bytes
@(i + 1)@layer.Digest@layer.MediaType@layer.Size.ToString("N0") bytes
Total (config and layers)@selected.Summary.ContentSize.ToString("N0") bytes
+ } + + @if (selected.Annotations.Count > 0) + { +

Annotations

+ + + @foreach (var annotation in selected.Annotations) + { + + } + +
@annotation.Key@annotation.Value
+ } + +

Document

+
@selected.Json
+ } + +

@(Model.IsRemote ? "Pull" : "Pull and push")

+
+ + + @for (var i = 0; i < Model.PullTabs.Count; i++) + { + var snippet = Model.PullTabs[i]; + +
+
+
@string.Join("\n", snippet.Lines ?? [])
+
+
+ } +
+

Registry API: @Model.RegistryUrl

+
diff --git a/src/BaGet.Web.FrontEnd/Views/DockerBrowse/Images.cshtml b/src/BaGet.Web.FrontEnd/Views/DockerBrowse/Images.cshtml new file mode 100644 index 000000000..bdb3cfd0b --- /dev/null +++ b/src/BaGet.Web.FrontEnd/Views/DockerBrowse/Images.cshtml @@ -0,0 +1,124 @@ +@model BaGet.Web.Application.Models.Docker.DockerImagesViewModel + +@{ + ViewData["Title"] = "Docker images"; + ViewData["HideSearchBar"] = true; +} + +
+

Docker images

+ + + + +

+ Registry: @Model.Host/@Model.RepositoryName + · @(Model.IsRemote ? "pull through it with the Docker CLI (see below); what is pulled is cached here." : "push and pull with the Docker CLI (see below).") +

+ + @if (Model.Result.Images.Count == 0) + { +
+

Oops, nothing here...

+

+ @(string.IsNullOrWhiteSpace(Model.Query) ? (Model.IsRemote ? "This repository has cached no image yet." : "This repository holds no image yet.") : "No image matches that text.") + @if (Model.IsRemote) + { + Pull one through it with docker pull (see below); the upstream's images are cached the first time they are pulled. + } + else + { + Push one with docker push (see below). + } +

+
+ } + else + { +

@Model.Result.Total image@(Model.Result.Total == 1 ? "" : "s")

+ +
+ @foreach (var image in Model.Result.Images) + { +
+
+ +
    +
  • @image.Tags tag@(image.Tags == 1 ? "" : "s")
  • +
  • @image.Manifests manifest@(image.Manifests == 1 ? "" : "s")
  • +
  • @image.Size.ToString("N0") bytes
  • +
  • + + Last updated @image.Modified.Humanize() + +
  • +
+
+
+ } +
+ + @if (Model.PageIndex > 1 || Model.HasNext) + { + + } + } + +

With the Docker CLI

+ @if (Model.IsRemote) + { +

This repository caches an upstream registry: it takes no pushes. Manifests and layers are fetched from the upstream when first pulled and served from here afterwards.

+ } + else if (Model.IsVirtual) + { +

This repository merges other repositories: a pull is answered by the first member, in order, that has the image; a push goes to its deploy repository.

+ } + +

+ Sign in with your user name and an API key as the password (create one); Docker then asks the registry for a short-lived token for each image. The image name starts with the repository (@Model.RepositoryName). +

+
+ + + @for (var i = 0; i < Model.CommandTabs.Count; i++) + { + var snippet = Model.CommandTabs[i]; + +
+
+
@string.Join("\n", snippet.Lines ?? [])
+
+
+ } +
+
diff --git a/src/BaGet.Web/Pages/Index.cshtml b/src/BaGet.Web.FrontEnd/Views/Home/Index.cshtml similarity index 55% rename from src/BaGet.Web/Pages/Index.cshtml rename to src/BaGet.Web.FrontEnd/Views/Home/Index.cshtml index 303e1c0c5..0818efab9 100644 --- a/src/BaGet.Web/Pages/Index.cshtml +++ b/src/BaGet.Web.FrontEnd/Views/Home/Index.cshtml @@ -1,10 +1,11 @@ -@page -@using BaGet.Protocol.Models -@model IndexModel +@model IndexViewModel +@inject Microsoft.Extensions.Options.IOptions Accounts +@inject BaGet.Core.IUrlGenerator Autocomplete @{ - ViewData["Title"] = "Packages"; + ViewData["Title"] = Model.IsHome ? "Home" : "Packages"; ViewData["SearchQuery"] = Model.Query; + ViewData["HideSearchBar"] = Model.IsHome; } @section SearchForm @@ -25,6 +26,52 @@ { } + + @if (Model.CanSort && Model.SortBy != SearchSort.Relevance) + { + + } +} + +@if (Model.IsHome) +{ +
+

Find and share packages

+ + +
+ + @if (Model.Totals != null) + { +
+
@Model.Totals.PackageIds.ToString("N0")
packages
+
@Model.Totals.PackageVersions.ToString("N0")
package versions
+
@Model.Totals.Downloads.ToString("N0")
downloads
+
+ } + + return; }
@@ -77,6 +124,28 @@
+ @if (Model.CanSort) + { +
+ + +
+ +
+
+ } +
@@ -88,38 +157,62 @@
-@if (Model.Packages.Count == 0) +@if ((Model.Packages?.Count ?? 0) == 0) {

Oops, nothing here...

It looks like there's no package here to see. Take a look below for useful links.

-

Upload a package

-

BaGet documentation

+

Upload a package

+

BaGet Extension documentation

BaGet issues

} else { - @foreach (var package in Model.Packages) +
+ @foreach (var package in Model.Packages??[]) { -
-